Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added support for reading a string as an io.Reader #701

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions iter_str_reader.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package jsoniter

import "io"

// Returns a reader that can be used to read the following string until EOF.
// Using the reader after EOF is undefined behavior, and so is using the reader
// when when the current token isn't a string.
func (iter *Iterator) ReadStringAsReader() (r io.Reader) {
c := iter.nextToken()
if c == '"' {
return iterStrReader{iter}
}
iter.ReportError("ReadStringAsReader", `expects " or n, but found `+string([]byte{c}))
return
}

var _ io.Reader = iterStrReader{}

type iterStrReader struct {
iter *Iterator
}

func (r iterStrReader) Read(dst []byte) (n int, err error) {
for i := r.iter.head; i < r.iter.tail; i++ {
// require ascii string and no escape
// for: field name, base64, number
if r.iter.buf[i] == '"' {
n = copy(dst, r.iter.buf[r.iter.head:i])
r.iter.head += n + 1
err = io.EOF
return
}
}

n = copy(dst, r.iter.buf[r.iter.head:])
r.iter.head += n

if r.iter.head == r.iter.tail {
if !r.iter.loadMore() {
err = io.ErrUnexpectedEOF
}
}

return
}
35 changes: 35 additions & 0 deletions iter_str_reader_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package jsoniter

import (
"bytes"
"fmt"
"io"
)

func ExampleIterator_ReadStringAsReader() {
json := bytes.NewBufferString(`{"foo":"abcdefghijklmnopqrstuvwxyz"}`)
iter := Parse(ConfigDefault, json, 16)

_ = iter.ReadObject()
r := iter.ReadStringAsReader()
buf := make([]byte, 8)

for {
n, err := r.Read(buf)
fmt.Println(string(buf[:n]))

if err != nil {
if err != io.EOF {
panic(err)
}
break
}
}

// Output:
//
// abcdefgh
// ijklmnop
// qrstuvwx
// yz
}