gitee.com/quant1x/pkg@v0.2.8/fastjson/scanner.go (about)

     1  package fastjson
     2  
     3  import (
     4  	"errors"
     5  )
     6  
     7  // Scanner scans a series of JSON values. Values may be delimited by whitespace.
     8  //
     9  // Scanner may parse JSON lines ( http://jsonlines.org/ ).
    10  //
    11  // Scanner may be re-used for subsequent parsing.
    12  //
    13  // Scanner cannot be used from concurrent goroutines.
    14  //
    15  // Use Parser for parsing only a single JSON value.
    16  type Scanner struct {
    17  	// b contains a working copy of json value passed to Init.
    18  	b []byte
    19  
    20  	// s points to the next JSON value to parse.
    21  	s string
    22  
    23  	// err contains the last error.
    24  	err error
    25  
    26  	// v contains the last parsed JSON value.
    27  	v *Value
    28  
    29  	// c is used for caching JSON values.
    30  	c cache
    31  }
    32  
    33  // Init initializes sc with the given s.
    34  //
    35  // s may contain multiple JSON values, which may be delimited by whitespace.
    36  func (sc *Scanner) Init(s string) {
    37  	sc.b = append(sc.b[:0], s...)
    38  	sc.s = b2s(sc.b)
    39  	sc.err = nil
    40  	sc.v = nil
    41  }
    42  
    43  // InitBytes initializes sc with the given b.
    44  //
    45  // b may contain multiple JSON values, which may be delimited by whitespace.
    46  func (sc *Scanner) InitBytes(b []byte) {
    47  	sc.Init(b2s(b))
    48  }
    49  
    50  // Next parses the next JSON value from s passed to Init.
    51  //
    52  // Returns true on success. The parsed value is available via Value call.
    53  //
    54  // Returns false either on error or on the end of s.
    55  // Call Error in order to determine the cause of the returned false.
    56  func (sc *Scanner) Next() bool {
    57  	if sc.err != nil {
    58  		return false
    59  	}
    60  
    61  	sc.s = skipWS(sc.s)
    62  	if len(sc.s) == 0 {
    63  		sc.err = errEOF
    64  		return false
    65  	}
    66  
    67  	sc.c.reset()
    68  	v, tail, err := parseValue(sc.s, &sc.c, 0)
    69  	if err != nil {
    70  		sc.err = err
    71  		return false
    72  	}
    73  
    74  	sc.s = tail
    75  	sc.v = v
    76  	return true
    77  }
    78  
    79  // Error returns the last error.
    80  func (sc *Scanner) Error() error {
    81  	if sc.err == errEOF {
    82  		return nil
    83  	}
    84  	return sc.err
    85  }
    86  
    87  // Value returns the last parsed value.
    88  //
    89  // The value is valid until the Next call.
    90  func (sc *Scanner) Value() *Value {
    91  	return sc.v
    92  }
    93  
    94  var errEOF = errors.New("end of s")