diff --git a/lib/pure/streams.nim b/lib/pure/streams.nim index 0a187cea22..61aa520d19 100644 --- a/lib/pure/streams.nim +++ b/lib/pure/streams.nim @@ -251,16 +251,29 @@ when not defined(js): strm.close() const bufferSize = 1024 - 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 + when nimvm: + var buffer2: string + buffer2.setLen(bufferSize) + while true: + let readBytes = readDataStr(s, buffer2, 0.. 0: break else: return false - line.string.add(c) + when nimvm: #Bug #12282 + line.add(c) + else: + line.string.add(c) result = true proc peekLine*(s: Stream, line: var TaintedString): bool = @@ -999,21 +1023,73 @@ iterator lines*(s: Stream): TaintedString = while s.readLine(line): yield line -when not defined(js): +type + StringStream* = ref StringStreamObj + ## A stream that encapsulates a string. + ## + ## **Note:** Not available for JS backend. + StringStreamObj* = object of StreamObj + ## A string stream object. + ## + ## **Note:** Not available for JS backend. + data*: string ## A string data. + ## This is updated when called `writeLine` etc. + pos: int - type - StringStream* = ref StringStreamObj - ## A stream that encapsulates a string. - ## - ## **Note:** Not available for JS backend. - StringStreamObj* = object of StreamObj - ## A string stream object. - ## - ## **Note:** Not available for JS backend. - data*: string ## A string data. - ## This is updated when called `writeLine` etc. - pos: int +when defined(js): #This section exists so that string streams work at compile time for the js backend + 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..= s.data.len @@ -1031,8 +1107,7 @@ when not defined(js): result = min(slice.b + 1 - slice.a, s.data.len - s.pos) if result > 0: when nimvm: - for i in 0 ..< result: # sorry, but no fast string splicing on the vm. - buffer[slice.a + i] = s.data[s.pos + i] + buffer[slice.a..