A collections of template and proc to work with binary data stored in either string or seq[byte] buffer.
Procs
proc toString(bytes: var seq[byte]): string {...}{.inline, raises: [], tags: [].}
-
Move memory from a mutableseq[byte] into a string
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.toString doAssert strbuf.len == 10*1024 doAssert buffer.len == 0
proc toByteArray(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.toByteArray doAssert strbuf.len == 0 doAssert buffer.len == 10*1024
Templates
template asString(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.asString: # ASCII representation of the bytes stored in bytesBuffer doAssert data == "0123456789"
template asString(bytes: seq[byte]; body)
- asString immutable template that uses copyMem instead of move. It is slower, but doesn't break immutability.
template asByteArray(str: var string; body)
-
Inject a mutable seq[byte] data containing the string buf
Example:
import sequtils var strBuffer = "abcdefghijklm" strBuffer.asByteArray: # ASCII value of the characters stored in strBuffer doAssert data == mapLiterals((97..109).toSeq, uint8)
template asByteArray(str: string; body)
- asByteArray immutable template that uses copyMem instead of move. It is slower, but doesn't break immutability.