vitess.io/vitess@v0.16.2/go/json2/unmarshal.go (about)

     1  /*
     2  Copyright 2019 The Vitess Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  // Package json2 provides some improvements over the original json.
    18  package json2
    19  
    20  import (
    21  	"bytes"
    22  	"encoding/json"
    23  	"fmt"
    24  
    25  	"google.golang.org/protobuf/encoding/protojson"
    26  	"google.golang.org/protobuf/proto"
    27  )
    28  
    29  var carriageReturn = []byte("\n")
    30  
    31  // Unmarshal wraps json.Unmarshal, but returns errors that
    32  // also mention the line number. This function is not very
    33  // efficient and should not be used for high QPS operations.
    34  func Unmarshal(data []byte, v any) error {
    35  	if pb, ok := v.(proto.Message); ok {
    36  		return annotate(data, protojson.Unmarshal(data, pb))
    37  	}
    38  	return annotate(data, json.Unmarshal(data, v))
    39  }
    40  
    41  func annotate(data []byte, err error) error {
    42  	if err == nil {
    43  		return nil
    44  	}
    45  	syntax, ok := err.(*json.SyntaxError)
    46  	if !ok {
    47  		return err
    48  	}
    49  
    50  	start := bytes.LastIndex(data[:syntax.Offset], carriageReturn) + 1
    51  	line, pos := bytes.Count(data[:start], carriageReturn)+1, int(syntax.Offset)-start
    52  
    53  	return fmt.Errorf("line: %d, position %d: %v", line, pos, err)
    54  }