streams_enh.nim 1.2 KB

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