You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
package main
import (
"encoding/json""fmt""io""strings"
)
// (ab)using the fact that the JSON decoder has accumulated over all it's read plus it's working on the new buffer// it's about to receive now.typelineCounterstruct {
committedLinesintcommittedBytesint64uncommitted []byteuncommittedLinesint
}
func (l*lineCounter) LineNumberFromOffset(offsetint64) int {
ifoffset<l.committedBytes {
panic("offset < l.committedBytes")
}
intoUncommitted:=offset-l.committedByteslinesIntoUncommitted:=countNewlines(l.uncommitted[:intoUncommitted])
returnl.committedLines+linesIntoUncommitted
}
var_ io.Writer= (*lineCounter)(nil)
func (l*lineCounter) Write(buf []byte) (int, error) {
// the fact that `Write()` was called means that the previous uncommitted buffer was consumed fully. "commit" now.l.committedBytes+=int64(len(l.uncommitted))
l.committedLines+=l.uncommittedLinesl.uncommittedLines=countNewlines(buf)
l.uncommitted=bufreturnlen(buf), nil
}
funcmain() {
lc:=&lineCounter{}
jd:=json.NewDecoder(io.TeeReader(strings.NewReader(`{ "Foo": "bar"}`), lc))
err:=jd.Decode(&struct{ Foostruct{} }{})
iferr!=nil {
fmt.Printf("err=%v pos=%d\n", err, lc.LineNumberFromOffset(jd.InputOffset()))
}
fmt.Println("Hello, 世界")
}
funccountNewlines(buf []byte) int {
newlines:=0for_, ch:=rangebuf {
ifch=='\n' {
newlines++
}
}
returnnewlines
}
The text was updated successfully, but these errors were encountered:
Playground code:
The text was updated successfully, but these errors were encountered: