src/pkg/encoding/json/stream.go - The Go Programming Language

Golang

Source file src/pkg/encoding/json/stream.go

     1	// Copyright 2010 The Go Authors.  All rights reserved.
     2	// Use of this source code is governed by a BSD-style
     3	// license that can be found in the LICENSE file.
     4	
     5	package json
     6	
     7	import (
     8		"errors"
     9		"io"
    10	)
    11	
    12	// A Decoder reads and decodes JSON objects from an input stream.
    13	type Decoder struct {
    14		r    io.Reader
    15		buf  []byte
    16		d    decodeState
    17		scan scanner
    18		err  error
    19	}
    20	
    21	// NewDecoder returns a new decoder that reads from r.
    22	//
    23	// The decoder introduces its own buffering and may
    24	// read data from r beyond the JSON values requested.
    25	func NewDecoder(r io.Reader) *Decoder {
    26		return &Decoder{r: r}
    27	}
    28	
    29	// Decode reads the next JSON-encoded value from its
    30	// input and stores it in the value pointed to by v.
    31	//
    32	// See the documentation for Unmarshal for details about
    33	// the conversion of JSON into a Go value.
    34	func (dec *Decoder) Decode(v interface{}) error {
    35		if dec.err != nil {
    36			return dec.err
    37		}
    38	
    39		n, err := dec.readValue()
    40		if err != nil {
    41			return err
    42		}
    43	
    44		// Don't save err from unmarshal into dec.err:
    45		// the connection is still usable since we read a complete JSON
    46		// object from it before the error happened.
    47		dec.d.init(dec.buf[0:n])
    48		err = dec.d.unmarshal(v)
    49	
    50		// Slide rest of data down.
    51		rest := copy(dec.buf, dec.buf[n:])
    52		dec.buf = dec.buf[0:rest]
    53	
    54		return err
    55	}
    56	
    57	// readValue reads a JSON value into dec.buf.
    58	// It returns the length of the encoding.
    59	func (dec *Decoder) readValue() (int, error) {
    60		dec.scan.reset()
    61	
    62		scanp := 0
    63		var err error
    64	Input:
    65		for {
    66			// Look in the buffer for a new value.
    67			for i, c := range dec.buf[scanp:] {
    68				dec.scan.bytes++
    69				v := dec.scan.step(&dec.scan, int(c))
    70				if v == scanEnd {
    71					scanp += i
    72					break Input
    73				}
    74				// scanEnd is delayed one byte.
    75				// We might block trying to get that byte from src,
    76				// so instead invent a space byte.
    77				if v == scanEndObject && dec.scan.step(&dec.scan, ' ') == scanEnd {
    78					scanp += i + 1
    79					break Input
    80				}
    81				if v == scanError {
    82					dec.err = dec.scan.err
    83					return 0, dec.scan.err
    84				}
    85			}
    86			scanp = len(dec.buf)
    87	
    88			// Did the last read have an error?
    89			// Delayed until now to allow buffer scan.
    90			if err != nil {
    91				if err == io.EOF {
    92					if dec.scan.step(&dec.scan, ' ') == scanEnd {
    93						break Input
    94					}
    95					if nonSpace(dec.buf) {
    96						err = io.ErrUnexpectedEOF
    97					}
    98				}
    99				dec.err = err
   100				return 0, err
   101			}
   102	
   103			// Make room to read more into the buffer.
   104			const minRead = 512
   105			if cap(dec.buf)-len(dec.buf) < minRead {
   106				newBuf := make([]byte, len(dec.buf), 2*cap(dec.buf)+minRead)
   107				copy(newBuf, dec.buf)
   108				dec.buf = newBuf
   109			}
   110	
   111			// Read.  Delay error for next iteration (after scan).
   112			var n int
   113			n, err = dec.r.Read(dec.buf[len(dec.buf):cap(dec.buf)])
   114			dec.buf = dec.buf[0 : len(dec.buf)+n]
   115		}
   116		return scanp, nil
   117	}
   118	
   119	func nonSpace(b []byte) bool {
   120		for _, c := range b {
   121			if !isSpace(rune(c)) {
   122				return true
   123			}
   124		}
   125		return false
   126	}
   127	
   128	// An Encoder writes JSON objects to an output stream.
   129	type Encoder struct {
   130		w   io.Writer
   131		e   encodeState
   132		err error
   133	}
   134	
   135	// NewEncoder returns a new encoder that writes to w.
   136	func NewEncoder(w io.Writer) *Encoder {
   137		return &Encoder{w: w}
   138	}
   139	
   140	// Encode writes the JSON encoding of v to the connection.
   141	//
   142	// See the documentation for Marshal for details about the
   143	// conversion of Go values to JSON.
   144	func (enc *Encoder) Encode(v interface{}) error {
   145		if enc.err != nil {
   146			return enc.err
   147		}
   148		enc.e.Reset()
   149		err := enc.e.marshal(v)
   150		if err != nil {
   151			return err
   152		}
   153	
   154		// Terminate each value with a newline.
   155		// This makes the output look a little nicer
   156		// when debugging, and some kind of space
   157		// is required if the encoded value was a number,
   158		// so that the reader knows there aren't more
   159		// digits coming.
   160		enc.e.WriteByte('\n')
   161	
   162		if _, err = enc.w.Write(enc.e.Bytes()); err != nil {
   163			enc.err = err
   164		}
   165		return err
   166	}
   167	
   168	// RawMessage is a raw encoded JSON object.
   169	// It implements Marshaler and Unmarshaler and can
   170	// be used to delay JSON decoding or precompute a JSON encoding.
   171	type RawMessage []byte
   172	
   173	// MarshalJSON returns *m as the JSON encoding of m.
   174	func (m *RawMessage) MarshalJSON() ([]byte, error) {
   175		return *m, nil
   176	}
   177	
   178	// UnmarshalJSON sets *m to a copy of data.
   179	func (m *RawMessage) UnmarshalJSON(data []byte) error {
   180		if m == nil {
   181			return errors.New("json.RawMessage: UnmarshalJSON on nil pointer")
   182		}
   183		*m = append((*m)[0:0], data...)
   184		return nil
   185	}
   186	
   187	var _ Marshaler = (*RawMessage)(nil)
   188	var _ Unmarshaler = (*RawMessage)(nil)