src/bytesequtils

A collections of template and proc to work with binary data stored in either string or seq[byte] buffer. Converting a seq[byte] into a string do not append a '\\0'. Be careful when interacting with cstring or C-API.

Procs

proc toByteSeq(str: var string): seq[byte] {.inline, ...raises: [], tags: [].}
Move memory from a mutable string into a seq[byte].

Example:

# Create a buffer
let buf_size = 10*1024
var strbuf = newString(buf_size)
# insert data into buffer
# Move data from the buffer into a string
var buffer = strbuf.toByteSeq
doAssert strbuf.len == 0
doAssert buffer.len == 10*1024
proc toStrBuf(bytes: var seq[byte]): string {.inline, ...raises: [], tags: [].}
Move memory from a mutableseq[byte] into a string Do not handle null termination. Manually add '\0' if you need to use cstring.

Example:

# Create a buffer
let buf_size = 10*1024
var buffer = newSeq[byte](buf_size)
# insert data into buffer
# Move data from the buffer into a string
var strbuf = buffer.toStrBuf
doAssert strbuf.len == 10*1024
doAssert buffer.len == 0

Templates

template asByteSeq(str: string; body)
asByteSeq immutable template that uses copyMem instead of move. It is slower, but doesn't break immutability.
template asByteSeq(str: var string; body)
Inject a mutable seq[byte] data containing the string buf

Example:

import sequtils
var strBuffer = "abcdefghijklm"
strBuffer.asByteSeq:
  # ASCII value of the characters stored in strBuffer
  doAssert data == mapLiterals((97..109).toSeq, uint8)
template asStrBuf(bytes: seq[byte]; body)
asStrBuf immutable template that uses copyMem instead of move. It is slower, but doesn't break immutability.
template asStrBuf(bytes: var seq[byte]; body)
Inject a mutable string data containing seq[byte] buf

Example:

import sequtils
var bytesBuffer: seq[byte] = mapLiterals((48..57).toSeq, uint8)
bytesBuffer.asStrBuf:
  # ASCII representation of the bytes stored in bytesBuffer
  doAssert data == "0123456789"