-
Notifications
You must be signed in to change notification settings - Fork 4
/
strings.plk
56 lines (49 loc) · 1.16 KB
/
strings.plk
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
// a short example of small, stack alocated strings
struct Quad<A> { a: A, b: A, c: A, d: A }
// use quads to make string 64 bytes sized
struct String { data: Quad<Quad<Quad<u8>>> }
fn from_u8_ptr(ptr: *u8) -> String {
let data = Quad(0, 0, 0, 0);
let data = Quad(data, data, data, data);
let data = Quad(data, data, data, data);
let str = String(data);
strcpy(
from: ptr,
to: &str as _,
);
return str;
}
fn strcpy(mut to: *mut u8, mut from: *u8) {
while *from != 0 {
*to = *from;
to = (to as _ + 1) as _;
from = (from as _ + 1) as _;
}
*to = 0;
}
fn append(to: *mut String, str: String) {
let mut ptr = to as *mut u8;
while *ptr != 0 {
ptr = (ptr as _ + 1) as _;
}
strcpy(
from: &str as _,
to: ptr,
);
}
fn print(str: String) {
let mut ptr = &str as _;
while *ptr != 0 {
putc(*ptr);
ptr = (ptr as _ + 1) as _;
}
}
fn main() -> i32 {
let mut a = from_u8_ptr("Stack ");
let b = from_u8_ptr("allocated ");
let c = from_u8_ptr("strings!\n");
append(&mut a, b);
append(&mut a, c);
print(a);
return 0;
}