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 words ;
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 ) foldable
13 GENERIC: c-(array)-constructor ( c-type -- word ) foldable
15 GENERIC: c-direct-array-constructor ( c-type -- word ) foldable
17 GENERIC: <c-array> ( len c-type -- array )
20 c-array-constructor execute( len -- array ) ; inline
22 GENERIC: (c-array) ( len c-type -- array )
25 c-(array)-constructor execute( len -- array ) ; inline
27 GENERIC: <c-direct-array> ( alien len c-type -- array )
29 M: word <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 M: memory-stream stream-read
61 [ index>> ] [ alien>> ] bi <displaced-alien>
62 swap memory>byte-array
63 ] [ [ + ] change-index drop ] 2bi ;
65 : byte-array>memory ( byte-array base -- )
66 swap dup byte-length memcpy ; inline
68 : >c-bool ( ? -- int ) 1 0 ? ; inline
70 : c-bool> ( int -- ? ) 0 = not ; inline
72 M: value-type c-type-rep drop int-rep ;
74 M: value-type c-type-getter
75 drop [ swap <displaced-alien> ] ;
77 M: value-type c-type-setter ( type -- quot )
78 [ c-type-getter ] [ c-type-unboxer-quot ] [ heap-size ] tri
79 '[ @ swap @ _ memcpy ] ;