summary refs log tree commit diff stats
path: root/lib/pure/streams.nim
blob: f58273ee88847c8dcae47d09b992a0149e4770f0 (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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
#
#
#            Nim's Runtime Library
#        (c) Copyright 2015 Andreas Rumpf
#
#    See the file "copying.txt", included in this
#    distribution, for details about the copyright.
#

## This module provides a stream interface and two implementations thereof:
## the `FileStream <#FileStream>`_ and the `StringStream <#StringStream>`_
## which implement the stream interface for Nim file objects (`File`) and
## strings.
##
## Other modules may provide other implementations for this standard
## stream interface.
##
## Basic usage
## ===========
##
## The basic flow of using this module is:
##
## 1. Open input stream
## 2. Read or write stream
## 3. Close stream
##
## StringStream example
## --------------------
##
## .. code-block:: Nim
##
##  import std/streams
##
##  var strm = newStringStream("""The first line
##  the second line
##  the third line""")
##
##  var line = ""
##
##  while strm.readLine(line):
##    echo line
##
##  # Output:
##  # The first line
##  # the second line
##  # the third line
##
##  strm.close()
##
## FileStream example
## ------------------
##
## Write file stream example:
##
## .. code-block:: Nim
##
##  import std/streams
##
##  var strm = newFileStream("somefile.txt", fmWrite)
##  var line = ""
##
##  if not isNil(strm):
##    strm.writeLine("The first line")
##    strm.writeLine("the second line")
##    strm.writeLine("the third line")
##    strm.close()
##
##  # Output (somefile.txt):
##  # The first line
##  # the second line
##  # the third line
##
## Read file stream example:
##
## .. code-block:: Nim
##
##  import std/streams
##
##  var strm = newFileStream("somefile.txt", fmRead)
##  var line = ""
##
##  if not isNil(strm):
##    while strm.readLine(line):
##      echo line
##    strm.close()
##
##  # Output:
##  # The first line
##  # the second line
##  # the third line
##
## See also
## ========
## * `asyncstreams module <asyncstreams.html>`_
## * `io module <syncio.html>`_ for `FileMode enum <syncio.html#FileMode>`_

import std/private/since

when defined(nimPreviewSlimSystem):
  import std/syncio

proc newEIO(msg: string): owned(ref IOError) =
  new(result)
  result.msg = msg

type
  Stream* = ref StreamObj
    ## All procedures of this module use this type.
    ## Procedures don't directly use `StreamObj <#StreamObj>`_.
  StreamObj* = object of RootObj
    ## Stream interface that supports writing or reading.
    ##
    ## **Note:**
    ## * That these fields here shouldn't be used directly.
    ##   They are accessible so that a stream implementation can override them.
    closeImpl*: proc (s: Stream)
      {.nimcall, raises: [Exception, IOError, OSError], tags: [WriteIOEffect], gcsafe.}
    atEndImpl*: proc (s: Stream): bool
      {.nimcall, raises: [Defect, IOError, OSError], tags: [], gcsafe.}
    setPositionImpl*: proc (s: Stream, pos: int)
      {.nimcall, raises: [Defect, IOError, OSError], tags: [], gcsafe.}
    getPositionImpl*: proc (s: Stream): int
      {.nimcall, raises: [Defect, IOError, OSError], tags: [], gcsafe.}

    readDataStrImpl*: proc (s: Stream, buffer: var string, slice: Slice[int]): int
      {.nimcall, raises: [Defect, IOError, OSError], tags: [ReadIOEffect], gcsafe.}

    readLineImpl*: proc(s: Stream, line: var string): bool
      {.nimcall, raises: [Defect, IOError, OSError], tags: [ReadIOEffect], gcsafe.}

    readDataImpl*: proc (s: Stream, buffer: pointer, bufLen: int): int
      {.nimcall, raises: [Defect, IOError, OSError], tags: [ReadIOEffect], gcsafe.}
    peekDataImpl*: proc (s: Stream, buffer: pointer, bufLen: int): int
      {.nimcall, raises: [Defect, IOError, OSError], tags: [ReadIOEffect], gcsafe.}
    writeDataImpl*: proc (s: Stream, buffer: pointer, bufLen: int)
      {.nimcall, raises: [Defect, IOError, OSError], tags: [WriteIOEffect], gcsafe.}

    flushImpl*: proc (s: Stream)
      {.nimcall, raises: [Defect, IOError, OSError], tags: [WriteIOEffect], gcsafe.}

proc flush*(s: Stream) =
  ## Flushes the buffers that the stream `s` might use.
  ##
  ## This procedure causes any unwritten data for that stream to be delivered
  ## to the host environment to be written to the file.
  ##
  ## See also:
  ## * `close proc <#close,Stream>`_
  runnableExamples:
    from std/os import removeFile

    var strm = newFileStream("somefile.txt", fmWrite)

    doAssert "Before write:" & readFile("somefile.txt") == "Before write:"
    strm.write("hello")
    doAssert "After  write:" & readFile("somefile.txt") == "After  write:"

    strm.flush()
    doAssert "After  flush:" & readFile("somefile.txt") == "After  flush:hello"
    strm.write("HELLO")
    strm.flush()
    doAssert "After  flush:" & readFile("somefile.txt") == "After  flush:helloHELLO"

    strm.close()
    doAssert "After  close:" & readFile("somefile.txt") == "After  close:helloHELLO"
    removeFile("somefile.txt")

  if not isNil(s.flushImpl): s.flushImpl(s)

proc close*(s: Stream) =
  ## Closes the stream `s`.
  ##
  ## See also:
  ## * `flush proc <#flush,Stream>`_
  runnableExamples:
    var strm = newStringStream("The first line\nthe second line\nthe third line")
    ## do something...
    strm.close()
  if not isNil(s.closeImpl): s.closeImpl(s)

proc atEnd*(s: Stream): bool =
  ## Checks if more data can be read from `s`. Returns ``true`` if all data has
  ## been read.
  runnableExamples:
    var strm = newStringStream("The first line\nthe second line\nthe third line")
    var line = ""
    doAssert strm.atEnd() == false
    while strm.readLine(line):
      discard
    doAssert strm.atEnd() == true
    strm.close()

  result = s.atEndImpl(s)

proc setPosition*(s: Stream, pos: int) =
  ## Sets the position `pos` of the stream `s`.
  runnableExamples:
    var strm = newStringStream("The first line\nthe second line\nthe third line")
    strm.setPosition(4)
    doAssert strm.readLine() == "first line"
    strm.setPosition(0)
    doAssert strm.readLine() == "The first line"
    strm.close()

  s.setPositionImpl(s, pos)

proc getPosition*(s: Stream): int =
  ## Retrieves the current position in the stream `s`.
  runnableExamples:
    var strm = newStringStream("The first line\nthe second line\nthe third line")
    doAssert strm.getPosition() == 0
    discard strm.readLine()
    doAssert strm.getPosition() == 15
    strm.close()

  result = s.getPositionImpl(s)

proc readData*(s: Stream, buffer: pointer, bufLen: int): int =
  ## Low level proc that reads data into an untyped `buffer` of `bufLen` size.
  ##
  ## **JS note:** `buffer` is treated as a ``ptr string`` and written to between
  ## ``0..<bufLen``.
  runnableExamples:
    var strm = newStringStream("abcde")
    var buffer: array[6, char]
    doAssert strm.readData(addr(buffer), 1024) == 5
    doAssert buffer == ['a', 'b', 'c', 'd', 'e', '\x00']
    doAssert strm.atEnd() == true
    strm.close()

  result = s.readDataImpl(s, buffer, bufLen)

proc readDataStr*(s: Stream, buffer: var string, slice: Slice[int]): int =
  ## Low level proc that reads data into a string ``buffer`` at ``slice``.
  runnableExamples:
    var strm = newStringStream("abcde")
    var buffer = "12345"
    doAssert strm.readDataStr(buffer, 0..3) == 4
    doAssert buffer == "abcd5"
    strm.close()

  if s.readDataStrImpl != nil:
    result = s.readDataStrImpl(s, buffer, slice)
  else:
    # fallback
    when declared(prepareMutation):
      # buffer might potentially be a CoW literal with ARC
      prepareMutation(buffer)
    result = s.readData(addr buffer[slice.a], slice.b + 1 - slice.a)

template jsOrVmBlock(caseJsOrVm, caseElse: untyped): untyped =
  when nimvm:
    block:
      caseJsOrVm
  else:
    block:
      when defined(js) or defined(nimscript):
        # nimscript has to be here to avoid semantic checking of caseElse
        caseJsOrVm
      else:
        caseElse

when (NimMajor, NimMinor) >= (1, 3) or not defined(js):
  proc readAll*(s: Stream): string =
    ## Reads all available data.
    runnableExamples:
      var strm = newStringStream("The first line\nthe second line\nthe third line")
      doAssert strm.readAll() == "The first line\nthe second line\nthe third line"
      doAssert strm.atEnd() == true
      strm.close()

    const bufferSize = 1024
    jsOrVmBlock:
      var buffer2: string
      buffer2.setLen(bufferSize)
      while true:
        let readBytes = readDataStr(s, buffer2, 0..<bufferSize)
        if readBytes == 0:
          break
        let prevLen = result.len
        result.setLen(prevLen + readBytes)
        result[prevLen..<prevLen+readBytes] = buffer2[0..<readBytes]
        if readBytes < bufferSize:
          break
    do: # not JS or VM
      var buffer {.noinit.}: array[bufferSize, char]
      while true:
        let readBytes = readData(s, addr(buffer[0]), bufferSize)
        if readBytes == 0:
          break
        let prevLen = result.len
        result.setLen(prevLen + readBytes)
        copyMem(addr(result[prevLen]), addr(buffer[0]), readBytes)
        if readBytes < bufferSize:
          break

proc peekData*(s: Stream, buffer: pointer, bufLen: int): int =
  ## Low level proc that reads data into an untyped `buffer` of `bufLen` size
  ## without moving stream position.
  ##
  ## **JS note:** `buffer` is treated as a ``ptr string`` and written to between
  ## ``0..<bufLen``.
  runnableExamples:
    var strm = newStringStream("abcde")
    var buffer: array[6, char]
    doAssert strm.peekData(addr(buffer), 1024) == 5
    doAssert buffer == ['a', 'b', 'c', 'd', 'e', '\x00']
    doAssert strm.atEnd() == false
    strm.close()

  result = s.peekDataImpl(s, buffer, bufLen)

proc writeData*(s: Stream, buffer: pointer, bufLen: int) =
  ## Low level proc that writes an untyped `buffer` of `bufLen` size
  ## to the stream `s`.
  ##
  ## **JS note:** `buffer` is treated as a ``ptr string`` and read between
  ## ``0..<bufLen``.
  runnableExamples:
    ## writeData
    var strm = newStringStream("")
    var buffer = ['a', 'b', 'c', 'd', 'e']
    strm.writeData(addr(buffer), sizeof(buffer))
    doAssert strm.atEnd() == true
    ## readData
    strm.setPosition(0)
    var buffer2: array[6, char]
    doAssert strm.readData(addr(buffer2), sizeof(buffer2)) == 5
    doAssert buffer2 == ['a', 'b', 'c', 'd', 'e', '\x00']
    strm.close()

  s.writeDataImpl(s, buffer, bufLen)

proc write*[T](s: Stream, x: T) =
  ## Generic write procedure. Writes `x` to the stream `s`. Implementation:
  ##
  ## **Note:** Not available for JS backend. Use `write(Stream, string)
  ## <#write,Stream,string>`_ for now.
  ##
  ## .. code-block:: Nim
  ##
  ##     s.writeData(s, unsafeAddr(x), sizeof(x))
  runnableExamples:
    var strm = newStringStream("")
    strm.write("abcde")
    strm.setPosition(0)
    doAssert strm.readAll() == "abcde"
    strm.close()

  writeData(s, unsafeAddr(x), sizeof(x))

proc write*(s: Stream, x: string) =
  ## Writes the string `x` to the stream `s`. No length field or
  ## terminating zero is written.
  runnableExamples:
    var strm = newStringStream("")
    strm.write("THE FIRST LINE")
    strm.setPosition(0)
    doAssert strm.readLine() == "THE FIRST LINE"
    strm.close()

  when nimvm:
    writeData(s, cstring(x), x.len)
  else:
    if x.len > 0:
      when defined(js):
        var x = x
        writeData(s, addr(x), x.len)
      else:
        writeData(s, cstring(x), x.len)

proc write*(s: Stream, args: varargs[string, `$`]) =
  ## Writes one or more strings to the the stream. No length fields or
  ## terminating zeros are written.
  runnableExamples:
    var strm = newStringStream("")
    strm.write(1, 2, 3, 4)
    strm.setPosition(0)
    doAssert strm.readLine() == "1234"
    strm.close()

  for str in args: write(s, str)

proc writeLine*(s: Stream, args: varargs[string, `$`]) =
  ## Writes one or more strings to the the stream `s` followed
  ## by a new line. No length field or terminating zero is written.
  runnableExamples:
    var strm = newStringStream("")
    strm.writeLine(1, 2)
    strm.writeLine(3, 4)
    strm.setPosition(0)
    doAssert strm.readAll() == "12\n34\n"
    strm.close()

  for str in args: write(s, str)
  write(s, "\n")

proc read*[T](s: Stream, result: var T) =
  ## Generic read procedure. Reads `result` from the stream `s`.
  ##
  ## **Note:** Not available for JS backend. Use `readStr <#readStr,Stream,int>`_ for now.
  runnableExamples:
    var strm = newStringStream("012")
    ## readInt
    var i: int8
    strm.read(i)
    doAssert i == 48
    ## readData
    var buffer: array[2, char]
    strm.read(buffer)
    doAssert buffer == ['1', '2']
    strm.close()

  if readData(s, addr(result), sizeof(T)) != sizeof(T):
    raise newEIO("cannot read from stream")

proc peek*[T](s: Stream, result: var T) =
  ## Generic peek procedure. Peeks `result` from the stream `s`.
  ##
  ## **Note:** Not available for JS backend. Use `peekStr <#peekStr,Stream,int>`_ for now.
  runnableExamples:
    var strm = newStringStream("012")
    ## peekInt
    var i: int8
    strm.peek(i)
    doAssert i == 48
    ## peekData
    var buffer: array[2, char]
    strm.peek(buffer)
    doAssert buffer == ['0', '1']
    strm.close()

  if peekData(s, addr(result), sizeof(T)) != sizeof(T):
    raise newEIO("cannot read from stream")

proc readChar*(s: Stream): char =
  ## Reads a char from the stream `s`.
  ##
  ## Raises `IOError` if an error occurred.
  ## Returns '\\0' as an EOF marker.
  runnableExamples:
    var strm = newStringStream("12\n3")
    doAssert strm.readChar() == '1'
    doAssert strm.readChar() == '2'
    doAssert strm.readChar() == '\n'
    doAssert strm.readChar() == '3'
    doAssert strm.readChar() == '\x00'
    strm.close()

  jsOrVmBlock:
    var str = " "
    if readDataStr(s, str, 0..0) != 1: result = '\0'
    else: result = str[0]
  do:
    if readData(s, addr(result), sizeof(result)) != 1: result = '\0'

proc peekChar*(s: Stream): char =
  ## Peeks a char from the stream `s`. Raises `IOError` if an error occurred.
  ## Returns '\\0' as an EOF marker.
  runnableExamples:
    var strm = newStringStream("12\n3")
    doAssert strm.peekChar() == '1'
    doAssert strm.peekChar() == '1'
    discard strm.readAll()
    doAssert strm.peekChar() == '\x00'
    strm.close()

  when defined(js):
    var str = " "
    if peekData(s, addr(str), sizeof(result)) != 1: result = '\0'
    else: result = str[0]
  else:
    if peekData(s, addr(result), sizeof(result)) != 1: result = '\0'

proc readBool*(s: Stream): bool =
  ## Reads a bool from the stream `s`.
  ##
  ## A bool is one byte long and it is `true` for every non-zero
  ## (`0000_0000`) value.
  ## Raises `IOError` if an error occurred.
  ##
  ## **Note:** Not available for JS backend. Use `readStr <#readStr,Stream,int>`_ for now.
  runnableExamples:
    var strm = newStringStream()
    ## setup for reading data
    strm.write(true)
    strm.write(false)
    strm.flush()
    strm.setPosition(0)
    ## get data
    doAssert strm.readBool() == true
    doAssert strm.readBool() == false
    doAssertRaises(IOError): discard strm.readBool()
    strm.close()

  var t: byte
  read(s, t)
  result = t != 0.byte

proc peekBool*(s: Stream): bool =
  ## Peeks a bool from the stream `s`.
  ##
  ## A bool is one byte long and it is `true` for every non-zero
  ## (`0000_0000`) value.
  ## Raises `IOError` if an error occurred.
  ##
  ## **Note:** Not available for JS backend. Use `peekStr <#peekStr,Stream,int>`_ for now.
  runnableExamples:
    var strm = newStringStream()
    ## setup for reading data
    strm.write(true)
    strm.write(false)
    strm.flush()
    strm.setPosition(0)
    ## get data
    doAssert strm.peekBool() == true
    ## not false
    doAssert strm.peekBool() == true
    doAssert strm.readBool() == true
    doAssert strm.peekBool() == false
    strm.close()

  var t: byte
  peek(s, t)
  result = t != 0.byte

proc readInt8*(s: Stream): int8 =
  ## Reads an int8 from the stream `s`. Raises `IOError` if an error occurred.
  ##
  ## **Note:** Not available for JS backend. Use `readStr <#readStr,Stream,int>`_ for now.
  runnableExamples:
    var strm = newStringStream()
    ## setup for reading data
    strm.write(1'i8)
    strm.write(2'i8)
    strm.flush()
    strm.setPosition(0)
    ## get data
    doAssert strm.readInt8() == 1'i8
    doAssert strm.readInt8() == 2'i8
    doAssertRaises(IOError): discard strm.readInt8()
    strm.close()

  read(s, result)

proc peekInt8*(s: Stream): int8 =
  ## Peeks an int8 from the stream `s`. Raises `IOError` if an error occurred.
  ##
  ## **Note:** Not available for JS backend. Use `peekStr <#peekStr,Stream,int>`_ for now.
  runnableExamples:
    var strm = newStringStream()
    ## setup for reading data
    strm.write(1'i8)
    strm.write(2'i8)
    strm.flush()
    strm.setPosition(0)
    ## get data
    doAssert strm.peekInt8() == 1'i8
    ## not 2'i8
    doAssert strm.peekInt8() == 1'i8
    doAssert strm.readInt8() == 1'i8
    doAssert strm.peekInt8() == 2'i8
    strm.close()

  peek(s, result)

proc readInt16*(s: Stream): int16 =
  ## Reads an int16 from the stream `s`. Raises `IOError` if an error occurred.
  ##
  ## **Note:** Not available for JS backend. Use `readStr <#readStr,Stream,int>`_ for now.
  runnableExamples:
    var strm = newStringStream()
    ## setup for reading data
    strm.write(1'i16)
    strm.write(2'i16)
    strm.flush()
    strm.setPosition(0)
    ## get data
    doAssert strm.readInt16() == 1'i16
    doAssert strm.readInt16() == 2'i16
    doAssertRaises(IOError): discard strm.readInt16()
    strm.close()

  read(s, result)

proc peekInt16*(s: Stream): int16 =
  ## Peeks an int16 from the stream `s`. Raises `IOError` if an error occurred.
  ##
  ## **Note:** Not available for JS backend. Use `peekStr <#peekStr,Stream,int>`_ for now.
  runnableExamples:
    var strm = newStringStream()
    ## setup for reading data
    strm.write(1'i16)
    strm.write(2'i16)
    strm.flush()
    strm.setPosition(0)
    ## get data
    doAssert strm.peekInt16() == 1'i16
    ## not 2'i16
    doAssert strm.peekInt16() == 1'i16
    doAssert strm.readInt16() == 1'i16
    doAssert strm.peekInt16() == 2'i16
    strm.close()

  peek(s, result)

proc readInt32*(s: Stream): int32 =
  ## Reads an int32 from the stream `s`. Raises `IOError` if an error occurred.
  ##
  ## **Note:** Not available for JS backend. Use `readStr <#readStr,Stream,int>`_ for now.
  runnableExamples:
    var strm = newStringStream()
    ## setup for reading data
    strm.write(1'i32)
    strm.write(2'i32)
    strm.flush()
    strm.setPosition(0)
    ## get data
    doAssert strm.readInt32() == 1'i32
    doAssert strm.readInt32() == 2'i32
    doAssertRaises(IOError): discard strm.readInt32()
    strm.close()

  read(s, result)

proc peekInt32*(s: Stream): int32 =
  ## Peeks an int32 from the stream `s`. Raises `IOError` if an error occurred.
  ##
  ## **Note:** Not available for JS backend. Use `peekStr <#peekStr,Stream,int>`_ for now.
  runnableExamples:
    var strm = newStringStream()
    ## setup for reading data
    strm.write(1'i32)
    strm.write(2'i32)
    strm.flush()
    strm.setPosition(0)
    ## get data
    doAssert strm.peekInt32() == 1'i32
    ## not 2'i32
    doAssert strm.peekInt32() == 1'i32
    doAssert strm.readInt32() == 1'i32
    doAssert strm.peekInt32() == 2'i32
    strm.close()

  peek(s, result)

proc readInt64*(s: Stream): int64 =
  ## Reads an int64 from the stream `s`. Raises `IOError` if an error occurred.
  ##
  ## **Note:** Not available for JS backend. Use `readStr <#readStr,Stream,int>`_ for now.
  runnableExamples:
    var strm = newStringStream()
    ## setup for reading data
    strm.write(1'i64)
    strm.write(2'i64)
    strm.flush()
    strm.setPosition(0)
    ## get data
    doAssert strm.readInt64() == 1'i64
    doAssert strm.readInt64() == 2'i64
    doAssertRaises(IOError): discard strm.readInt64()
    strm.close()

  read(s, result)

proc peekInt64*(s: Stream): int64 =
  ## Peeks an int64 from the stream `s`. Raises `IOError` if an error occurred.
  ##
  ## **Note:** Not available for JS backend. Use `peekStr <#peekStr,Stream,int>`_ for now.
  runnableExamples:
    var strm = newStringStream()
    ## setup for reading data
    strm.write(1'i64)
    strm.write(2'i64)
    strm.flush()
    strm.setPosition(0)
    ## get data
    doAssert strm.peekInt64() == 1'i64
    ## not 2'i64
    doAssert strm.peekInt64() == 1'i64
    doAssert strm.readInt64() == 1'i64
    doAssert strm.peekInt64() == 2'i64
    strm.close()

  peek(s, result)

proc readUint8*(s: Stream): uint8 =
  ## Reads an uint8 from the stream `s`. Raises `IOError` if an error occurred.
  ##
  ## **Note:** Not available for JS backend. Use `readStr <#readStr,Stream,int>`_ for now.
  runnableExamples:
    var strm = newStringStream()
    ## setup for reading data
    strm.write(1'u8)
    strm.write(2'u8)
    strm.flush()
    strm.setPosition(0)
    ## get data
    doAssert strm.readUint8() == 1'u8
    doAssert strm.readUint8() == 2'u8
    doAssertRaises(IOError): discard strm.readUint8()
    strm.close()

  read(s, result)

proc peekUint8*(s: Stream): uint8 =
  ## Peeks an uint8 from the stream `s`. Raises `IOError` if an error occurred.
  ##
  ## **Note:** Not available for JS backend. Use `peekStr <#peekStr,Stream,int>`_ for now.
  runnableExamples:
    var strm = newStringStream()
    ## setup for reading data
    strm.write(1'u8)
    strm.write(2'u8)
    strm.flush()
    strm.setPosition(0)
    ## get data
    doAssert strm.peekUint8() == 1'u8
    ## not 2'u8
    doAssert strm.peekUint8() == 1'u8
    doAssert strm.readUint8() == 1'u8
    doAssert strm.peekUint8() == 2'u8
    strm.close()

  peek(s, result)

proc readUint16*(s: Stream): uint16 =
  ## Reads an uint16 from the stream `s`. Raises `IOError` if an error occurred.
  ##
  ## **Note:** Not available for JS backend. Use `readStr <#readStr,Stream,int>`_ for now.
  runnableExamples:
    var strm = newStringStream()
    ## setup for reading data
    strm.write(1'u16)
    strm.write(2'u16)
    strm.flush()
    strm.setPosition(0)
    ## get data
    doAssert strm.readUint16() == 1'u16
    doAssert strm.readUint16() == 2'u16
    doAssertRaises(IOError): discard strm.readUint16()
    strm.close()

  read(s, result)

proc peekUint16*(s: Stream): uint16 =
  ## Peeks an uint16 from the stream `s`. Raises `IOError` if an error occurred.
  ##
  ## **Note:** Not available for JS backend. Use `peekStr <#peekStr,Stream,int>`_ for now.
  runnableExamples:
    var strm = newStringStream()
    ## setup for reading data
    strm.write(1'u16)
    strm.write(2'u16)
    strm.flush()
    strm.setPosition(0)
    ## get data
    doAssert strm.peekUint16() == 1'u16
    ## not 2'u16
    doAssert strm.peekUint16() == 1'u16
    doAssert strm.readUint16() == 1'u16
    doAssert strm.peekUint16() == 2'u16
    strm.close()

  peek(s, result)

proc readUint32*(s: Stream): uint32 =
  ## Reads an uint32 from the stream `s`. Raises `IOError` if an error occurred.
  ##
  ## **Note:** Not available for JS backend. Use `readStr <#readStr,Stream,int>`_ for now.
  runnableExamples:
    var strm = newStringStream()
    ## setup for reading data
    strm.write(1'u32)
    strm.write(2'u32)
    strm.flush()
    strm.setPosition(0)

    ## get data
    doAssert strm.readUint32() == 1'u32
    doAssert strm.readUint32() == 2'u32
    doAssertRaises(IOError): discard strm.readUint32()
    strm.close()

  read(s, result)

proc peekUint32*(s: Stream): uint32 =
  ## Peeks an uint32 from the stream `s`. Raises `IOError` if an error occurred.
  ##
  ## **Note:** Not available for JS backend. Use `peekStr <#peekStr,Stream,int>`_ for now.
  runnableExamples:
    var strm = newStringStream()
    ## setup for reading data
    strm.write(1'u32)
    strm.write(2'u32)
    strm.flush()
    strm.setPosition(0)
    ## get data
    doAssert strm.peekUint32() == 1'u32
    ## not 2'u32
    doAssert strm.peekUint32() == 1'u32
    doAssert strm.readUint32() == 1'u32
    doAssert strm.peekUint32() == 2'u32
    strm.close()

  peek(s, result)

proc readUint64*(s: Stream): uint64 =
  ## Reads an uint64 from the stream `s`. Raises `IOError` if an error occurred.
  ##
  ## **Note:** Not available for JS backend. Use `readStr <#readStr,Stream,int>`_ for now.
  runnableExamples:
    var strm = newStringStream()
    ## setup for reading data
    strm.write(1'u64)
    strm.write(2'u64)
    strm.flush()
    strm.setPosition(0)
    ## get data
    doAssert strm.readUint64() == 1'u64
    doAssert strm.readUint64() == 2'u64
    doAssertRaises(IOError): discard strm.readUint64()
    strm.close()

  read(s, result)

proc peekUint64*(s: Stream): uint64 =
  ## Peeks an uint64 from the stream `s`. Raises `IOError` if an error occurred.
  ##
  ## **Note:** Not available for JS backend. Use `peekStr <#peekStr,Stream,int>`_ for now.
  runnableExamples:
    var strm = newStringStream()
    ## setup for reading data
    strm.write(1'u64)
    strm.write(2'u64)
    strm.flush()
    strm.setPosition(0)
    ## get data
    doAssert strm.peekUint64() == 1'u64
    ## not 2'u64
    doAssert strm.peekUint64() == 1'u64
    doAssert strm.readUint64() == 1'u64
    doAssert strm.peekUint64() == 2'u64
    strm.close()

  peek(s, result)

proc readFloat32*(s: Stream): float32 =
  ## Reads a float32 from the stream `s`. Raises `IOError` if an error occurred.
  ##
  ## **Note:** Not available for JS backend. Use `readStr <#readStr,Stream,int>`_ for now.
  runnableExamples:
    var strm = newStringStream()
    ## setup for reading data
    strm.write(1'f32)
    strm.write(2'f32)
    strm.flush()
    strm.setPosition(0)
    ## get data
    doAssert strm.readFloat32() == 1'f32
    doAssert strm.readFloat32() == 2'f32
    doAssertRaises(IOError): discard strm.readFloat32()
    strm.close()

  read(s, result)

proc peekFloat32*(s: Stream): float32 =
  ## Peeks a float32 from the stream `s`. Raises `IOError` if an error occurred.
  ##
  ## **Note:** Not available for JS backend. Use `peekStr <#peekStr,Stream,int>`_ for now.
  runnableExamples:
    var strm = newStringStream()
    ## setup for reading data
    strm.write(1'f32)
    strm.write(2'f32)
    strm.flush()
    strm.setPosition(0)
    ## get data
    doAssert strm.peekFloat32() == 1'f32
    ## not 2'f32
    doAssert strm.peekFloat32() == 1'f32
    doAssert strm.readFloat32() == 1'f32
    doAssert strm.peekFloat32() == 2'f32
    strm.close()

  peek(s, result)

proc readFloat64*(s: Stream): float64 =
  ## Reads a float64 from the stream `s`. Raises `IOError` if an error occurred.
  ##
  ## **Note:** Not available for JS backend. Use `readStr <#readStr,Stream,int>`_ for now.
  runnableExamples:
    var strm = newStringStream()
    ## setup for reading data
    strm.write(1'f64)
    strm.write(2'f64)
    strm.flush()
    strm.setPosition(0)
    ## get data
    doAssert strm.readFloat64() == 1'f64
    doAssert strm.readFloat64() == 2'f64
    doAssertRaises(IOError): discard strm.readFloat64()
    strm.close()

  read(s, result)

proc peekFloat64*(s: Stream): float64 =
  ## Peeks a float64 from the stream `s`. Raises `IOError` if an error occurred.
  ##
  ## **Note:** Not available for JS backend. Use `peekStr <#peekStr,Stream,int>`_ for now.
  runnableExamples:
    var strm = newStringStream()
    ## setup for reading data
    strm.write(1'f64)
    strm.write(2'f64)
    strm.flush()
    strm.setPosition(0)
    ## get data
    doAssert strm.peekFloat64() == 1'f64
    ## not 2'f64
    doAssert strm.peekFloat64() == 1'f64
    doAssert strm.readFloat64() == 1'f64
    doAssert strm.peekFloat64() == 2'f64
    strm.close()

  peek(s, result)

proc readStrPrivate(s: Stream, length: int, str: var string) =
  if length > len(str): setLen(str, length)
  when defined(js):
    let L = readData(s, addr(str), length)
  else:
    let L = readData(s, cstring(str), length)
  if L != len(str): setLen(str, L)

proc readStr*(s: Stream, length: int, str: var string) {.since: (1, 3).} =
  ## Reads a string of length `length` from the stream `s`. Raises `IOError` if
  ## an error occurred.
  readStrPrivate(s, length, str)

proc readStr*(s: Stream, length: int): string =
  ## Reads a string of length `length` from the stream `s`. Raises `IOError` if
  ## an error occurred.
  runnableExamples:
    var strm = newStringStream("abcde")
    doAssert strm.readStr(2) == "ab"
    doAssert strm.readStr(2) == "cd"
    doAssert strm.readStr(2) == "e"
    doAssert strm.readStr(2) == ""
    strm.close()
  result = newString(length)
  readStrPrivate(s, length, result)

proc peekStrPrivate(s: Stream, length: int, str: var string) =
  if length > len(str): setLen(str, length)
  when defined(js):
    let L = peekData(s, addr(str), length)
  else:
    let L = peekData(s, cstring(str), length)
  if L != len(str): setLen(str, L)

proc peekStr*(s: Stream, length: int, str: var string) {.since: (1, 3).} =
  ## Peeks a string of length `length` from the stream `s`. Raises `IOError` if
  ## an error occurred.
  peekStrPrivate(s, length, str)

proc peekStr*(s: Stream, length: int): string =
  ## Peeks a string of length `length` from the stream `s`. Raises `IOError` if
  ## an error occurred.
  runnableExamples:
    var strm = newStringStream("abcde")
    doAssert strm.peekStr(2) == "ab"
    ## not "cd
    doAssert strm.peekStr(2) == "ab"
    doAssert strm.readStr(2) == "ab"
    doAssert strm.peekStr(2) == "cd"
    strm.close()
  result = newString(length)
  peekStrPrivate(s, length, result)

proc readLine*(s: Stream, line: var string): bool =
  ## Reads a line of text from the stream `s` into `line`. `line` must not be
  ## ``nil``! May throw an IO exception.
  ##
  ## A line of text may be delimited by ``LF`` or ``CRLF``.
  ## The newline character(s) are not part of the returned string.
  ## Returns ``false`` if the end of the file has been reached, ``true``
  ## otherwise. If ``false`` is returned `line` contains no new data.
  ##
  ## See also:
  ## * `readLine(Stream) proc <#readLine,Stream>`_
  ## * `peekLine(Stream) proc <#peekLine,Stream>`_
  ## * `peekLine(Stream, string) proc <#peekLine,Stream,string>`_
  runnableExamples:
    var strm = newStringStream("The first line\nthe second line\nthe third line")
    var line = ""
    doAssert strm.readLine(line) == true
    doAssert line == "The first line"
    doAssert strm.readLine(line) == true
    doAssert line == "the second line"
    doAssert strm.readLine(line) == true
    doAssert line == "the third line"
    doAssert strm.readLine(line) == false
    doAssert line == ""
    strm.close()

  if s.readLineImpl != nil:
    result = s.readLineImpl(s, line)
  else:
    # fallback
    line.setLen(0)
    while true:
      var c = readChar(s)
      if c == '\c':
        c = readChar(s)
        break
      elif c == '\L': break
      elif c == '\0':
        if line.len > 0: break
        else: return false
      line.add(c)
    result = true

proc peekLine*(s: Stream, line: var string): bool =
  ## Peeks a line of text from the stream `s` into `line`. `line` must not be
  ## ``nil``! May throw an IO exception.
  ##
  ## A line of text may be delimited by ``CR``, ``LF`` or
  ## ``CRLF``. The newline character(s) are not part of the returned string.
  ## Returns ``false`` if the end of the file has been reached, ``true``
  ## otherwise. If ``false`` is returned `line` contains no new data.
  ##
  ## See also:
  ## * `readLine(Stream) proc <#readLine,Stream>`_
  ## * `readLine(Stream, string) proc <#readLine,Stream,string>`_
  ## * `peekLine(Stream) proc <#peekLine,Stream>`_
  runnableExamples:
    var strm = newStringStream("The first line\nthe second line\nthe third line")
    var line = ""
    doAssert strm.peekLine(line) == true
    doAssert line == "The first line"
    doAssert strm.peekLine(line) == true
    ## not "the second line"
    doAssert line == "The first line"
    doAssert strm.readLine(line) == true
    doAssert line == "The first line"
    doAssert strm.peekLine(line) == true
    doAssert line == "the second line"
    strm.close()

  let pos = getPosition(s)
  defer: setPosition(s, pos)
  result = readLine(s, line)

proc readLine*(s: Stream): string =
  ## Reads a line from a stream `s`. Raises `IOError` if an error occurred.
  ##
  ## **Note:** This is not very efficient.
  ##
  ## See also:
  ## * `readLine(Stream, string) proc <#readLine,Stream,string>`_
  ## * `peekLine(Stream) proc <#peekLine,Stream>`_
  ## * `peekLine(Stream, string) proc <#peekLine,Stream,string>`_
  runnableExamples:
    var strm = newStringStream("The first line\nthe second line\nthe third line")
    doAssert strm.readLine() == "The first line"
    doAssert strm.readLine() == "the second line"
    doAssert strm.readLine() == "the third line"
    doAssertRaises(IOError): discard strm.readLine()
    strm.close()

  result = ""
  if s.atEnd:
    raise newEIO("cannot read from stream")
  while true:
    var c = readChar(s)
    if c == '\c':
      c = readChar(s)
      break
    if c == '\L' or c == '\0':
      break
    else:
      result.add(c)

proc peekLine*(s: Stream): string =
  ## Peeks a line from a stream `s`. Raises `IOError` if an error occurred.
  ##
  ## **Note:** This is not very efficient.
  ##
  ## See also:
  ## * `readLine(Stream) proc <#readLine,Stream>`_
  ## * `readLine(Stream, string) proc <#readLine,Stream,string>`_
  ## * `peekLine(Stream, string) proc <#peekLine,Stream,string>`_
  runnableExamples:
    var strm = newStringStream("The first line\nthe second line\nthe third line")
    doAssert strm.peekLine() == "The first line"
    ## not "the second line"
    doAssert strm.peekLine() == "The first line"
    doAssert strm.readLine() == "The first line"
    doAssert strm.peekLine() == "the second line"
    strm.close()

  let pos = getPosition(s)
  defer: setPosition(s, pos)
  result = readLine(s)

iterator lines*(s: Stream): string =
  ## Iterates over every line in the stream.
  ## The iteration is based on ``readLine``.
  ##
  ## See also:
  ## * `readLine(Stream) proc <#readLine,Stream>`_
  ## * `readLine(Stream, string) proc <#readLine,Stream,string>`_
  runnableExamples:
    var strm = newStringStream("The first line\nthe second line\nthe third line")
    var lines: seq[string]
    for line in strm.lines():
      lines.add line
    doAssert lines == @["The first line", "the second line", "the third line"]
    strm.close()

  var line: string
  while s.readLine(line):
    yield line

type
  StringStream* = ref StringStreamObj
    ## A stream that encapsulates a string.
  StringStreamObj* = object of StreamObj
    ## A string stream object.
    data*: string ## A string data.
                  ## This is updated when called `writeLine` etc.
    pos: int

when (NimMajor, NimMinor) < (1, 3) and defined(js):
  proc ssAtEnd(s: Stream): bool {.compileTime.} =
    var s = StringStream(s)
    return s.pos >= s.data.len

  proc ssSetPosition(s: Stream, pos: int) {.compileTime.} =
    var s = StringStream(s)
    s.pos = clamp(pos, 0, s.data.len)

  proc ssGetPosition(s: Stream): int {.compileTime.} =
    var s = StringStream(s)
    return s.pos

  proc ssReadDataStr(s: Stream, buffer: var string, slice: Slice[int]): int {.compileTime.} =
    var s = StringStream(s)
    result = min(slice.b + 1 - slice.a, s.data.len - s.pos)
    if result > 0:
      buffer[slice.a..<slice.a+result] = s.data[s.pos..<s.pos+result]
      inc(s.pos, result)
    else:
      result = 0

  proc ssClose(s: Stream) {.compileTime.} =
    var s = StringStream(s)
    s.data = ""

  proc newStringStream*(s: string = ""): owned StringStream {.compileTime.} =
    new(result)
    result.data = s
    result.pos = 0
    result.closeImpl = ssClose
    result.atEndImpl = ssAtEnd
    result.setPositionImpl = ssSetPosition
    result.getPositionImpl = ssGetPosition
    result.readDataStrImpl = ssReadDataStr

  proc readAll*(s: Stream): string {.compileTime.} =
    const bufferSize = 1024
    var bufferr: string
    bufferr.setLen(bufferSize)
    while true:
      let readBytes = readDataStr(s, bufferr, 0..<bufferSize)
      if readBytes == 0:
        break
      let prevLen = result.len
      result.setLen(prevLen + readBytes)
      result[prevLen..<prevLen+readBytes] = bufferr[0..<readBytes]
      if readBytes < bufferSize:
        break

else: # after 1.3 or JS not defined
  proc ssAtEnd(s: Stream): bool =
    var s = StringStream(s)
    return s.pos >= s.data.len

  proc ssSetPosition(s: Stream, pos: int) =
    var s = StringStream(s)
    s.pos = clamp(pos, 0, s.data.len)

  proc ssGetPosition(s: Stream): int =
    var s = StringStream(s)
    return s.pos

  proc ssReadDataStr(s: Stream, buffer: var string, slice: Slice[int]): int =
    var s = StringStream(s)
    result = min(slice.b + 1 - slice.a, s.data.len - s.pos)
    if result > 0:
      jsOrVmBlock:
        buffer[slice.a..<slice.a+result] = s.data[s.pos..<s.pos+result]
      do:
        copyMem(unsafeAddr buffer[slice.a], addr s.data[s.pos], result)
      inc(s.pos, result)
    else:
      result = 0

  proc ssReadData(s: Stream, buffer: pointer, bufLen: int): int =
    var s = StringStream(s)
    result = min(bufLen, s.data.len - s.pos)
    if result > 0:
      when defined(js):
        try:
          cast[ptr string](buffer)[][0..<result] = s.data[s.pos..<s.pos+result]
        except:
          raise newException(Defect, "could not read string stream, " &
            "did you use a non-string buffer pointer?", getCurrentException())
      elif not defined(nimscript):
        copyMem(buffer, addr(s.data[s.pos]), result)
      inc(s.pos, result)
    else:
      result = 0

  proc ssPeekData(s: Stream, buffer: pointer, bufLen: int): int =
    var s = StringStream(s)
    result = min(bufLen, s.data.len - s.pos)
    if result > 0:
      when defined(js):
        try:
          cast[ptr string](buffer)[][0..<result] = s.data[s.pos..<s.pos+result]
        except:
          raise newException(Defect, "could not peek string stream, " &
            "did you use a non-string buffer pointer?", getCurrentException())
      elif not defined(nimscript):
        copyMem(buffer, addr(s.data[s.pos]), result)
    else:
      result = 0

  proc ssWriteData(s: Stream, buffer: pointer, bufLen: int) =
    var s = StringStream(s)
    if bufLen <= 0:
      return
    if s.pos + bufLen > s.data.len:
      setLen(s.data, s.pos + bufLen)
    when defined(js):
      try:
        s.data[s.pos..<s.pos+bufLen] = cast[ptr string](buffer)[][0..<bufLen]
      except:
        raise newException(Defect, "could not write to string stream, " &
          "did you use a non-string buffer pointer?", getCurrentException())
    elif not defined(nimscript):
      copyMem(addr(s.data[s.pos]), buffer, bufLen)
    inc(s.pos, bufLen)

  proc ssClose(s: Stream) =
    var s = StringStream(s)
    s.data = ""

  proc newStringStream*(s: sink string = ""): owned StringStream =
    ## Creates a new stream from the string `s`.
    ##
    ## See also:
    ## * `newFileStream proc <#newFileStream,File>`_ creates a file stream from
    ##   opened File.
    ## * `newFileStream proc <#newFileStream,string,FileMode,int>`_  creates a
    ##   file stream from the file name and the mode.
    ## * `openFileStream proc <#openFileStream,string,FileMode,int>`_ creates a
    ##   file stream from the file name and the mode.
    runnableExamples:
      var strm = newStringStream("The first line\nthe second line\nthe third line")
      doAssert strm.readLine() == "The first line"
      doAssert strm.readLine() == "the second line"
      doAssert strm.readLine() == "the third line"
      strm.close()

    new(result)
    result.data = s
    when nimvm:
      discard
    else:
      when declared(prepareMutation):
        prepareMutation(result.data) # Allows us to mutate using `addr` logic like `copyMem`, otherwise it errors.
    result.pos = 0
    result.closeImpl = ssClose
    result.atEndImpl = ssAtEnd
    result.setPositionImpl = ssSetPosition
    result.getPositionImpl = ssGetPosition
    result.readDataStrImpl = ssReadDataStr
    when nimvm:
      discard
    else:
      result.readDataImpl = ssReadData
      result.peekDataImpl = ssPeekData
      result.writeDataImpl = ssWriteData

type
  FileStream* = ref FileStreamObj
    ## A stream that encapsulates a `File`.
    ##
    ## **Note:** Not available for JS backend.
  FileStreamObj* = object of Stream
    ## A file stream object.
    ##
    ## **Note:** Not available for JS backend.
    f: File

proc fsClose(s: Stream) =
  if FileStream(s).f != nil:
    close(FileStream(s).f)
    FileStream(s).f = nil
proc fsFlush(s: Stream) = flushFile(FileStream(s).f)
proc fsAtEnd(s: Stream): bool = return endOfFile(FileStream(s).f)
proc fsSetPosition(s: Stream, pos: int) = setFilePos(FileStream(s).f, pos)
proc fsGetPosition(s: Stream): int = return int(getFilePos(FileStream(s).f))

proc fsReadData(s: Stream, buffer: pointer, bufLen: int): int =
  result = readBuffer(FileStream(s).f, buffer, bufLen)

proc fsReadDataStr(s: Stream, buffer: var string, slice: Slice[int]): int =
  result = readBuffer(FileStream(s).f, addr buffer[slice.a], slice.b + 1 - slice.a)

proc fsPeekData(s: Stream, buffer: pointer, bufLen: int): int =
  let pos = fsGetPosition(s)
  defer: fsSetPosition(s, pos)
  result = readBuffer(FileStream(s).f, buffer, bufLen)

proc fsWriteData(s: Stream, buffer: pointer, bufLen: int) =
  if writeBuffer(FileStream(s).f, buffer, bufLen) != bufLen:
    raise newEIO("cannot write to stream")

proc fsReadLine(s: Stream, line: var string): bool =
  result = readLine(FileStream(s).f, line)

proc newFileStream*(f: File): owned FileStream =
  ## Creates a new stream from the file `f`.
  ##
  ## **Note:** Not available for JS backend.
  ##
  ## See also:
  ## * `newStringStream proc <#newStringStream,string>`_ creates a new stream
  ##   from string.
  ## * `newFileStream proc <#newFileStream,string,FileMode,int>`_ is the same
  ##   as using `open proc <syncio.html#open,File,string,FileMode,int>`_
  ##   on Examples.
  ## * `openFileStream proc <#openFileStream,string,FileMode,int>`_ creates a
  ##   file stream from the file name and the mode.
  runnableExamples:
    ## Input (somefile.txt):
    ## The first line
    ## the second line
    ## the third line
    var f: File
    if open(f, "somefile.txt", fmRead, -1):
      var strm = newFileStream(f)
      var line = ""
      while strm.readLine(line):
        echo line
      ## Output:
      ## The first line
      ## the second line
      ## the third line
      strm.close()

  new(result)
  result.f = f
  result.closeImpl = fsClose
  result.atEndImpl = fsAtEnd
  result.setPositionImpl = fsSetPosition
  result.getPositionImpl = fsGetPosition
  result.readDataStrImpl = fsReadDataStr
  result.readDataImpl = fsReadData
  result.readLineImpl = fsReadLine
  result.peekDataImpl = fsPeekData
  result.writeDataImpl = fsWriteData
  result.flushImpl = fsFlush

proc newFileStream*(filename: string, mode: FileMode = fmRead,
    bufSize: int = -1): owned FileStream =
  ## Creates a new stream from the file named `filename` with the mode `mode`.
  ##
  ## If the file cannot be opened, `nil` is returned. See the `io module
  ## <syncio.html>`_ for a list of available `FileMode enums <syncio.html#FileMode>`_.
  ##
  ## **Note:**
  ## * **This function returns nil in case of failure.**
  ##   To prevent unexpected behavior and ensure proper error handling,
  ##   use `openFileStream proc <#openFileStream,string,FileMode,int>`_
  ##   instead.
  ## * Not available for JS backend.
  ##
  ## See also:
  ## * `newStringStream proc <#newStringStream,string>`_ creates a new stream
  ##   from string.
  ## * `newFileStream proc <#newFileStream,File>`_ creates a file stream from
  ##   opened File.
  ## * `openFileStream proc <#openFileStream,string,FileMode,int>`_ creates a
  ##   file stream from the file name and the mode.
  runnableExamples:
    from std/os import removeFile
    var strm = newFileStream("somefile.txt", fmWrite)
    if not isNil(strm):
      strm.writeLine("The first line")
      strm.writeLine("the second line")
      strm.writeLine("the third line")
      strm.close()
      ## Output (somefile.txt)
      ## The first line
      ## the second line
      ## the third line
      removeFile("somefile.txt")

  var f: File
  if open(f, filename, mode, bufSize): result = newFileStream(f)

proc openFileStream*(filename: string, mode: FileMode = fmRead,
    bufSize: int = -1): owned FileStream =
  ## Creates a new stream from the file named `filename` with the mode `mode`.
  ## If the file cannot be opened, an IO exception is raised.
  ##
  ## **Note:** Not available for JS backend.
  ##
  ## See also:
  ## * `newStringStream proc <#newStringStream,string>`_ creates a new stream
  ##   from string.
  ## * `newFileStream proc <#newFileStream,File>`_ creates a file stream from
  ##   opened File.
  ## * `newFileStream proc <#newFileStream,string,FileMode,int>`_  creates a
  ##   file stream from the file name and the mode.
  runnableExamples:
    try:
      ## Input (somefile.txt):
      ## The first line
      ## the second line
      ## the third line
      var strm = openFileStream("somefile.txt")
      echo strm.readLine()
      ## Output:
      ## The first line
      strm.close()
    except:
      stderr.write getCurrentExceptionMsg()

  var f: File
  if open(f, filename, mode, bufSize):
    return newFileStream(f)
  else:
    raise newEIO("cannot open file stream: " & filename)

when false:
  type
    FileHandleStream* = ref FileHandleStreamObj
    FileHandleStreamObj* = object of Stream
      handle*: FileHandle
      pos: int

  proc newEOS(msg: string): ref OSError =
    new(result)
    result.msg = msg

  proc hsGetPosition(s: FileHandleStream): int =
    return s.pos

  when defined(windows):
    # do not import windows as this increases compile times:
    discard
  else:
    import posix

    proc hsSetPosition(s: FileHandleStream, pos: int) =
      discard lseek(s.handle, pos, SEEK_SET)

    proc hsClose(s: FileHandleStream) = discard close(s.handle)
    proc hsAtEnd(s: FileHandleStream): bool =
      var pos = hsGetPosition(s)
      var theEnd = lseek(s.handle, 0, SEEK_END)
      result = pos >= theEnd
      hsSetPosition(s, pos) # set position back

    proc hsReadData(s: FileHandleStream, buffer: pointer, bufLen: int): int =
      result = posix.read(s.handle, buffer, bufLen)
      inc(s.pos, result)

    proc hsPeekData(s: FileHandleStream, buffer: pointer, bufLen: int): int =
      result = posix.read(s.handle, buffer, bufLen)

    proc hsWriteData(s: FileHandleStream, buffer: pointer, bufLen: int) =
      if posix.write(s.handle, buffer, bufLen) != bufLen:
        raise newEIO("cannot write to stream")
      inc(s.pos, bufLen)

  proc newFileHandleStream*(handle: FileHandle): owned FileHandleStream =
    new(result)
    result.handle = handle
    result.pos = 0
    result.close = hsClose
    result.atEnd = hsAtEnd
    result.setPosition = hsSetPosition
    result.getPosition = hsGetPosition
    result.readData = hsReadData
    result.peekData = hsPeekData
    result.writeData = hsWriteData

  proc newFileHandleStream*(filename: string,
                            mode: FileMode): owned FileHandleStream =
    when defined(windows):
      discard
    else:
      var flags: cint
      case mode
      of fmRead: flags = posix.O_RDONLY
      of fmWrite: flags = O_WRONLY or int(O_CREAT)
      of fmReadWrite: flags = O_RDWR or int(O_CREAT)
      of fmReadWriteExisting: flags = O_RDWR
      of fmAppend: flags = O_WRONLY or int(O_CREAT) or O_APPEND
      static: doAssert false # handle bug #17888
      var handle = open(filename, flags)
      if handle < 0: raise newEOS("posix.open() call failed")
    result = newFileHandleStream(handle)