1 ! (c)2009 Slava Pestov, Joe Groff bsd license
2 USING: accessors alien alien.c-types alien.strings arrays
3 byte-arrays cpu.architecture fry io io.encodings.binary
4 io.files io.streams.memory kernel libc math sequences ;
7 GENERIC: require-c-array ( c-type -- )
9 M: array require-c-array first require-c-array ;
11 GENERIC: c-array-constructor ( c-type -- word )
13 GENERIC: c-(array)-constructor ( c-type -- word )
15 GENERIC: c-direct-array-constructor ( c-type -- word )
17 GENERIC: <c-array> ( len c-type -- array )
19 M: c-type-name <c-array>
20 c-array-constructor execute( len -- array ) ; inline
22 GENERIC: (c-array) ( len c-type -- array )
24 M: c-type-name (c-array)
25 c-(array)-constructor execute( len -- array ) ; inline
27 GENERIC: <c-direct-array> ( alien len c-type -- array )
29 M: c-type-name <c-direct-array>
30 c-direct-array-constructor execute( alien len -- array ) ; inline
32 : malloc-array ( n type -- array )
33 [ heap-size calloc ] [ <c-direct-array> ] 2bi ; inline
35 : (malloc-array) ( n type -- alien )
36 [ heap-size * malloc ] [ <c-direct-array> ] 2bi ; inline
38 : <c-object> ( type -- array )
39 heap-size <byte-array> ; inline
41 : (c-object) ( type -- array )
42 heap-size (byte-array) ; inline
44 : malloc-object ( type -- alien )
45 1 swap heap-size calloc ; inline
47 : (malloc-object) ( type -- alien )
48 heap-size malloc ; inline
50 : malloc-byte-array ( byte-array -- alien )
51 dup byte-length [ nip malloc dup ] 2keep memcpy ;
53 : memory>byte-array ( alien len -- byte-array )
54 [ nip (byte-array) dup ] 2keep memcpy ;
56 : malloc-string ( string encoding -- alien )
57 string>alien malloc-byte-array ;
59 : malloc-file-contents ( path -- alien len )
60 binary file-contents [ malloc-byte-array ] [ length ] bi ;
62 M: memory-stream stream-read
64 [ index>> ] [ alien>> ] bi <displaced-alien>
65 swap memory>byte-array
66 ] [ [ + ] change-index drop ] 2bi ;
68 : byte-array>memory ( byte-array base -- )
69 swap dup byte-length memcpy ; inline
71 : >c-bool ( ? -- int ) 1 0 ? ; inline
73 : c-bool> ( int -- ? ) 0 = not ; inline
75 M: value-type c-type-rep drop int-rep ;
77 M: value-type c-type-getter
78 drop [ swap <displaced-alien> ] ;
80 M: value-type c-type-setter ( type -- quot )
81 [ c-type-getter ] [ c-type-unboxer-quot ] [ heap-size ] tri
82 '[ @ swap @ _ memcpy ] ;