summary refs log tree commit diff stats
path: root/tests/manyloc/keineschweine/dependencies/genpacket/streams_enh.nim
blob: a0c8a7a3c28c0cb25118f06e49ef506758674524 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import streams
from strutils import repeat

proc readPaddedStr*(s: PStream, length: int, padChar = '\0'): string =
  var lastChr = length
  result = s.readStr(length)
  while lastChr >= 0 and result[lastChr - 1] == padChar: dec(lastChr)
  result.setLen(lastChr)

proc writePaddedStr*(s: PStream, str: string, length: int, padChar = '\0') =
  if str.len < length:
    s.write(str)
    s.write(repeat(padChar, length - str.len))
  elif str.len > length:
    s.write(str.substr(0, length - 1))
  else:
    s.write(str)

proc readLEStr*(s: PStream): string =
  var len = s.readInt16()
  result = s.readStr(len)

proc writeLEStr*(s: PStream, str: string) =
  s.write(str.len.int16)
  s.write(str)

when true:
  var testStream = newStringStream()

  testStream.writeLEStr("Hello")
  doAssert testStream.data == "\5\0Hello"

  testStream.setPosition 0
  var res = testStream.readLEStr()
  doAssert res == "Hello"

  testStream.setPosition 0
  testStream.writePaddedStr("Sup", 10)
  echo(repr(testStream), testStream.data.len)
  doAssert testStream.data == "Sup"&repeat('\0', 7)

  testStream.setPosition 0
  res = testStream.readPaddedStr(10)
  doAssert res == "Sup"

  testStream.close()