Nim icon indicating copy to clipboard operation
Nim copied to clipboard

streams.write doesn't work with openArray or seq type arguments

Open demotomohiro opened this issue 5 years ago • 3 comments

Example

import streams

template testStream(arg: untyped): untyped =
  var ss = newStringStream()
  ss.write(arg)
  ss.flush()
  echo ss.data

let
  ary = ['N', 'i', 'm', ' ', 'l', 'a', 'n', 'g', 'u', 'a', 'g', 'e', '\0']
  sq = @ary
testStream(ary)
testStream(sq)

proc test(ary: openArray[char]) =
  testStream(ary)

test(ary)
test(sq)

Current Output

Nim language
P�P
Nim lang
Nim lang

Expected Output

Nim language
Nim language
Nim language
Nim language

Possible Solution

Add following overload to streams module.

proc write*[T](s: Stream, x: openArray[T] | seq[T]) =
  for v in x:
    s.write(v)

  when false:
    # Edit: Following code doesn't work correctly when T is seq
    if x.len != 0:
      writeData(s, unsafeAddr(x[0]), sizeof(T) * x.len)

Without proc write[T](s: Stream, x: seq[T]), proc write*[T](s: Stream, x: T) is called for a seq type argument and it doesn't work.

Alternative Solution

Forbid calling streams.write with openArray or seq. User must use streams.writeData or call streams.write for the each elements.

proc write*[T](s: Stream, x: openArray[T] | seq[T]) {.error.}

Additional Information

f:\temp>nim -v
Nim Compiler Version 1.3.5 [Windows: amd64]
Compiled at 2020-06-02
Copyright (c) 2006-2020 by Andreas Rumpf

git hash: e5b64af8317eb0f5e8b9912691b69aab4cd26adf
active boot switches: -d:release

demotomohiro avatar Jun 02 '20 04:06 demotomohiro