Building Bytes

The complete source of builtInTypes_bytes_builder.ek9, compiled by the EK9 compiler. Shown on builtInTypes.html.

#!ek9
defines module site.builtInTypes.bytesBuilder

  defines constant

    tlsVersionTls12 <- 0x0303
    tlsBodyLength <- 8

  defines program

    BytesBuilderExample()
      stdout <- Stdout()

      //Building the TLS-record shape that the BytesReader example parses. The endianness is in
      //the method name, so it is visible on the line doing the writing.
      record <- BytesBuilder()
      record.append(Byte("16"))
      record.appendUInt16BE(tlsVersionTls12)
      record.appendUInt16BE(tlsBodyLength)
      record.append(Bytes("034142430358595a"))
      stdout.println(`framed: ${record.toBytes()}`)

      //Big and little endian genuinely differ - there is no defaulted spelling
      bigEndian <- BytesBuilder()
      bigEndian.appendUInt32BE(0x01020304)
      littleEndian <- BytesBuilder()
      littleEndian.appendUInt32LE(0x01020304)
      stdout.println(`big ${bigEndian.toBytes()}, little ${littleEndian.toBytes()}`)

      //A number too wide for its field is rejected, never truncated into a quiet lie
      tooWide <- BytesBuilder()
      tooWide.appendUInt16BE(0x10000)
      stdout.println(`too wide accepted: ${tooWide?}`)

      //xorInto is AddRoundKey, the Argon2 block XOR and the ChaCha20 keystream application,
      //and it is its own inverse
      block <- BytesBuilder(Bytes("ffffffff"))
      block.xorInto(0, Bytes("0f0f0f0f"))
      stdout.println(`after xor: ${block.toBytes()}`)

      //wipe zeroes the backing store and leaves the builder usable - something an immutable
      //Bytes fundamentally cannot offer
      secret <- BytesBuilder(Bytes("cafebabedeadbeef"))
      secret.wipe()
      stdout.println(`wiped to length ${length secret}, still usable ${secret?}`)

Download builtInTypes_bytes_builder.ek9

Output

framed: 1603030008034142430358595A
big 01020304, little 04030201
too wide accepted: false
after xor: F0F0F0F0
wiped to length 0, still usable true