raz / conform / run / Ptr.raz

66 lines · 1.8 KiB · raw · history · last change 264716cb

1(* SYSTEM.PTR(s), the address a slice starts at (report section 6.8): SYSTEM.ADR(s[0])
2 when s isn't empty; nil for a slice as it starts and for []; and, of
3 an array, the address of its first element. *)
4module Ptr;
5import Out;
6import SYSTEM;
7
8type Value = record n: INT; p: ^U8; end;
9
10const Digits: [4]INT = [1, 2, 3, 4];
11
12var kept: []U8;
13
14(* a slice as a pointer and a length, with no test for the empty one *)
15proc valueOf(s: []U8): Value;
16begin
17 return {n: LEN(s), p: SYSTEM.PTR(s)};
18end;
19
20(* and back: empty when n is 0, whatever p is *)
21proc bytes(v: Value): []U8;
22begin
23 return v.p[0..v.n];
24end;
25
26proc same(s: []U8): []U8;
27begin
28 return s;
29end;
30
31proc first(const a: [3]I64): ^I64;
32begin
33 return SYSTEM.PTR(a);
34end;
35
36proc main*;
37var
38 a: [6]U8; s, none: []U8; v: Value; w: [3]I64; ws: []I64; q: ^I64;
39 d: ^INT; i: INT;
40begin
41 a := [104, 101, 108, 108, 111, 10];
42 s := a[0..6];
43 Out.str(bytes(valueOf(s)));
44 Out.str(bytes(valueOf(s[1..3]))); Out.str("\n");
45 if SYSTEM.PTR(s) = SYSTEM.ADR(s[0]) then Out.str("a slice: ADR(s[0])\n"); end;
46 if SYSTEM.PTR(a) = SYSTEM.ADR(a[0]) then Out.str("an array: ADR(a[0])\n"); end;
47 if SYSTEM.PTR(s[2..5]) = SYSTEM.ADR(a[2]) then Out.str("a slice of it: ADR(a[2])\n"); end;
48 if SYSTEM.PTR(same(s)) = SYSTEM.ADR(a[0]) then Out.str("a call's slice\n"); end;
49 v := valueOf(none);
50 if v.p = nil then Out.str("a slice as it starts: nil\n"); end;
51 v := valueOf([]);
52 if v.p = nil then Out.str("[]: nil\n"); end;
53 Out.int(LEN(bytes(v))); Out.str(" bytes back\n");
54 kept := s[3..5];
55 Out.str(SYSTEM.PTR(kept)[0..2]); Out.str("\n");
56 w := [10, 20, 30];
57 if first(w) = SYSTEM.ADR(w[0]) then Out.str("a const parameter: in place\n"); end;
58 ws := w[0..3];
59 q := SYSTEM.PTR(ws);
60 for i := 0 to 2 do Out.int(q[i]); Out.str(" "); end;
61 Out.str("\n");
62 d := SYSTEM.PTR(Digits);
63 Out.int(d[3]); Out.str("\n");
64end;
65
66end Ptr.