-
Notifications
You must be signed in to change notification settings - Fork 34
/
main.clay
127 lines (104 loc) · 2.68 KB
/
main.clay
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
import printer.(print,println);
import data.vectors.*;
//
// Opaque
//
alias Opaque = Int;
//
// display
//
define display;
overload display(x) {
print(x);
}
[T]
overload display(a:Vector[T]) {
print("[");
for (i in range(size(a))) {
if (i != 0)
print(", ");
display(a[i]);
}
print("]");
}
//
// Displayable
//
record Displayable (
obj : Pointer[Opaque],
size : SizeT,
alignment : SizeT,
destructor : CodePointer[[Opaque],[]],
copyConstructor : CodePointer[[Opaque],[Opaque]],
display : CodePointer[[Opaque],[]],
);
overload RegularRecord?(#Displayable) = false;
// primary constructor
[T]
overload Displayable(x:T) {
var obj = allocateRawMemoryAligned(T, 1, TypeAlignment(T));
obj^ <-- x;
var destructor = makeCodePointer(destroy, T);
var copyConstructor = makeCodePointer(T, T);
var displayPtr = makeCodePointer(display, T);
return Displayable(Pointer[Opaque](obj),
TypeSize(T),
TypeAlignment(T),
CodePointer[[Opaque],[]](destructor),
CodePointer[[Opaque],[Opaque]](copyConstructor),
CodePointer[[Opaque],[]](displayPtr));
}
// default constructor
overload Displayable() {
return Displayable(null(Opaque), SizeT(0), SizeT(0),
CodePointer[[Opaque],[]](0),
CodePointer[[Opaque],[Opaque]](0),
CodePointer[[Opaque],[]](0));
}
// copy constructor
overload Displayable(x:Displayable) {
var p = allocateRawMemoryAligned(Int8, x.size, x.alignment);
var obj = Pointer[Opaque](p);
obj^ <-- x.copyConstructor(x.obj^);
return Displayable(obj, x.size, x.alignment,
x.destructor, x.copyConstructor, x.display);
}
// moveUnsafe
overload moveUnsafe(src:Displayable) --> returned:Displayable {
returned <-- Displayable(
src.obj,
src.size,
src.alignment,
src.destructor,
src.copyConstructor,
src.display
);
}
// resetUnsafe
overload resetUnsafe(x:Displayable) {
x <-- Displayable();
}
// destructor
overload destroy(x:Displayable) {
if (not null?(x.obj)) {
x.destructor(x.obj^);
freeRawMemoryAligned(x.obj);
}
}
overload assign(dest:Displayable, ref src:Displayable) {
dest = copy(src);
}
overload display(x:Displayable) {
x.display(x.obj^);
}
displayln(x) { display(x); println(); }
main() {
var v = Vector[Displayable]();
push(v, Displayable(1));
push(v, Displayable(3.2));
push(v, Displayable("Hi!"));
for (i in range(3))
push(v, Displayable(v));
for (x in v)
displayln(x);
}