value_reader.go raw

   1  // Copyright (C) MongoDB, Inc. 2017-present.
   2  //
   3  // Licensed under the Apache License, Version 2.0 (the "License"); you may
   4  // not use this file except in compliance with the License. You may obtain
   5  // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
   6  
   7  package bsonrw
   8  
   9  import (
  10  	"bytes"
  11  	"encoding/binary"
  12  	"errors"
  13  	"fmt"
  14  	"io"
  15  	"math"
  16  	"sync"
  17  
  18  	"go.mongodb.org/mongo-driver/bson/bsontype"
  19  	"go.mongodb.org/mongo-driver/bson/primitive"
  20  )
  21  
  22  var _ ValueReader = (*valueReader)(nil)
  23  
  24  var vrPool = sync.Pool{
  25  	New: func() interface{} {
  26  		return new(valueReader)
  27  	},
  28  }
  29  
  30  // BSONValueReaderPool is a pool for ValueReaders that read BSON.
  31  //
  32  // Deprecated: BSONValueReaderPool will not be supported in Go Driver 2.0.
  33  type BSONValueReaderPool struct {
  34  	pool sync.Pool
  35  }
  36  
  37  // NewBSONValueReaderPool instantiates a new BSONValueReaderPool.
  38  //
  39  // Deprecated: BSONValueReaderPool will not be supported in Go Driver 2.0.
  40  func NewBSONValueReaderPool() *BSONValueReaderPool {
  41  	return &BSONValueReaderPool{
  42  		pool: sync.Pool{
  43  			New: func() interface{} {
  44  				return new(valueReader)
  45  			},
  46  		},
  47  	}
  48  }
  49  
  50  // Get retrieves a ValueReader from the pool and uses src as the underlying BSON.
  51  //
  52  // Deprecated: BSONValueReaderPool will not be supported in Go Driver 2.0.
  53  func (bvrp *BSONValueReaderPool) Get(src []byte) ValueReader {
  54  	vr := bvrp.pool.Get().(*valueReader)
  55  	vr.reset(src)
  56  	return vr
  57  }
  58  
  59  // Put inserts a ValueReader into the pool. If the ValueReader is not a BSON ValueReader nothing
  60  // is inserted into the pool and ok will be false.
  61  //
  62  // Deprecated: BSONValueReaderPool will not be supported in Go Driver 2.0.
  63  func (bvrp *BSONValueReaderPool) Put(vr ValueReader) (ok bool) {
  64  	bvr, ok := vr.(*valueReader)
  65  	if !ok {
  66  		return false
  67  	}
  68  
  69  	bvr.reset(nil)
  70  	bvrp.pool.Put(bvr)
  71  	return true
  72  }
  73  
  74  // ErrEOA is the error returned when the end of a BSON array has been reached.
  75  var ErrEOA = errors.New("end of array")
  76  
  77  // ErrEOD is the error returned when the end of a BSON document has been reached.
  78  var ErrEOD = errors.New("end of document")
  79  
  80  type vrState struct {
  81  	mode  mode
  82  	vType bsontype.Type
  83  	end   int64
  84  }
  85  
  86  // valueReader is for reading BSON values.
  87  type valueReader struct {
  88  	offset int64
  89  	d      []byte
  90  
  91  	stack []vrState
  92  	frame int64
  93  }
  94  
  95  // NewBSONDocumentReader returns a ValueReader using b for the underlying BSON
  96  // representation. Parameter b must be a BSON Document.
  97  func NewBSONDocumentReader(b []byte) ValueReader {
  98  	// TODO(skriptble): There's a lack of symmetry between the reader and writer, since the reader takes a []byte while the
  99  	// TODO writer takes an io.Writer. We should have two versions of each, one that takes a []byte and one that takes an
 100  	// TODO io.Reader or io.Writer. The []byte version will need to return a thing that can return the finished []byte since
 101  	// TODO it might be reallocated when appended to.
 102  	return newValueReader(b)
 103  }
 104  
 105  // NewBSONValueReader returns a ValueReader that starts in the Value mode instead of in top
 106  // level document mode. This enables the creation of a ValueReader for a single BSON value.
 107  func NewBSONValueReader(t bsontype.Type, val []byte) ValueReader {
 108  	stack := make([]vrState, 1, 5)
 109  	stack[0] = vrState{
 110  		mode:  mValue,
 111  		vType: t,
 112  	}
 113  	return &valueReader{
 114  		d:     val,
 115  		stack: stack,
 116  	}
 117  }
 118  
 119  func newValueReader(b []byte) *valueReader {
 120  	stack := make([]vrState, 1, 5)
 121  	stack[0] = vrState{
 122  		mode: mTopLevel,
 123  	}
 124  	return &valueReader{
 125  		d:     b,
 126  		stack: stack,
 127  	}
 128  }
 129  
 130  func (vr *valueReader) reset(b []byte) {
 131  	if vr.stack == nil {
 132  		vr.stack = make([]vrState, 1, 5)
 133  	}
 134  	vr.stack = vr.stack[:1]
 135  	vr.stack[0] = vrState{mode: mTopLevel}
 136  	vr.d = b
 137  	vr.offset = 0
 138  	vr.frame = 0
 139  }
 140  
 141  func (vr *valueReader) advanceFrame() {
 142  	if vr.frame+1 >= int64(len(vr.stack)) { // We need to grow the stack
 143  		length := len(vr.stack)
 144  		if length+1 >= cap(vr.stack) {
 145  			// double it
 146  			buf := make([]vrState, 2*cap(vr.stack)+1)
 147  			copy(buf, vr.stack)
 148  			vr.stack = buf
 149  		}
 150  		vr.stack = vr.stack[:length+1]
 151  	}
 152  	vr.frame++
 153  
 154  	// Clean the stack
 155  	vr.stack[vr.frame].mode = 0
 156  	vr.stack[vr.frame].vType = 0
 157  	vr.stack[vr.frame].end = 0
 158  }
 159  
 160  func (vr *valueReader) pushDocument() error {
 161  	vr.advanceFrame()
 162  
 163  	vr.stack[vr.frame].mode = mDocument
 164  
 165  	size, err := vr.readLength()
 166  	if err != nil {
 167  		return err
 168  	}
 169  	vr.stack[vr.frame].end = int64(size) + vr.offset - 4
 170  
 171  	return nil
 172  }
 173  
 174  func (vr *valueReader) pushArray() error {
 175  	vr.advanceFrame()
 176  
 177  	vr.stack[vr.frame].mode = mArray
 178  
 179  	size, err := vr.readLength()
 180  	if err != nil {
 181  		return err
 182  	}
 183  	vr.stack[vr.frame].end = int64(size) + vr.offset - 4
 184  
 185  	return nil
 186  }
 187  
 188  func (vr *valueReader) pushElement(t bsontype.Type) {
 189  	vr.advanceFrame()
 190  
 191  	vr.stack[vr.frame].mode = mElement
 192  	vr.stack[vr.frame].vType = t
 193  }
 194  
 195  func (vr *valueReader) pushValue(t bsontype.Type) {
 196  	vr.advanceFrame()
 197  
 198  	vr.stack[vr.frame].mode = mValue
 199  	vr.stack[vr.frame].vType = t
 200  }
 201  
 202  func (vr *valueReader) pushCodeWithScope() (int64, error) {
 203  	vr.advanceFrame()
 204  
 205  	vr.stack[vr.frame].mode = mCodeWithScope
 206  
 207  	size, err := vr.readLength()
 208  	if err != nil {
 209  		return 0, err
 210  	}
 211  	vr.stack[vr.frame].end = int64(size) + vr.offset - 4
 212  
 213  	return int64(size), nil
 214  }
 215  
 216  func (vr *valueReader) pop() {
 217  	switch vr.stack[vr.frame].mode {
 218  	case mElement, mValue:
 219  		vr.frame--
 220  	case mDocument, mArray, mCodeWithScope:
 221  		vr.frame -= 2 // we pop twice to jump over the vrElement: vrDocument -> vrElement -> vrDocument/TopLevel/etc...
 222  	}
 223  }
 224  
 225  func (vr *valueReader) invalidTransitionErr(destination mode, name string, modes []mode) error {
 226  	te := TransitionError{
 227  		name:        name,
 228  		current:     vr.stack[vr.frame].mode,
 229  		destination: destination,
 230  		modes:       modes,
 231  		action:      "read",
 232  	}
 233  	if vr.frame != 0 {
 234  		te.parent = vr.stack[vr.frame-1].mode
 235  	}
 236  	return te
 237  }
 238  
 239  func (vr *valueReader) typeError(t bsontype.Type) error {
 240  	return fmt.Errorf("positioned on %s, but attempted to read %s", vr.stack[vr.frame].vType, t)
 241  }
 242  
 243  func (vr *valueReader) invalidDocumentLengthError() error {
 244  	return fmt.Errorf("document is invalid, end byte is at %d, but null byte found at %d", vr.stack[vr.frame].end, vr.offset)
 245  }
 246  
 247  func (vr *valueReader) ensureElementValue(t bsontype.Type, destination mode, callerName string) error {
 248  	switch vr.stack[vr.frame].mode {
 249  	case mElement, mValue:
 250  		if vr.stack[vr.frame].vType != t {
 251  			return vr.typeError(t)
 252  		}
 253  	default:
 254  		return vr.invalidTransitionErr(destination, callerName, []mode{mElement, mValue})
 255  	}
 256  
 257  	return nil
 258  }
 259  
 260  func (vr *valueReader) Type() bsontype.Type {
 261  	return vr.stack[vr.frame].vType
 262  }
 263  
 264  func (vr *valueReader) nextElementLength() (int32, error) {
 265  	var length int32
 266  	var err error
 267  	switch vr.stack[vr.frame].vType {
 268  	case bsontype.Array, bsontype.EmbeddedDocument, bsontype.CodeWithScope:
 269  		length, err = vr.peekLength()
 270  	case bsontype.Binary:
 271  		length, err = vr.peekLength()
 272  		length += 4 + 1 // binary length + subtype byte
 273  	case bsontype.Boolean:
 274  		length = 1
 275  	case bsontype.DBPointer:
 276  		length, err = vr.peekLength()
 277  		length += 4 + 12 // string length + ObjectID length
 278  	case bsontype.DateTime, bsontype.Double, bsontype.Int64, bsontype.Timestamp:
 279  		length = 8
 280  	case bsontype.Decimal128:
 281  		length = 16
 282  	case bsontype.Int32:
 283  		length = 4
 284  	case bsontype.JavaScript, bsontype.String, bsontype.Symbol:
 285  		length, err = vr.peekLength()
 286  		length += 4
 287  	case bsontype.MaxKey, bsontype.MinKey, bsontype.Null, bsontype.Undefined:
 288  		length = 0
 289  	case bsontype.ObjectID:
 290  		length = 12
 291  	case bsontype.Regex:
 292  		regex := bytes.IndexByte(vr.d[vr.offset:], 0x00)
 293  		if regex < 0 {
 294  			err = io.EOF
 295  			break
 296  		}
 297  		pattern := bytes.IndexByte(vr.d[vr.offset+int64(regex)+1:], 0x00)
 298  		if pattern < 0 {
 299  			err = io.EOF
 300  			break
 301  		}
 302  		length = int32(int64(regex) + 1 + int64(pattern) + 1)
 303  	default:
 304  		return 0, fmt.Errorf("attempted to read bytes of unknown BSON type %v", vr.stack[vr.frame].vType)
 305  	}
 306  
 307  	return length, err
 308  }
 309  
 310  func (vr *valueReader) ReadValueBytes(dst []byte) (bsontype.Type, []byte, error) {
 311  	switch vr.stack[vr.frame].mode {
 312  	case mTopLevel:
 313  		length, err := vr.peekLength()
 314  		if err != nil {
 315  			return bsontype.Type(0), nil, err
 316  		}
 317  		dst, err = vr.appendBytes(dst, length)
 318  		if err != nil {
 319  			return bsontype.Type(0), nil, err
 320  		}
 321  		return bsontype.Type(0), dst, nil
 322  	case mElement, mValue:
 323  		length, err := vr.nextElementLength()
 324  		if err != nil {
 325  			return bsontype.Type(0), dst, err
 326  		}
 327  
 328  		dst, err = vr.appendBytes(dst, length)
 329  		t := vr.stack[vr.frame].vType
 330  		vr.pop()
 331  		return t, dst, err
 332  	default:
 333  		return bsontype.Type(0), nil, vr.invalidTransitionErr(0, "ReadValueBytes", []mode{mElement, mValue})
 334  	}
 335  }
 336  
 337  func (vr *valueReader) Skip() error {
 338  	switch vr.stack[vr.frame].mode {
 339  	case mElement, mValue:
 340  	default:
 341  		return vr.invalidTransitionErr(0, "Skip", []mode{mElement, mValue})
 342  	}
 343  
 344  	length, err := vr.nextElementLength()
 345  	if err != nil {
 346  		return err
 347  	}
 348  
 349  	err = vr.skipBytes(length)
 350  	vr.pop()
 351  	return err
 352  }
 353  
 354  func (vr *valueReader) ReadArray() (ArrayReader, error) {
 355  	if err := vr.ensureElementValue(bsontype.Array, mArray, "ReadArray"); err != nil {
 356  		return nil, err
 357  	}
 358  
 359  	err := vr.pushArray()
 360  	if err != nil {
 361  		return nil, err
 362  	}
 363  
 364  	return vr, nil
 365  }
 366  
 367  func (vr *valueReader) ReadBinary() (b []byte, btype byte, err error) {
 368  	if err := vr.ensureElementValue(bsontype.Binary, 0, "ReadBinary"); err != nil {
 369  		return nil, 0, err
 370  	}
 371  
 372  	length, err := vr.readLength()
 373  	if err != nil {
 374  		return nil, 0, err
 375  	}
 376  
 377  	btype, err = vr.readByte()
 378  	if err != nil {
 379  		return nil, 0, err
 380  	}
 381  
 382  	// Check length in case it is an old binary without a length.
 383  	if btype == 0x02 && length > 4 {
 384  		length, err = vr.readLength()
 385  		if err != nil {
 386  			return nil, 0, err
 387  		}
 388  	}
 389  
 390  	b, err = vr.readBytes(length)
 391  	if err != nil {
 392  		return nil, 0, err
 393  	}
 394  	// Make a copy of the returned byte slice because it's just a subslice from the valueReader's
 395  	// buffer and is not safe to return in the unmarshaled value.
 396  	cp := make([]byte, len(b))
 397  	copy(cp, b)
 398  
 399  	vr.pop()
 400  	return cp, btype, nil
 401  }
 402  
 403  func (vr *valueReader) ReadBoolean() (bool, error) {
 404  	if err := vr.ensureElementValue(bsontype.Boolean, 0, "ReadBoolean"); err != nil {
 405  		return false, err
 406  	}
 407  
 408  	b, err := vr.readByte()
 409  	if err != nil {
 410  		return false, err
 411  	}
 412  
 413  	if b > 1 {
 414  		return false, fmt.Errorf("invalid byte for boolean, %b", b)
 415  	}
 416  
 417  	vr.pop()
 418  	return b == 1, nil
 419  }
 420  
 421  func (vr *valueReader) ReadDocument() (DocumentReader, error) {
 422  	switch vr.stack[vr.frame].mode {
 423  	case mTopLevel:
 424  		// read size
 425  		size, err := vr.readLength()
 426  		if err != nil {
 427  			return nil, err
 428  		}
 429  		if int(size) != len(vr.d) {
 430  			return nil, fmt.Errorf("invalid document length")
 431  		}
 432  		vr.stack[vr.frame].end = int64(size) + vr.offset - 4
 433  		return vr, nil
 434  	case mElement, mValue:
 435  		if vr.stack[vr.frame].vType != bsontype.EmbeddedDocument {
 436  			return nil, vr.typeError(bsontype.EmbeddedDocument)
 437  		}
 438  	default:
 439  		return nil, vr.invalidTransitionErr(mDocument, "ReadDocument", []mode{mTopLevel, mElement, mValue})
 440  	}
 441  
 442  	err := vr.pushDocument()
 443  	if err != nil {
 444  		return nil, err
 445  	}
 446  
 447  	return vr, nil
 448  }
 449  
 450  func (vr *valueReader) ReadCodeWithScope() (code string, dr DocumentReader, err error) {
 451  	if err := vr.ensureElementValue(bsontype.CodeWithScope, 0, "ReadCodeWithScope"); err != nil {
 452  		return "", nil, err
 453  	}
 454  
 455  	totalLength, err := vr.readLength()
 456  	if err != nil {
 457  		return "", nil, err
 458  	}
 459  	strLength, err := vr.readLength()
 460  	if err != nil {
 461  		return "", nil, err
 462  	}
 463  	if strLength <= 0 {
 464  		return "", nil, fmt.Errorf("invalid string length: %d", strLength)
 465  	}
 466  	strBytes, err := vr.readBytes(strLength)
 467  	if err != nil {
 468  		return "", nil, err
 469  	}
 470  	code = string(strBytes[:len(strBytes)-1])
 471  
 472  	size, err := vr.pushCodeWithScope()
 473  	if err != nil {
 474  		return "", nil, err
 475  	}
 476  
 477  	// The total length should equal:
 478  	// 4 (total length) + strLength + 4 (the length of str itself) + (document length)
 479  	componentsLength := int64(4+strLength+4) + size
 480  	if int64(totalLength) != componentsLength {
 481  		return "", nil, fmt.Errorf(
 482  			"length of CodeWithScope does not match lengths of components; total: %d; components: %d",
 483  			totalLength, componentsLength,
 484  		)
 485  	}
 486  	return code, vr, nil
 487  }
 488  
 489  func (vr *valueReader) ReadDBPointer() (ns string, oid primitive.ObjectID, err error) {
 490  	if err := vr.ensureElementValue(bsontype.DBPointer, 0, "ReadDBPointer"); err != nil {
 491  		return "", oid, err
 492  	}
 493  
 494  	ns, err = vr.readString()
 495  	if err != nil {
 496  		return "", oid, err
 497  	}
 498  
 499  	oidbytes, err := vr.readBytes(12)
 500  	if err != nil {
 501  		return "", oid, err
 502  	}
 503  
 504  	copy(oid[:], oidbytes)
 505  
 506  	vr.pop()
 507  	return ns, oid, nil
 508  }
 509  
 510  func (vr *valueReader) ReadDateTime() (int64, error) {
 511  	if err := vr.ensureElementValue(bsontype.DateTime, 0, "ReadDateTime"); err != nil {
 512  		return 0, err
 513  	}
 514  
 515  	i, err := vr.readi64()
 516  	if err != nil {
 517  		return 0, err
 518  	}
 519  
 520  	vr.pop()
 521  	return i, nil
 522  }
 523  
 524  func (vr *valueReader) ReadDecimal128() (primitive.Decimal128, error) {
 525  	if err := vr.ensureElementValue(bsontype.Decimal128, 0, "ReadDecimal128"); err != nil {
 526  		return primitive.Decimal128{}, err
 527  	}
 528  
 529  	b, err := vr.readBytes(16)
 530  	if err != nil {
 531  		return primitive.Decimal128{}, err
 532  	}
 533  
 534  	l := binary.LittleEndian.Uint64(b[0:8])
 535  	h := binary.LittleEndian.Uint64(b[8:16])
 536  
 537  	vr.pop()
 538  	return primitive.NewDecimal128(h, l), nil
 539  }
 540  
 541  func (vr *valueReader) ReadDouble() (float64, error) {
 542  	if err := vr.ensureElementValue(bsontype.Double, 0, "ReadDouble"); err != nil {
 543  		return 0, err
 544  	}
 545  
 546  	u, err := vr.readu64()
 547  	if err != nil {
 548  		return 0, err
 549  	}
 550  
 551  	vr.pop()
 552  	return math.Float64frombits(u), nil
 553  }
 554  
 555  func (vr *valueReader) ReadInt32() (int32, error) {
 556  	if err := vr.ensureElementValue(bsontype.Int32, 0, "ReadInt32"); err != nil {
 557  		return 0, err
 558  	}
 559  
 560  	vr.pop()
 561  	return vr.readi32()
 562  }
 563  
 564  func (vr *valueReader) ReadInt64() (int64, error) {
 565  	if err := vr.ensureElementValue(bsontype.Int64, 0, "ReadInt64"); err != nil {
 566  		return 0, err
 567  	}
 568  
 569  	vr.pop()
 570  	return vr.readi64()
 571  }
 572  
 573  func (vr *valueReader) ReadJavascript() (code string, err error) {
 574  	if err := vr.ensureElementValue(bsontype.JavaScript, 0, "ReadJavascript"); err != nil {
 575  		return "", err
 576  	}
 577  
 578  	vr.pop()
 579  	return vr.readString()
 580  }
 581  
 582  func (vr *valueReader) ReadMaxKey() error {
 583  	if err := vr.ensureElementValue(bsontype.MaxKey, 0, "ReadMaxKey"); err != nil {
 584  		return err
 585  	}
 586  
 587  	vr.pop()
 588  	return nil
 589  }
 590  
 591  func (vr *valueReader) ReadMinKey() error {
 592  	if err := vr.ensureElementValue(bsontype.MinKey, 0, "ReadMinKey"); err != nil {
 593  		return err
 594  	}
 595  
 596  	vr.pop()
 597  	return nil
 598  }
 599  
 600  func (vr *valueReader) ReadNull() error {
 601  	if err := vr.ensureElementValue(bsontype.Null, 0, "ReadNull"); err != nil {
 602  		return err
 603  	}
 604  
 605  	vr.pop()
 606  	return nil
 607  }
 608  
 609  func (vr *valueReader) ReadObjectID() (primitive.ObjectID, error) {
 610  	if err := vr.ensureElementValue(bsontype.ObjectID, 0, "ReadObjectID"); err != nil {
 611  		return primitive.ObjectID{}, err
 612  	}
 613  
 614  	oidbytes, err := vr.readBytes(12)
 615  	if err != nil {
 616  		return primitive.ObjectID{}, err
 617  	}
 618  
 619  	var oid primitive.ObjectID
 620  	copy(oid[:], oidbytes)
 621  
 622  	vr.pop()
 623  	return oid, nil
 624  }
 625  
 626  func (vr *valueReader) ReadRegex() (string, string, error) {
 627  	if err := vr.ensureElementValue(bsontype.Regex, 0, "ReadRegex"); err != nil {
 628  		return "", "", err
 629  	}
 630  
 631  	pattern, err := vr.readCString()
 632  	if err != nil {
 633  		return "", "", err
 634  	}
 635  
 636  	options, err := vr.readCString()
 637  	if err != nil {
 638  		return "", "", err
 639  	}
 640  
 641  	vr.pop()
 642  	return pattern, options, nil
 643  }
 644  
 645  func (vr *valueReader) ReadString() (string, error) {
 646  	if err := vr.ensureElementValue(bsontype.String, 0, "ReadString"); err != nil {
 647  		return "", err
 648  	}
 649  
 650  	vr.pop()
 651  	return vr.readString()
 652  }
 653  
 654  func (vr *valueReader) ReadSymbol() (symbol string, err error) {
 655  	if err := vr.ensureElementValue(bsontype.Symbol, 0, "ReadSymbol"); err != nil {
 656  		return "", err
 657  	}
 658  
 659  	vr.pop()
 660  	return vr.readString()
 661  }
 662  
 663  func (vr *valueReader) ReadTimestamp() (t uint32, i uint32, err error) {
 664  	if err := vr.ensureElementValue(bsontype.Timestamp, 0, "ReadTimestamp"); err != nil {
 665  		return 0, 0, err
 666  	}
 667  
 668  	i, err = vr.readu32()
 669  	if err != nil {
 670  		return 0, 0, err
 671  	}
 672  
 673  	t, err = vr.readu32()
 674  	if err != nil {
 675  		return 0, 0, err
 676  	}
 677  
 678  	vr.pop()
 679  	return t, i, nil
 680  }
 681  
 682  func (vr *valueReader) ReadUndefined() error {
 683  	if err := vr.ensureElementValue(bsontype.Undefined, 0, "ReadUndefined"); err != nil {
 684  		return err
 685  	}
 686  
 687  	vr.pop()
 688  	return nil
 689  }
 690  
 691  func (vr *valueReader) ReadElement() (string, ValueReader, error) {
 692  	switch vr.stack[vr.frame].mode {
 693  	case mTopLevel, mDocument, mCodeWithScope:
 694  	default:
 695  		return "", nil, vr.invalidTransitionErr(mElement, "ReadElement", []mode{mTopLevel, mDocument, mCodeWithScope})
 696  	}
 697  
 698  	t, err := vr.readByte()
 699  	if err != nil {
 700  		return "", nil, err
 701  	}
 702  
 703  	if t == 0 {
 704  		if vr.offset != vr.stack[vr.frame].end {
 705  			return "", nil, vr.invalidDocumentLengthError()
 706  		}
 707  
 708  		vr.pop()
 709  		return "", nil, ErrEOD
 710  	}
 711  
 712  	name, err := vr.readCString()
 713  	if err != nil {
 714  		return "", nil, err
 715  	}
 716  
 717  	vr.pushElement(bsontype.Type(t))
 718  	return name, vr, nil
 719  }
 720  
 721  func (vr *valueReader) ReadValue() (ValueReader, error) {
 722  	switch vr.stack[vr.frame].mode {
 723  	case mArray:
 724  	default:
 725  		return nil, vr.invalidTransitionErr(mValue, "ReadValue", []mode{mArray})
 726  	}
 727  
 728  	t, err := vr.readByte()
 729  	if err != nil {
 730  		return nil, err
 731  	}
 732  
 733  	if t == 0 {
 734  		if vr.offset != vr.stack[vr.frame].end {
 735  			return nil, vr.invalidDocumentLengthError()
 736  		}
 737  
 738  		vr.pop()
 739  		return nil, ErrEOA
 740  	}
 741  
 742  	if err := vr.skipCString(); err != nil {
 743  		return nil, err
 744  	}
 745  
 746  	vr.pushValue(bsontype.Type(t))
 747  	return vr, nil
 748  }
 749  
 750  // readBytes reads length bytes from the valueReader starting at the current offset. Note that the
 751  // returned byte slice is a subslice from the valueReader buffer and must be converted or copied
 752  // before returning in an unmarshaled value.
 753  func (vr *valueReader) readBytes(length int32) ([]byte, error) {
 754  	if length < 0 {
 755  		return nil, fmt.Errorf("invalid length: %d", length)
 756  	}
 757  
 758  	if vr.offset+int64(length) > int64(len(vr.d)) {
 759  		return nil, io.EOF
 760  	}
 761  
 762  	start := vr.offset
 763  	vr.offset += int64(length)
 764  
 765  	return vr.d[start : start+int64(length)], nil
 766  }
 767  
 768  func (vr *valueReader) appendBytes(dst []byte, length int32) ([]byte, error) {
 769  	if vr.offset+int64(length) > int64(len(vr.d)) {
 770  		return nil, io.EOF
 771  	}
 772  
 773  	start := vr.offset
 774  	vr.offset += int64(length)
 775  	return append(dst, vr.d[start:start+int64(length)]...), nil
 776  }
 777  
 778  func (vr *valueReader) skipBytes(length int32) error {
 779  	if vr.offset+int64(length) > int64(len(vr.d)) {
 780  		return io.EOF
 781  	}
 782  
 783  	vr.offset += int64(length)
 784  	return nil
 785  }
 786  
 787  func (vr *valueReader) readByte() (byte, error) {
 788  	if vr.offset+1 > int64(len(vr.d)) {
 789  		return 0x0, io.EOF
 790  	}
 791  
 792  	vr.offset++
 793  	return vr.d[vr.offset-1], nil
 794  }
 795  
 796  func (vr *valueReader) skipCString() error {
 797  	idx := bytes.IndexByte(vr.d[vr.offset:], 0x00)
 798  	if idx < 0 {
 799  		return io.EOF
 800  	}
 801  	vr.offset += int64(idx) + 1
 802  	return nil
 803  }
 804  
 805  func (vr *valueReader) readCString() (string, error) {
 806  	idx := bytes.IndexByte(vr.d[vr.offset:], 0x00)
 807  	if idx < 0 {
 808  		return "", io.EOF
 809  	}
 810  	start := vr.offset
 811  	// idx does not include the null byte
 812  	vr.offset += int64(idx) + 1
 813  	return string(vr.d[start : start+int64(idx)]), nil
 814  }
 815  
 816  func (vr *valueReader) readString() (string, error) {
 817  	length, err := vr.readLength()
 818  	if err != nil {
 819  		return "", err
 820  	}
 821  
 822  	if int64(length)+vr.offset > int64(len(vr.d)) {
 823  		return "", io.EOF
 824  	}
 825  
 826  	if length <= 0 {
 827  		return "", fmt.Errorf("invalid string length: %d", length)
 828  	}
 829  
 830  	if vr.d[vr.offset+int64(length)-1] != 0x00 {
 831  		return "", fmt.Errorf("string does not end with null byte, but with %v", vr.d[vr.offset+int64(length)-1])
 832  	}
 833  
 834  	start := vr.offset
 835  	vr.offset += int64(length)
 836  	return string(vr.d[start : start+int64(length)-1]), nil
 837  }
 838  
 839  func (vr *valueReader) peekLength() (int32, error) {
 840  	if vr.offset+4 > int64(len(vr.d)) {
 841  		return 0, io.EOF
 842  	}
 843  
 844  	idx := vr.offset
 845  	return (int32(vr.d[idx]) | int32(vr.d[idx+1])<<8 | int32(vr.d[idx+2])<<16 | int32(vr.d[idx+3])<<24), nil
 846  }
 847  
 848  func (vr *valueReader) readLength() (int32, error) { return vr.readi32() }
 849  
 850  func (vr *valueReader) readi32() (int32, error) {
 851  	if vr.offset+4 > int64(len(vr.d)) {
 852  		return 0, io.EOF
 853  	}
 854  
 855  	idx := vr.offset
 856  	vr.offset += 4
 857  	return (int32(vr.d[idx]) | int32(vr.d[idx+1])<<8 | int32(vr.d[idx+2])<<16 | int32(vr.d[idx+3])<<24), nil
 858  }
 859  
 860  func (vr *valueReader) readu32() (uint32, error) {
 861  	if vr.offset+4 > int64(len(vr.d)) {
 862  		return 0, io.EOF
 863  	}
 864  
 865  	idx := vr.offset
 866  	vr.offset += 4
 867  	return (uint32(vr.d[idx]) | uint32(vr.d[idx+1])<<8 | uint32(vr.d[idx+2])<<16 | uint32(vr.d[idx+3])<<24), nil
 868  }
 869  
 870  func (vr *valueReader) readi64() (int64, error) {
 871  	if vr.offset+8 > int64(len(vr.d)) {
 872  		return 0, io.EOF
 873  	}
 874  
 875  	idx := vr.offset
 876  	vr.offset += 8
 877  	return int64(vr.d[idx]) | int64(vr.d[idx+1])<<8 | int64(vr.d[idx+2])<<16 | int64(vr.d[idx+3])<<24 |
 878  		int64(vr.d[idx+4])<<32 | int64(vr.d[idx+5])<<40 | int64(vr.d[idx+6])<<48 | int64(vr.d[idx+7])<<56, nil
 879  }
 880  
 881  func (vr *valueReader) readu64() (uint64, error) {
 882  	if vr.offset+8 > int64(len(vr.d)) {
 883  		return 0, io.EOF
 884  	}
 885  
 886  	idx := vr.offset
 887  	vr.offset += 8
 888  	return uint64(vr.d[idx]) | uint64(vr.d[idx+1])<<8 | uint64(vr.d[idx+2])<<16 | uint64(vr.d[idx+3])<<24 |
 889  		uint64(vr.d[idx+4])<<32 | uint64(vr.d[idx+5])<<40 | uint64(vr.d[idx+6])<<48 | uint64(vr.d[idx+7])<<56, nil
 890  }
 891