Source

gomongo / bson.go

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
// Based on the Go json package.
// Original Copyright 2009 The Go Authors. All rights reserved.
// Modifications Copyright 2009 Michael Stephens.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE and LICENSE.GO files.

package mongo

import (
	"os";
	"io";
	"io/ioutil";
	"fmt";
	"math";
	"time";
	"bytes";
	"strconv";
	"encoding/binary";
	"encoding/base64"
	"container/vector";
)

const (
	EOOKind	= iota;
	NumberKind;
	StringKind;
	ObjectKind;
	ArrayKind;
	BinaryKind;
	UndefinedKind;	// deprecated
	OIDKind;
	BooleanKind;
	DateKind;
	NullKind;
	RegexKind;
	RefKind;	// deprecated
	CodeKind;
	SymbolKind;
	CodeWithScope;
	IntKind;
	TimestampKind;
	LongKind;
	MinKeyKind;
	MaxKeyKind;
)

type BSON interface {
	Kind() int;
	Number() float64;
	String() string;
	OID() OID;
	Bool() bool;
	Date() *time.Time;
	Regex() (string, string);
	Int() int32;
	Long() int64;
	Get(s string) BSON;
	Elem(i int) BSON;
	Len() int;

	Bytes() []byte;
	
	//return the value as an interface {}
	Interface() interface {}
	
	DebugPrint() string
	
	//to allow marshalling a struct and then tacking on an ID.
	AddField(name string, value interface {}) os.Error
}

type OID []byte

var oidEncoding = base64.NewEncoding("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-")

func (oid OID) String() string {
	if oid == nil {
		return ""
	}
	b := [(12 + 2) / 3 * 4]byte{}[:]
	oidEncoding.Encode(b, []byte(oid))
	return string(b)
}

func NewOID(src string) (OID, os.Error) {
	if src == "" {
		return nil, nil
	}
	b := [12]byte{}[:]
	n, err := oidEncoding.Decode(b, []byte(src))
	if err != nil {
		return nil, err
	}
	if n != 12 {
		return nil, os.NewError("Incorrect number of bytes for OID")
	}
	return OID(b), nil
}

func (lhs OID) Less(rhs OID) bool {
	return bytes.Compare([]byte(lhs), []byte(rhs)) < 0
}

type _Null struct{}

var Null BSON = &_Null{}

func (*_Null) Kind() int		{ return NullKind }
func (*_Null) Number() float64		{ return 0 }
func (*_Null) String() string		{ return "null" }
func (*_Null) OID() OID		{ return nil }
func (*_Null) Bool() bool		{ return false }
func (*_Null) Date() *time.Time		{ return nil }
func (*_Null) Regex() (string, string)	{ return "", "" }
func (*_Null) Int() int32		{ return 0 }
func (*_Null) Long() int64		{ return 0 }
func (*_Null) Get(string) BSON		{ return Null }
func (*_Null) Elem(int) BSON		{ return Null }
func (*_Null) Len() int			{ return 0 }
func (*_Null) Bytes() []byte		{ return []byte{0} }
func (*_Null) Interface() interface {}		{ return nil }
func (*_Null) DebugPrint() string {return "NULL"}
func (*_Null) AddField(name string, value interface {}) os.Error {return os.NewError("Only allowed on structs")}

type _Number struct {
	value	float64;
	_Null;
}

func (n *_Number) Kind() int		{ return NumberKind }
func (n *_Number) Number() float64	{ return n.value }
func (n *_Number) Bytes() []byte {
	bits := math.Float64bits(n.value);
	b := []byte{0, 0, 0, 0, 0, 0, 0, 0};
	binary.LittleEndian.PutUint64(b, bits);
	return b;
}
func (obj *_Number) Interface() interface {}		{ return obj.value }
func (n *_Number) DebugPrint() string {return fmt.Sprintf("%vf", n.value)}

type _String struct {
	value	string;
	_Null;
}

func (s *_String) Kind() int		{ return StringKind }
func (s *_String) String() string	{ return s.value }
func (s *_String) Bytes() []byte {
	b := []byte{0, 0, 0, 0};
	l := len(s.value) + 1;
	binary.LittleEndian.PutUint32(b, uint32(l));

	buf := bytes.NewBuffer(b);
	buf.WriteString(s.value);
	buf.WriteByte(0);

	return buf.Bytes();
}
func (obj *_String) Interface() interface {}		{ return obj.value }
func (s *_String) DebugPrint() string {return fmt.Sprintf(`"%s"`, s.value)}

type _Object struct {
	value	map[string]BSON;
	_Null;
}

func (o *_Object) Kind() int	{ return ObjectKind }
func (o *_Object) Get(s string) BSON {
	if o.value == nil {
		return Null
	}

	b, ok := o.value[s];
	if !ok {
		return Null
	}

	return b;
}
func (o *_Object) Len() int	{ return len(o.value) }
func (o *_Object) Bytes() []byte {
	buf := bytes.NewBuffer([]byte{});
	for k, v := range o.value {
		buf.WriteByte(byte(v.Kind()));
		buf.WriteString(k);
		buf.WriteByte(0);
		buf.Write(v.Bytes());
	}
	buf.WriteByte(0);

	l := buf.Len() + 4;
	b := []byte{0, 0, 0, 0};
	binary.LittleEndian.PutUint32(b, uint32(l));
	return bytes.Add(b, buf.Bytes());
}
func (o *_Object) DebugPrint() (str string) {
	str = "{"
	comma := ""
	for k, v := range o.value {
		str += fmt.Sprintf(`%s"%s" : %s`, comma, k, v.DebugPrint())
		comma = ", "
	}
	str += "}"
	return
}
func (o *_Object) AddField(name string, value interface {}) os.Error {
	switch v := value.(type) {
		case string: o.value[name] = &_String{v, _Null{}}
		case uint64: o.value[name] = &_Long{int64(v), _Null{}}
		default: return os.NewError("Unhandled Type")
	}
	return nil
}

var EmptyObject BSON = &_Object{map[string]BSON{}, _Null{}}

type _Array struct {
	value	*vector.Vector;
	_Null;
}

func (a *_Array) Kind() int	{ return ArrayKind }
func (a *_Array) Elem(i int) BSON {
	if a.value == nil {
		return Null
	}

	if a.Len() < i {
		return Null
	}

	return a.value.At(i).(BSON);
}
func (a *_Array) Len() int	{ return a.value.Len() }
func (a *_Array) Bytes() []byte {
	buf := bytes.NewBuffer([]byte{});

	for i := 0; i < a.value.Len(); i++ {
		v := a.value.At(i).(BSON);
		buf.WriteByte(byte(v.Kind()));
		buf.WriteString(strconv.Itoa(i));
		buf.WriteByte(0);
		buf.Write(v.Bytes());
	}
	buf.WriteByte(0);

	l := buf.Len() + 4;
	b := []byte{0, 0, 0, 0};
	binary.LittleEndian.PutUint32(b, uint32(l));
	return bytes.Add(b, buf.Bytes());
}
func (a *_Array) DebugPrint() (str string) {
	str = "["
	for i := 0; i < a.value.Len(); i++ {
		str += a.value.At(i).(BSON).DebugPrint()
		if i < a.value.Len() - 1 {
			str += ", "
		}
	}
	str += "]"
	return
}

type _OID struct {
	value	[]byte;
	_Null;
}

func (o *_OID) Kind() int	{ return OIDKind }
func (o *_OID) OID() OID	{ return OID(o.value) }
func (o *_OID) Bytes() []byte	{ return o.value }
func (o *_OID) Interface() interface {}		{ return OID(o.value) }
func (o *_OID) DebugPrint() string {return fmt.Sprintf("%v", o.value)}

func OIDConstruct(b BSON) OID {
	var o OID
	copy(o[0:12], b.(*_OID).value)
	return o
}

type _Boolean struct {
	value	bool;
	_Null;
}

func (b *_Boolean) Kind() int	{ return BooleanKind }
func (b *_Boolean) Bool() bool	{ return b.value }
func (b *_Boolean) Bytes() []byte {
	if b.value {
		return []byte{1}
	}
	return []byte{0};
}
func (obj *_Boolean) Interface() interface {}		{return obj.value }
func (b *_Boolean) DebugPrint() string {
	if b.value {
		return "true"
	}
	return "false"
}

type _Date struct {
	value	*time.Time;
	_Null;
}

func (d *_Date) Kind() int		{ return DateKind }
func (d *_Date) Date() *time.Time	{ return d.value }
func (d *_Date) Bytes() []byte {
	b := []byte{0, 0, 0, 0, 0, 0, 0, 0};
	seconds := int64(0)
	if d.value != nil {
		seconds = d.value.Seconds()
	}
	mtime := seconds * 1000;
	binary.LittleEndian.PutUint64(b, uint64(mtime));
	return b;
}
func (obj *_Date) Interface() interface {}		{ return obj.value }
func (d *_Date) DebugPrint() string {return fmt.Sprintf("%s", d.value)}

type _Regex struct {
	regex, options	string;
	_Null;
}

func (r *_Regex) Kind() int			{ return RegexKind }
func (r *_Regex) Regex() (string, string)	{ return r.regex, r.options }
func (r *_Regex) Bytes() []byte {
	buf := bytes.NewBufferString(r.regex);
	buf.WriteByte(0);
	buf.WriteString(r.options);
	buf.WriteByte(0);
	return buf.Bytes();
}
func (r *_Regex) DebugPrint() string {return "Regex(" + r.regex + "," + r.options + ")"}

type _Int struct {
	value	int32;
	_Null;
}

func (i *_Int) Kind() int	{ return IntKind }
func (i *_Int) Int() int32	{ return i.value }
func (i *_Int) Bytes() []byte {
	b := []byte{0, 0, 0, 0};
	binary.LittleEndian.PutUint32(b, uint32(i.value));
	return b;
}
func (obj *_Int) Interface() interface {}		{ return obj.value }
func (i *_Int) DebugPrint() string {return fmt.Sprintf("%vi", i.value)}

type _Long struct {
	value	int64;
	_Null;
}

func (l *_Long) Kind() int	{ return LongKind }
func (l *_Long) Long() int64	{ return l.value }
func (l *_Long) Bytes() []byte {
	b := []byte{0, 0, 0, 0, 0, 0, 0, 0};
	binary.LittleEndian.PutUint64(b, uint64(l.value));
	return b;
}
func (obj *_Long) Interface() interface {}		{ return obj.value }
func (l *_Long) DebugPrint() string {return fmt.Sprintf("%vl", l.value)}

func Equal(a, b BSON) bool {
	switch {
	case a == nil && b == nil:
		return true
	case a == nil || b == nil:
		return false
	case a.Kind() != b.Kind():
		return false
	}

	switch a.Kind() {
	case NumberKind:
		return a.Number() == b.Number()
	case StringKind:
		return a.String() == b.String()
	case ObjectKind:
		obj := a.(*_Object).value;
		if len(obj) != len(b.(*_Object).value) {
			return false
		}
		for k, v := range obj {
			if !Equal(v, b.Get(k)) {
				return false
			}
		}
		return true;
	case ArrayKind:
		if a.Len() != b.Len() {
			return false
		}
		for i := 0; i < a.Len(); i++ {
			if !Equal(a.Elem(i), b.Elem(i)) {
				return false
			}
		}
		return true;
	case OIDKind:
		return bytes.Equal([]byte(a.OID()), []byte(b.OID()))
	case BooleanKind:
		return a.Bool() == b.Bool()
	case DateKind:
		return a.Date() == b.Date()
	case RegexKind:
		ar, ao := a.Regex();
		br, bo := b.Regex();
		return ar == br && ao == bo;
	case IntKind:
		return a.Int() == b.Int()
	case LongKind:
		return a.Long() == b.Long()
	}
	return true;

}

type Builder interface {
	// Set value
	Int64(i int64);
	Int32(i int32);
	Float64(f float64);
	String(s string);
	Bool(b bool);
	Date(d *time.Time);
	OID(o []byte);
	Regex(regex, options string);
	Null();
	Object();
	Array();

	// Create sub-Builders
	Key(s string) Builder;
	Elem(i int) Builder;

	// Flush changes to parent Builder if necessary.
	Flush();
}

type _BSONBuilder struct {
	ptr	*BSON;

	arr	*vector.Vector;
	elem	int;

	obj	map[string]BSON;
	key	string;
}

func (bb *_BSONBuilder) Put(b BSON) {
	switch {
	case bb.ptr != nil:
		*bb.ptr = b
	case bb.arr != nil:
		bb.arr.Set(bb.elem, b)
	case bb.obj != nil:
		bb.obj[bb.key] = b
	}
}

func (bb *_BSONBuilder) Get() BSON {
	switch {
	case bb.ptr != nil:
		return *bb.ptr
	case bb.arr != nil:
		return bb.arr.At(bb.elem).(BSON)
	case bb.obj != nil:
		return bb.obj[bb.key]
	}
	return nil;
}

func (bb *_BSONBuilder) Float64(f float64)	{ bb.Put(&_Number{f, _Null{}}) }
func (bb *_BSONBuilder) String(s string)	{ bb.Put(&_String{s, _Null{}}) }
func (bb *_BSONBuilder) Object()		{ bb.Put(&_Object{make(map[string]BSON), _Null{}}) }
func (bb *_BSONBuilder) Array()			{ bb.Put(&_Array{new(vector.Vector), _Null{}}) }
func (bb *_BSONBuilder) Bool(b bool)		{ bb.Put(&_Boolean{b, _Null{}}) }
func (bb *_BSONBuilder) Date(t *time.Time) {
	if t == nil {
		t = &time.Time{}
	}
	bb.Put(&_Date{t, _Null{}})
}
func (bb *_BSONBuilder) Null()			{ bb.Put(Null) }
func (bb *_BSONBuilder) Regex(regex, options string) {
	bb.Put(&_Regex{regex, options, _Null{}})
}
func (bb *_BSONBuilder) Int32(i int32)	{ bb.Put(&_Int{i, _Null{}}) }
func (bb *_BSONBuilder) Int64(i int64)	{ bb.Put(&_Long{i, _Null{}}) }
func (bb *_BSONBuilder) OID(o []byte)	{ bb.Put(&_OID{o, _Null{}}) }

func (bb *_BSONBuilder) Key(key string) Builder {
	bb2 := new(_BSONBuilder);

	switch obj := bb.Get().(type) {
	case *_Object:
		bb2.obj = obj.value;
		bb2.key = key;
		bb2.obj[key] = Null;
	case *_Array:
		bb2.arr = obj.value;
		elem, _ := strconv.Atoi(key);
		bb2.elem = elem;
		for elem >= bb2.arr.Len() {
			bb2.arr.Push(Null)
		}
	}
	return bb2;
}

func (bb *_BSONBuilder) Elem(i int) Builder {
	bb2 := new(_BSONBuilder);
	bb2.arr = bb.Get().(*_Array).value;
	bb2.elem = i;
	for i >= bb2.arr.Len() {
		bb2.arr.Push(Null)
	}
	return bb2;
}

func (bb *_BSONBuilder) Flush()	{}

func BytesToBSON(b []byte) (BSON, os.Error) {
	var bson BSON;
	bb := new(_BSONBuilder);
	bb.ptr = &bson;
	bb.Object();
	err := Parse(bytes.NewBuffer(b[4:len(b)]), bb);
	return bson, err;
}

func readCString(buf *bytes.Buffer) string {
	out := bytes.NewBuffer([]byte{});
	var c byte;
	for c, _ = buf.ReadByte(); c != 0; c, _ = buf.ReadByte() {
		out.WriteByte(c)
	}

	return out.String();
}

func Parse(buf *bytes.Buffer, builder Builder) (err os.Error) {
	kind, _ := buf.ReadByte();
	err = nil;

	for kind != EOOKind {
		name := readCString(buf);
		b2 := builder.Key(name);

		switch kind {
		case NumberKind:
			lr := io.LimitReader(buf, 8);
			bits, _ := ioutil.ReadAll(lr);
			ui64 := binary.LittleEndian.Uint64(bits);
			fl64 := math.Float64frombits(ui64);
			b2.Float64(fl64);
		case StringKind:
			bits, _ := ioutil.ReadAll(io.LimitReader(buf, 4));
			l := binary.LittleEndian.Uint32(bits);
			s, _ := ioutil.ReadAll(io.LimitReader(buf, int64(l-1)));
			buf.ReadByte();
			b2.String(string(s));
		case ObjectKind:
			b2.Object();
			ioutil.ReadAll(io.LimitReader(buf, 4));
			err = Parse(buf, b2);
		case ArrayKind:
			b2.Array();
			ioutil.ReadAll(io.LimitReader(buf, 4));
			err = Parse(buf, b2);
		case OIDKind:
			oid, _ := ioutil.ReadAll(io.LimitReader(buf, 12));
			b2.OID(oid);
		case BooleanKind:
			b, _ := buf.ReadByte();
			if b == 1 {
				b2.Bool(true)
			} else {
				b2.Bool(false)
			}
		case DateKind:
			bits, _ := ioutil.ReadAll(io.LimitReader(buf, 8));
			ui64 := binary.LittleEndian.Uint64(bits);
			b2.Date(time.SecondsToUTC(int64(ui64) / 1000));
		case RegexKind:
			regex := readCString(buf);
			options := readCString(buf);
			b2.Regex(regex, options);
		case IntKind:
			bits, _ := ioutil.ReadAll(io.LimitReader(buf, 4));
			ui32 := binary.LittleEndian.Uint32(bits);
			b2.Int32(int32(ui32));
		case LongKind:
			bits, _ := ioutil.ReadAll(io.LimitReader(buf, 8));
			ui64 := binary.LittleEndian.Uint64(bits);
			b2.Int64(int64(ui64));
		default:
			err = os.NewError(fmt.Sprintf("don't know how to handle kind %v yet", kind))
		}

		kind, _ = buf.ReadByte();
	}
	
	if b, ok := builder.(*structBuilder); b != nil && ok {
		if b.map_ != nil {
			b.map_.SetElem(b.key, b.val)
		}
	}

	return;
}