neo: Correct the documentation of neo.nit according to PR #734.
[nit.git] / lib / c.nit
1 # This file is part of NIT (http://www.nitlanguage.org).
2 #
3 # Copyright 2014 Alexis Laferrière <alexis.laf@xymus.net>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # Utilities and performant structure for the FFI with C
18 module c
19 import standard
20 intrude import standard::collection::array
21
22 # A thin wrapper around a `NativeCArray` adding length information
23 abstract class CArray[E]
24 super AbstractArrayRead[E]
25
26 private init(length: Int) do self._length = length
27 end
28
29 # A native C array, as in a pointer to the first element of the array
30 extern class NativeCArray `{ void * `}
31 type E: nullable Object
32 type SELF: NativeCArray
33
34 fun [](index: E): E is abstract
35 fun []=(index: E, val: E) is abstract
36
37 # Return pointer to the address to the second element of this array
38 #
39 # This is the standard `+` operator on pointers in C
40 fun +(offset: Int): SELF is abstract
41 end
42
43 # Wrapper around an array of `int` in C (`int*`) with length and destroy state
44 class CIntArray
45 super CArray[Int]
46
47 var native_array: NativeCIntArray
48 init(size: Int)
49 do
50 native_array = new NativeCIntArray(size)
51 super size
52 end
53
54 redef fun [](index)
55 do
56 assert not destroyed
57 assert index >= 0 and index < length
58 return native_array[index]
59 end
60
61 fun []=(index: Int, val: Int)
62 do
63 assert not destroyed
64 assert index >= 0 and index < length
65 native_array[index] = val
66 end
67
68 var destroyed = false
69 fun destroy
70 do
71 if destroyed then return
72
73 native_array.free
74 destroyed = true
75 end
76 end
77
78 # An array of `int` in C (`int*`)
79 extern class NativeCIntArray `{ int* `}
80 super NativeCArray
81 redef type E: Int
82 redef type SELF: NativeCIntArray
83
84 new(size: Int) `{ return calloc(size, sizeof(int)); `}
85 redef fun [](index) `{ return recv[index]; `}
86 redef fun []=(index, val) `{ recv[index] = val; `}
87
88 redef fun +(offset) `{ return recv + offset; `}
89 end
90
91 redef class NativeString
92 super NativeCArray
93 redef type E: Char
94 redef type SELF: NativeString
95
96 redef fun +(offset) `{ return recv + offset; `}
97 end