| 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. *) |
| 4 | module Ptr; |
| 5 | import Out; |
| 6 | import SYSTEM; |
| 7 | |
| 8 | type Value = record n: INT; p: ^U8; end; |
| 9 | |
| 10 | const Digits: [4]INT = [1, 2, 3, 4]; |
| 11 | |
| 12 | var kept: []U8; |
| 13 | |
| 14 | (* a slice as a pointer and a length, with no test for the empty one *) |
| 15 | proc valueOf(s: []U8): Value; |
| 16 | begin |
| 17 | return {n: LEN(s), p: SYSTEM.PTR(s)}; |
| 18 | end; |
| 19 | |
| 20 | (* and back: empty when n is 0, whatever p is *) |
| 21 | proc bytes(v: Value): []U8; |
| 22 | begin |
| 23 | return v.p[0..v.n]; |
| 24 | end; |
| 25 | |
| 26 | proc same(s: []U8): []U8; |
| 27 | begin |
| 28 | return s; |
| 29 | end; |
| 30 | |
| 31 | proc first(const a: [3]I64): ^I64; |
| 32 | begin |
| 33 | return SYSTEM.PTR(a); |
| 34 | end; |
| 35 | |
| 36 | proc main*; |
| 37 | var |
| 38 | a: [6]U8; s, none: []U8; v: Value; w: [3]I64; ws: []I64; q: ^I64; |
| 39 | d: ^INT; i: INT; |
| 40 | begin |
| 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"); |
| 64 | end; |
| 65 | |
| 66 | end Ptr. |