doc: Fix the presentation of the inner classes.
[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
33 fun [](index: E): E is abstract
34 fun []=(index: E, val: E) is abstract
35
36 # Return pointer to the address to the second element of this array
37 #
38 # This is the standard `+` operator on pointers in C
39 fun +(offset: Int): SELF is abstract
40 end
41
42 # Wrapper around an array of `int` in C (`int*`) with length and destroy state
43 class CIntArray
44 super CArray[Int]
45
46 var native_array: NativeCIntArray
47 init(size: Int)
48 do
49 native_array = new NativeCIntArray(size)
50 super size
51 end
52
53 redef fun [](index)
54 do
55 assert not destroyed
56 assert index >= 0 and index < length
57 return native_array[index]
58 end
59
60 fun []=(index: Int, val: Int)
61 do
62 assert not destroyed
63 assert index >= 0 and index < length
64 native_array[index] = val
65 end
66
67 var destroyed = false
68 fun destroy
69 do
70 if destroyed then return
71
72 native_array.free
73 destroyed = true
74 end
75 end
76
77 # An array of `int` in C (`int*`)
78 extern class NativeCIntArray `{ int* `}
79 super NativeCArray
80 redef type E: Int
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
93 redef fun +(offset) `{ return recv + offset; `}
94 end