Debian Codegraph @

tests/manyloc/keineschweine/dependencies/genpacket/streams_enh.nim

raw
1 import streams
2 from strutils import repeat
3
4 proc readPaddedStr*(s: PStream, length: int, padChar = '\0'): string =
5 var lastChr = length
6 result = s.readStr(length)
7 while lastChr >= 0 and result[lastChr - 1] == padChar: dec(lastChr)
8 result.setLen(lastChr)
9
10 proc writePaddedStr*(s: PStream, str: string, length: int, padChar = '\0') =
11 if str.len < length:
12 s.write(str)
13 s.write(repeat(padChar, length - str.len))
14 elif str.len > length:
15 s.write(str.substr(0, length - 1))
16 else:
17 s.write(str)
18
19 proc readLEStr*(s: PStream): string =
20 var len = s.readInt16()
21 result = s.readStr(len)
22
23 proc writeLEStr*(s: PStream, str: string) =
24 s.write(str.len.int16)
25 s.write(str)
26
27 when true:
28 var testStream = newStringStream()
29
30 testStream.writeLEStr("Hello")
31 doAssert testStream.data == "\5\0Hello"
32
33 testStream.setPosition 0
34 var res = testStream.readLEStr()
35 doAssert res == "Hello"
36
37 testStream.setPosition 0
38 testStream.writePaddedStr("Sup", 10)
39 echo(repr(testStream), testStream.data.len)
40 doAssert testStream.data == "Sup"&repeat('\0', 7)
41
42 testStream.setPosition 0
43 res = testStream.readPaddedStr(10)
44 doAssert res == "Sup"
45
46 testStream.close()
47