The Go Programming Language

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

release.r60.3. Except as noted, this content is licensed under a Creative Commons Attribution 3.0 License.