func Unmarshal(in []byte, out interface{}) (err error) {
	if raw, ok := out.(*Raw); ok {
		raw.Kind = 3
		raw.Data = in
		return nil
	}
	defer handleErr(&err)
	v := reflect.ValueOf(out)
	switch v.Kind() {
	case reflect.Ptr:
		fallthrough
	case reflect.Map:
		d := newDecoder(in)
		d.readDocTo(v)
		if d.i < len(d.in) {
			return errors.New("document is corrupted")
		}
	case reflect.Struct:
		return errors.New("unmarshal can't deal with struct values. Use a pointer")
	default:
		return errors.New("unmarshal needs a map or a pointer to a struct")
	}
	return nil
}
Unmarshal deserializes data from in into the out value.  The out value
must be a map, a pointer to a struct, or a pointer to a bson.D value.
In the case of struct values, only exported fields will be deserialized.
The lowercased field name is used as the key for each exported field,
but this behavior may be changed using the respective field tag.
The tag may also contain flags to tweak the marshalling behavior for
the field. The tag formats accepted are:

"[<key>][,<flag1>[,<flag2>]]"

`(...) bson:"[<key>][,<flag1>[,<flag2>]]" (...)`

The following flags are currently supported during unmarshal (see the
Marshal method for other flags):

inline     Inline the field, which must be a struct or a map.
Inlined structs are handled as if its fields were part
of the outer struct. An inlined map causes keys that do
not match any other struct field to be inserted in the
map rather than being discarded as usual.

The target field or element types of out may not necessarily match
the BSON values of the provided data.  The following conversions are
made automatically:

- Numeric types are converted if at least the integer part of the
value would be preserved correctly
- Bools are converted to numeric types as 1 or 0
- Numeric types are converted to bools as true if not 0 or false otherwise
- Binary and string BSON data is converted to a string, array or byte slice

If the value would not fit the type and cannot be converted, it's
silently skipped.

Pointer values are initialized when necessary.
package bson
import (
	"bytes"
	"crypto/md5"
	"crypto/rand"
	"encoding/binary"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"math"
	"os"
	"reflect"
	"runtime"
	"strings"
	"sync"
	"sync/atomic"
	"time"
)
const (
	ElementFloat64                byte = 0x01
	ElementString                 byte = 0x02
	ElementDocument               byte = 0x03
	ElementArray                  byte = 0x04
	ElementBinary                 byte = 0x05
	Element06                     byte = 0x06
	ElementObjectId               byte = 0x07
	ElementBool                   byte = 0x08
	ElementDatetime               byte = 0x09
	ElementNil                    byte = 0x0A
	ElementRegEx                  byte = 0x0B
	ElementDBPointer              byte = 0x0C
	ElementJavaScriptWithoutScope byte = 0x0D
	ElementSymbol                 byte = 0x0E
	ElementJavaScriptWithScope    byte = 0x0F
	ElementInt32                  byte = 0x10
	ElementTimestamp              byte = 0x11
	ElementInt64                  byte = 0x12
	ElementDecimal128             byte = 0x13
	ElementMinKey                 byte = 0xFF
	ElementMaxKey                 byte = 0x7F
	BinaryGeneric     byte = 0x00
	BinaryFunction    byte = 0x01
	BinaryBinaryOld   byte = 0x02
	BinaryUUIDOld     byte = 0x03
	BinaryUUID        byte = 0x04
	BinaryMD5         byte = 0x05
	BinaryUserDefined byte = 0x80
)
type Getter interface {
	GetBSON() (interface{}, error)
}
type Setter interface {
	SetBSON(raw Raw) error
}
var ErrSetZero = errors.New("set to zero")
type M map[string]interface{}
type D []DocElem
type DocElem struct {
	Name  string
	Value interface{}
}
func (d D) Map() (m M) {
	m = make(M, len(d))
	for _, item := range d {
		m[item.Name] = item.Value
	}
	return m
}
type Raw struct {
	Kind byte
	Data []byte
}
type RawD []RawDocElem
type RawDocElem struct {
	Name  string
	Value Raw
}
type ObjectId string
func ObjectIdHex(s string) ObjectId {
	d, err := hex.DecodeString(s)
	if err != nil || len(d) != 12 {
		panic(fmt.Sprintf("invalid input to ObjectIdHex: %q", s))
	}
	return ObjectId(d)
}
func IsObjectIdHex(s string) bool {
	if len(s) != 24 {
		return false
	}
	_, err := hex.DecodeString(s)
	return err == nil
}
var objectIdCounter = readRandomUint32()
func readRandomUint32() uint32 {
	var b [4]byte
	_, err := io.ReadFull(rand.Reader, b[:])
	if err != nil {
		panic(fmt.Errorf("cannot read random object id: %v", err))
	}
	return uint32((uint32(b[0]) << 0) | (uint32(b[1]) << 8) | (uint32(b[2]) << 16) | (uint32(b[3]) << 24))
}
var machineId = readMachineId()
var processId = os.Getpid()
func readMachineId() []byte {
	var sum [3]byte
	id := sum[:]
	hostname, err1 := os.Hostname()
	if err1 != nil {
		_, err2 := io.ReadFull(rand.Reader, id)
		if err2 != nil {
			panic(fmt.Errorf("cannot get hostname: %v; %v", err1, err2))
		}
		return id
	}
	hw := md5.New()
	hw.Write([]byte(hostname))
	copy(id, hw.Sum(nil))
	return id
}
func NewObjectId() ObjectId {
	var b [12]byte
	binary.BigEndian.PutUint32(b[:], uint32(time.Now().Unix()))
	b[4] = machineId[0]
	b[5] = machineId[1]
	b[6] = machineId[2]
	b[7] = byte(processId >> 8)
	b[8] = byte(processId)
	i := atomic.AddUint32(&objectIdCounter, 1)
	b[9] = byte(i >> 16)
	b[10] = byte(i >> 8)
	b[11] = byte(i)
	return ObjectId(b[:])
}
func NewObjectIdWithTime(t time.Time) ObjectId {
	var b [12]byte
	binary.BigEndian.PutUint32(b[:4], uint32(t.Unix()))
	return ObjectId(string(b[:]))
}
func (id ObjectId) String() string {
	return fmt.Sprintf(`ObjectIdHex("%x")`, string(id))
}
func (id ObjectId) Hex() string {
	return hex.EncodeToString([]byte(id))
}
func (id ObjectId) MarshalJSON() ([]byte, error) {
	return []byte(fmt.Sprintf(`"%x"`, string(id))), nil
}
var nullBytes = []byte("null")
func (id *ObjectId) UnmarshalJSON(data []byte) error {
	if len(data) > 0 && (data[0] == '{' || data[0] == 'O') {
		var v struct {
			Id   json.RawMessage `json:"$oid"`
			Func struct {
				Id json.RawMessage
			} `json:"$oidFunc"`
		}
		err := jdec(data, &v)
		if err == nil {
			if len(v.Id) > 0 {
				data = []byte(v.Id)
			} else {
				data = []byte(v.Func.Id)
			}
		}
	}
	if len(data) == 2 && data[0] == '"' && data[1] == '"' || bytes.Equal(data, nullBytes) {
		*id = ""
		return nil
	}
	if len(data) != 26 || data[0] != '"' || data[25] != '"' {
		return fmt.Errorf("invalid ObjectId in JSON: %s", string(data))
	}
	var buf [12]byte
	_, err := hex.Decode(buf[:], data[1:25])
	if err != nil {
		return fmt.Errorf("invalid ObjectId in JSON: %s (%s)", string(data), err)
	}
	*id = ObjectId(string(buf[:]))
	return nil
}
func (id ObjectId) MarshalText() ([]byte, error) {
	return []byte(fmt.Sprintf("%x", string(id))), nil
}
func (id *ObjectId) UnmarshalText(data []byte) error {
	if len(data) == 1 && data[0] == ' ' || len(data) == 0 {
		*id = ""
		return nil
	}
	if len(data) != 24 {
		return fmt.Errorf("invalid ObjectId: %s", data)
	}
	var buf [12]byte
	_, err := hex.Decode(buf[:], data[:])
	if err != nil {
		return fmt.Errorf("invalid ObjectId: %s (%s)", data, err)
	}
	*id = ObjectId(string(buf[:]))
	return nil
}
func (id ObjectId) Valid() bool {
	return len(id) == 12
}
func (id ObjectId) byteSlice(start, end int) []byte {
	if len(id) != 12 {
		panic(fmt.Sprintf("invalid ObjectId: %q", string(id)))
	}
	return []byte(string(id)[start:end])
}
func (id ObjectId) Time() time.Time {
	secs := int64(binary.BigEndian.Uint32(id.byteSlice(0, 4)))
	return time.Unix(secs, 0)
}
func (id ObjectId) Machine() []byte {
	return id.byteSlice(4, 7)
}
func (id ObjectId) Pid() uint16 {
	return binary.BigEndian.Uint16(id.byteSlice(7, 9))
}
func (id ObjectId) Counter() int32 {
	b := id.byteSlice(9, 12)
	return int32(uint32(b[0])<<16 | uint32(b[1])<<8 | uint32(b[2]))
}
type Symbol string
func Now() time.Time {
	return time.Unix(0, time.Now().UnixNano()/1e6*1e6)
}
type MongoTimestamp int64
func (ts MongoTimestamp) Time() time.Time {
	return time.Unix(int64(uint64(ts)>>32), 0)
}
func (ts MongoTimestamp) Counter() uint32 {
	return uint32(ts)
}
func NewMongoTimestamp(t time.Time, c uint32) (MongoTimestamp, error) {
	u := t.Unix()
	if u < 0 || u > math.MaxUint32 {
		return -1, errors.New("invalid value for time")
	}
	i := int64(u<<32 | int64(c))
	return MongoTimestamp(i), nil
}
type orderKey int64
var MaxKey = orderKey(1<<63 - 1)
var MinKey = orderKey(-1 << 63)
type undefined struct{}
var Undefined undefined
type Binary struct {
	Kind byte
	Data []byte
}
type RegEx struct {
	Pattern string
	Options string
}
type JavaScript struct {
	Code  string
	Scope interface{}
}
type DBPointer struct {
	Namespace string
	Id        ObjectId
}
const initialBufferSize = 64
func handleErr(err *error) {
	if r := recover(); r != nil {
		if _, ok := r.(runtime.Error); ok {
			panic(r)
		} else if _, ok := r.(externalPanic); ok {
			panic(r)
		} else if s, ok := r.(string); ok {
			*err = errors.New(s)
		} else if e, ok := r.(error); ok {
			*err = e
		} else {
			panic(r)
		}
	}
}
func Marshal(in interface{}) (out []byte, err error) {
	return MarshalBuffer(in, make([]byte, 0, initialBufferSize))
}
func MarshalBuffer(in interface{}, buf []byte) (out []byte, err error) {
	defer handleErr(&err)
	e := &encoder{buf}
	e.addDoc(reflect.ValueOf(in))
	return e.out, nil
}