Reading values out of Bytes

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

#!ek9
defines module site.builtInTypes.bytesReader

  defines program

    BytesReaderExample()
      stdout <- Stdout()

      //A TLS-record shape: type, version, body length, then a length-prefixed body
      record <- Bytes("1603030008034142430358595a")
      cursor <- record.reader()

      stdout.println(`type ${cursor.readByte()}, version ${cursor.readUInt16BE()}`)
      bodyLength <- cursor.readUInt16BE()

      //A bounded view - it cannot read past its own boundary
      body <- cursor.slice(bodyLength)
      fieldLength <- body.readByte().toInteger()
      stdout.println(`first field: ${body.readBytes(fieldLength)}`)

      //A short read is un set and does NOT move the cursor
      short <- Bytes("010203").reader()
      stdout.println(`wide read set: ${short.readUInt32BE()?}`)
      stdout.println(`still at ${short.position()}, smaller read gives ${short.readUInt16BE()}`)

Download builtInTypes_bytes_reader.ek9

Output

type 16, version 771
first field: 414243
wide read set: false
still at 0, smaller read gives 258