Unable to get StringStream created from marshal to output the data

194 views Asked by At

Say I have a type like this:

type
  Foo = object of RootObj
    f1: string
  Bar = object of Foo
    b1: string

And I marshal an instance like this:

var bar: Bar
bar.f1 = "FOO"
bar.b1 = "BAR"

var s = newStringStream()
s.store(bar)

I can read its data directly:

echo s.data # outputs {"b1": "BAR", "f1": "FOO"}

But I'm unable to read it using readLine() or any other of the reading procs:

var line: TaintedString = ""
while s.readLine(line):
    echo line

There's simply no output.


It works fine if I'm not creating the data using marshal.store.

var s = newStringStream("foo\nbar")

var line: TaintedString = ""
while s.readLine(line):
    echo line # outputs `foo` then `bar`

So it seems I'm missing something probably very fundamental and obvious. Any idea what that may be?

2

There are 2 answers

1
Reimer Behrends On BEST ANSWER

Streams work like files; when you write to them, the current position within the file moves with the writes. You can observe this with echo s.getPosition before and after the call.

If you create a new string stream from a string, the position will be set to zero.

In order to make this work, simply use

s.setPosition(0)

after a write.

0
uran On

StringStream has the same position value for both reading and writing. Do you do setPosition to 0 before trying to read?