Types, patterns and values
Slide 31 of 85
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.

An integer's bits are reached with &, | and ^ — and, or and exclusive or, on two integers of one type — with ~, which flips every bit, and with << and >>, which 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 &= |= ^= <<= >>= step a mut integer. They bind tighter than a comparison — x & 1 == 0 asks about x & 1 — and have no order of their own: 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, every 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, and whether every field lands where it should — whole bytes, a run starting on one — is checked at compile time.

hive.conv.bytesOf(text) and hive.conv.fromBytes(bytes) cross 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"
	}
}