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