niti: fix type in tool description
[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
20 # A thin wrapper around a `NativeCArray` adding length information
21 abstract class CArray[E]
22 super AbstractArrayRead[E]
23
24 private init(length: Int) do self._length = length
25 end
26
27 # A native C array, as in a pointer to the first element of the array
28 extern class NativeCArray `{ void * `}
29 type E: nullable Object
30 type SELF: NativeCArray
31
32 fun [](index: E): E is abstract
33 fun []=(index: E, val: E) is abstract
34
35 # Return pointer to the address to the second element of this array
36 #
37 # This is the standard `+` operator on pointers in C
38 fun +(offset: Int): SELF is abstract
39 end
40
41 # Wrapper around an array of `int` in C (`int*`) with length and destroy state
42 class CIntArray
43 super CArray[Int]
44
45 var native_array: NativeCIntArray
46 init(size: Int)
47 do
48 native_array = new NativeCIntArray(size)
49 super size
50 end
51
52 redef fun [](index)
53 do
54 assert not destroyed
55 assert index >= 0 and index < length
56 return native_array[index]
57 end
58
59 fun []=(index: Int, val: Int)
60 do
61 assert not destroyed
62 assert index >= 0 and index < length
63 native_array[index] = val
64 end
65
66 var destroyed = false
67 fun destroy
68 do
69 if destroyed then return
70
71 native_array.free
72 destroyed = true
73 end
74 end
75
76 # An array of `int` in C (`int*`)
77 extern class NativeCIntArray `{ int* `}
78 super NativeCArray
79 redef type E: Int
80 redef type SELF: NativeCIntArray
81
82 new(size: Int) `{ return calloc(size, sizeof(int)); `}
83 redef fun [](index) `{ return recv[index]; `}
84 redef fun []=(index, val) `{ recv[index] = val; `}
85
86 redef fun +(offset) `{ return recv + offset; `}
87 end
88
89 redef class NativeString
90 super NativeCArray
91 redef type E: Char
92 redef type SELF: NativeString
93
94 redef fun +(offset) `{ return recv + offset; `}
95 end