Set · lesson 7 of 15

Records and pointers

Boxes.raz
module Boxes;
import Fmt;

type
    Point = record x, y: INT; end;
    Box = record lo, hi: Point; end;

proc area(b: Box): INT;
begin
    return (b.hi.x - b.lo.x) * (b.hi.y - b.lo.y);
end;

proc grow(b: ^Box; n: INT);
begin
    DEC(b^.lo.x, n);
    DEC(b^.lo.y, n);
    INC(b^.hi.x, n);
    INC(b^.hi.y, n);
end;

proc main*;
var b: Box; p: ^Point;
begin
    b := {lo: {x: 1, y: 1}, hi: {x: 4, y: 3}};
    Fmt.print("{}\n", [Fmt.int(area(b))]);
    grow(ADR(b), 1);
    p := ADR(b.hi);
    p^.x := 10;
    Fmt.print("{} {}\n", [Fmt.int(area(b)), Fmt.int(b.hi.x)]);
end;

end Boxes.
6
40 10

A record is laid out as C lays out a struct. {lo: ..., hi: ...} builds one, naming its fields; the ones it leaves out are zero. ^Box is a pointer to a Box, ADR(b) the address of b, and b^ what a pointer points at. A pointer is never the record: it is b^.lo, never b.lo, so you always see where the memory is reached through an address.

Copies and literals

Assigning a record copies it whole, as with an array. A record is compared field by field by writing the comparison, not by =.

Points.raz
module Points;
import Out;

type Point = record x, y: INT; end;

proc show(p: Point);
begin
    Out.char('('); Out.int(p.x); Out.str(", "); Out.int(p.y); Out.char(')');
end;

proc mirror(p: Point): Point;
begin
    return {x: p.y, y: p.x};
end;

proc main*;
var a, b: Point;
begin
    a := {x: 3, y: 4};
    b := a;                  (* a copy *)
    b.x := 30;
    show(a); show(b); show(mirror(a)); Out.ln;
    a := {y: 9};             (* x is zero *)
    show(a); Out.ln;
end;

end Points.
(3, 4)(30, 4)(4, 3)
(0, 9)

Tables of constants

A constant may be a record, or an array of them: a table the program reads but can't change. Its fields are integers, reals, BOOLs, strings, procedures and the like, and arrays and records of these.

Planets.raz
module Planets;
import Fmt;

type Planet = record name: []U8; moons: INT; water: BOOL; end;

const Inner: []Planet = [
    {name: "Mercury"},
    {name: "Venus"},
    {name: "Earth", moons: 1, water: true},
    {name: "Mars", moons: 2}];

proc main*;
var i, total: INT;
begin
    for i := 0 to LEN(Inner) - 1 do
        total := total + Inner[i].moons;
        if Inner[i].moons = 0 then Fmt.print("{} has no moon\n", [Fmt.str(Inner[i].name)]); end;
    end;
    Fmt.print("{} moons in all\n", [Fmt.int(total)]);
end;

end Planets.
Mercury has no moon
Venus has no moon
3 moons in all

Fields left out are zero, as in any literal: Mercury's moons is 0 and its water is false. A constant typed []Planet takes its length from its literal, here 4, so a planet added to the list needs no count changed.

Layout

A record's layout is C's: each field at the next multiple of its own alignment, and the whole padded to a multiple of its largest alignment. SIZE(T) says how many bytes. A packed record has no padding, which is what a file format or a wire protocol wants.

Layout.raz
module Layout;
import Out;

type
    Loose = record a: U8; b: U32; c: U8; end;
    Tight = packed record a: U8; b: U32; c: U8; end;

proc main*;
begin
    Out.str("loose: "); Out.int(SIZE(Loose)); Out.ln;     (* 12 *)
    Out.str("tight: "); Out.int(SIZE(Tight)); Out.ln;     (* 6 *)
    Out.str("INT:   "); Out.int(SIZE(INT)); Out.ln;
    Out.str("[5]I16: "); Out.int(SIZE([5]I16)); Out.ln;
end;

end Layout.
loose: 12
tight: 6
INT:   8
[5]I16: 10

A field of a packed record may sit at any address, and is read and written like any other; but it has no address of its own to take with ADR.

Bytes as numbers and records: views

A file, a socket or a device hands a program bytes. A view reads and writes them as another type: msg[3].(U32) is the U32 whose four bytes start at msg[3], and msg[0].(Head) the Head whose bytes start at msg[0].

Wire.raz
module Wire;
import Out;

type Head = packed record magic: U16; kind: U8; len: U32; end;   (* 7 bytes, as sent *)

var msg: [32]U8;

proc main*;
var h: Head; i: INT; sum: I64;
begin
    (* what a socket might have handed us *)
    msg[0] := 52H; msg[1] := 5AH;
    msg[2] := 1;
    msg[3].(U32) := 8;
    msg[7].(I32) := 100;
    msg[11].(I32) := 200;

    h := msg[0].(Head);
    Out.hex(U64(h.magic), 4); Out.char(' ');
    Out.int(I64(h.kind)); Out.char(' ');
    Out.int(I64(h.len)); Out.ln;
    sum := 0;
    i := 7;
    while i < 7 + INT(h.len) do
        sum := sum + I64(msg[i].(I32));
        i := i + 4;
    end;
    Out.int(sum); Out.ln;
end;

end Wire.
5A52 1 8
300

A view isn't a copy: it *is* those bytes, so msg[3].(U32) := 8 writes msg[3] to msg[6], and a view goes wherever a variable does, with a field after it, in INC, on the left of :=. Nor is it a conversion: I64(x) is a real's number, x.(U64) its bits. The magic number reads 5A52, its bytes backwards, because x86-64 keeps a number's low byte first; a format with an order of its own is read with Str.le or Str.be.

A view of an element must end inside the array, and the program checks it as it checks an index:

Short.raz
module Short;
import Out;

var msg: [10]U8;

proc main*;
var i: INT;
begin
    i := 0;
    while i < LEN(msg) do
        Out.int(I64(msg[i].(U32))); Out.char(' ');
        i := i + 4;
    end;
end;

end Short.
0 0 Short.raz:11:25: a view at index 8 runs past a length of 10
  in Short.main at Short.raz:11:25: i = 8

The type of a view is an integer, a real or a pointer, or a record or array made of them: types any bytes are a value of, which a BOOL or an enumeration isn't. A view may start at any byte, so, as a packed record's field, it has no address of its own.

Pointers

ADR(x) takes the address of a variable, ^T is a pointer to a T, and p^ is what it points at. A pointer that points nowhere is nil, and following it stops the program with a message that names the place, so a forgotten check is found at once instead of corrupting memory.

Pointers.raz
module Pointers;
import Out;

type Counter = record hits: INT; name: []U8; end;

proc hit(c: ^Counter);
begin
    if c = nil then return; end;
    INC(c^.hits);
end;

proc swap(a, b: ^INT);
var t: INT;
begin
    t := a^;
    a^ := b^;
    b^ := t;
end;

proc main*;
var c: Counter; x, y: INT; p: ^INT;
begin
    c.name := "front door";
    hit(ADR(c)); hit(ADR(c)); hit(nil);
    Out.str(c.name); Out.str(": "); Out.int(c.hits); Out.ln;
    x := 1; y := 2;
    swap(ADR(x), ADR(y));
    Out.int(x); Out.char(' '); Out.int(y); Out.ln;
    p := ADR(x);
    p^ := p^ + 40;
    Out.int(x); Out.ln;
end;

end Pointers.
front door: 2
2 1
42

Pointers that link

A record may hold a pointer to its own type, which is how lists and trees are made. Memory for them comes from an allocator, which is the next lesson; here the nodes simply live in an array.

Chain.raz
module Chain;
import Out;

type Node = record next: ^Node; val: INT; end;

proc main*;
var nodes: [4]Node; head, n: ^Node; i: INT;
begin
    head := nil;
    for i := 0 to 3 do
        nodes[i].val := (i + 1) * 10;
        nodes[i].next := head;       (* each new one in front *)
        head := ADR(nodes[i]);
    end;
    n := head;
    while n # nil do
        Out.int(n^.val); Out.char(' ');
        n := n^.next;
    end;
    Out.ln;
end;

end Chain.
40 30 20 10 

Save a program under its module’s name and run it with raz run Name.raz.