Types, patterns and valuesSlide 31 of 86
31<<<>>>Types, patterns and values

Bits and bytes

Grammar: bit-expr, bits-lit, bit-part, bits-pattern, bit-field
add-expr&|^<<>>add-expr
bit-expr = add-expr { ( "&" | "|" | "^" | "<<" | ">>" ) add-expr } ;
<<<bit-part,bit-part>>>
bits-lit = "<<<" [ bit-part { "," bit-part } ] ">>>" ;As the compiler reads it; §2.6 of the specification is out of date here.
expression:typelittle
bit-part = expression [ ":" type ] [ "little" ] ;As the compiler reads it; §2.6 of the specification is out of date here.
<<<bit-field,bit-field...IDENT>>>
bits-pattern = "<<<" { bit-field "," } [ bit-field | "..." IDENT ] ">>>" ;As the compiler reads it; §2.7 of the specification is out of date here.
bindingliteral:typeIDENT[expression]little
bit-field = ( binding | literal ) [ ":" ( type | IDENT "[" expression "]" ) ] [ "little" ] ;As the compiler reads it; §2.7 of the specification is out of date here.

&, | and ^ are and, or and exclusive or on two integers of one type; ~ flips every bit; << and >> shift the left side by a count that is unsigned or a literal, so it is never negative. Every result stays within its type's width, and &= |= ^= <<= >>= update a mut integer. These operators bind tighter than a comparison — x & 1 == 0 asks about x & 1 — and have no order among themselves: x >> 4 & 0xF is a compile error until parentheses say which goes first. A Bool keeps &&, || and !.

0xFF and 0b1010 are hexadecimal and binary literals, and _ may sit between digits: 0xFFFF_0000.

<<<...>>> builds bytes and takes them apart, most significant bit first, each field as wide as its type:

  • <<<version, length, payload>>> is a UInt8[dyn]: a UInt4 writes four bits, a UInt16 two bytes, a Str or a UInt8[] its bytes, and a literal one byte unless it says otherwise, 0x0D0A: UInt16.
  • packet is <<<version: UInt4, ihl: UInt4, length: UInt16, ...rest>>> reads them back. A field is a name and its type, a literal to match, _ to skip, or a run of bytes whose length an earlier field read, body: UInt8[size].
  • little after a field orders its bytes least significant first.
  • The subject is a UInt8[], a Str or an integer. The compiler checks that every field lands where it should: whole bytes, and a run starting on a byte.

hive.conv.bytesOf(text) and hive.conv.fromBytes(bytes) convert between a Str and its bytes.

func fnv1a(text: Str): UInt32 {
	mut UInt32 hash = 0x811C_9DC5
	for each b in hive.conv.bytesOf(text) {
		hash = (hash ^ UInt32(b)) * 0x0100_0193
	}
	return hash
}

proc main(): void {
	UInt8 flags = 0b1100_1010
	echo flags & 0x0F         // 10
	echo flags >> 4           // 12
	echo ~flags               // 53
	echo fnv1a("hello")       // 1335831723

	UInt8[dyn] header = <<<UInt4(4), UInt4(5), 0, 0x0054: UInt16>>>
	echo header               // [69, 0, 0, 84]
	if header is <<<version: UInt4, ihl: UInt4, _: UInt8, length: UInt16>>> {
		echo "IPv{version}, {length} bytes"
	}
}