blob: f143b3f0ade62020b8c0bf0632296b3c85240adc [file] [log] [blame]
Russ Cox0e8384a2010-04-27 10:46:37 -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 (
Russ Cox0e8384a2010-04-27 10:46:37 -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
Brad Fitzpatrick9b8d4e02011-04-15 08:14:34 -070026// Decode reads the next JSON-encoded value from its
27// input and stores it in the value pointed to by v.
Russ Cox0e8384a2010-04-27 10:46:37 -070028//
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:] {
Brad Fitzpatrick9b8d4e02011-04-15 08:14:34 -070065 dec.scan.bytes++
Russ Cox0e8384a2010-04-27 10:46:37 -070066 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
116func 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.
126type 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.
133func 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.
141func (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.
168type RawMessage []byte
169
170// MarshalJSON returns *m as the JSON encoding of m.
171func (m *RawMessage) MarshalJSON() ([]byte, os.Error) {
172 return *m, nil
173}
174
175// UnmarshalJSON sets *m to a copy of data.
176func (m *RawMessage) UnmarshalJSON(data []byte) os.Error {
177 if m == nil {
178 return os.NewError("json.RawMessage: UnmarshalJSON on nil pointer")
179 }
Kyle Consalus009aebd2010-12-01 11:59:13 -0800180 *m = append((*m)[0:0], data...)
Russ Cox0e8384a2010-04-27 10:46:37 -0700181 return nil
182}
183
184var _ Marshaler = (*RawMessage)(nil)
185var _ Unmarshaler = (*RawMessage)(nil)