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

JSON errors: line numbers #24

Open
joonas-fi opened this issue Sep 11, 2023 · 1 comment
Open

JSON errors: line numbers #24

joonas-fi opened this issue Sep 11, 2023 · 1 comment
Labels
enhancement New feature or request

Comments

@joonas-fi
Copy link
Member

Playground code:

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.
type lineCounter struct {
	committedLines int
	committedBytes int64

	uncommitted      []byte
	uncommittedLines int
}

func (l *lineCounter) LineNumberFromOffset(offset int64) int {
	if offset < l.committedBytes {
		panic("offset < l.committedBytes")
	}

	intoUncommitted := offset - l.committedBytes

	linesIntoUncommitted := countNewlines(l.uncommitted[:intoUncommitted])

	return l.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.uncommittedLines

	l.uncommittedLines = countNewlines(buf)
	l.uncommitted = buf

	return len(buf), nil
}

func main() {
	lc := &lineCounter{}

	jd := json.NewDecoder(io.TeeReader(strings.NewReader(`{


	"Foo": "bar"}`), lc))
	err := jd.Decode(&struct{ Foo struct{} }{})
	if err != nil {
		fmt.Printf("err=%v pos=%d\n", err, lc.LineNumberFromOffset(jd.InputOffset()))
	}

	fmt.Println("Hello, 世界")
}

func countNewlines(buf []byte) int {
	newlines := 0

	for _, ch := range buf {
		if ch == '\n' {
			newlines++
		}
	}

	return newlines
}
@joonas-fi joonas-fi added the enhancement New feature or request label Sep 11, 2023
@joonas-fi
Copy link
Member Author

golang/go#43513

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant