tstreams.nim 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. discard """
  2. matrix: "--mm:refc; --mm:orc"
  3. input: "Arne"
  4. output: '''
  5. Hello! What is your name?
  6. Nice name: Arne
  7. fs is: nil
  8. threw exception
  9. _heh_
  10. '''
  11. nimout: '''
  12. I
  13. AM
  14. GROOT
  15. '''
  16. """
  17. import std/[syncio, streams, assertions]
  18. block tstreams:
  19. var outp = newFileStream(stdout)
  20. var inp = newFileStream(stdin)
  21. writeLine(outp, "Hello! What is your name?")
  22. var line = readLine(inp)
  23. writeLine(outp, "Nice name: " & line)
  24. block tstreams2:
  25. var
  26. fs = newFileStream("amissingfile.txt")
  27. line = ""
  28. echo "fs is: ",repr(fs)
  29. if not isNil(fs):
  30. while fs.readLine(line):
  31. echo line
  32. fs.close()
  33. block tstreams3:
  34. try:
  35. var fs = openFileStream("shouldneverexist.txt")
  36. except IOError:
  37. echo "threw exception"
  38. static:
  39. var s = newStringStream("I\nAM\nGROOT")
  40. for line in s.lines:
  41. echo line
  42. s.close
  43. block:
  44. let fs = newFileStream("amissingfile.txt")
  45. defer: fs.close()
  46. doAssert isNil(fs)
  47. # bug #12410
  48. var a = newStringStream "hehohihahuhyh"
  49. a.readDataStrImpl = nil
  50. var buffer = "_ooo_"
  51. doAssert a.readDataStr(buffer, 1..3) == 3
  52. echo buffer
  53. block:
  54. var ss = newStringStream("The quick brown fox jumped over the lazy dog.\nThe lazy dog ran")
  55. doAssert(ss.getPosition == 0)
  56. doAssert(ss.peekStr(5) == "The q")
  57. doAssert(ss.getPosition == 0) # haven't moved
  58. doAssert(ss.readStr(5) == "The q")
  59. doAssert(ss.getPosition == 5) # did move
  60. doAssert(ss.peekLine() == "uick brown fox jumped over the lazy dog.")
  61. doAssert(ss.getPosition == 5) # haven't moved
  62. var str = newString(100)
  63. doAssert(ss.peekLine(str))
  64. doAssert(str == "uick brown fox jumped over the lazy dog.")
  65. doAssert(ss.getPosition == 5) # haven't moved
  66. # bug #19707 - Ensure we dont error with writing over literals on arc/orc
  67. ss.setPosition(0)
  68. ss.write("hello")
  69. ss.setPosition(0)
  70. doAssert(ss.peekStr(5) == "hello")
  71. # bug #19716
  72. static: # Ensure streams it doesnt break with nimscript on arc/orc #19716
  73. let s = newStringStream("a")
  74. doAssert s.data == "a"
  75. static: # issue #24054, readStr
  76. var s = newStringStream("foo bar baz")
  77. doAssert s.readStr(3) == "foo"
  78. template main =
  79. var strm = newStringStream("abcde")
  80. var buffer = "12345"
  81. doAssert strm.readDataStr(buffer, 0..3) == 4
  82. doAssert buffer == "abcd5"
  83. strm.close()
  84. static: main()
  85. main()