// ParseBSON parses the bson from the Reader interface. It returns a channel that the caller can use
// to retrieve the parsed BSON ops, and a channel for parse errors.
420121
func parseBSON(done <-chan struct{}, r io.Reader) (<-chan map[string]interface{}, <-chan error) {
	c := make(chan map[string]interface{})
	errc := make(chan error, 1)

	go func() {
		defer close(c)
		scanner := bsonScanner.New(r)
	scan:
		for scanner.Scan() {
			op := map[string]interface{}{}
			if err := bson.Unmarshal(scanner.Bytes(), &op); err != nil {
				errc <- err
				return
			}
			select {
			case c <- op:
			case <-done:
				break scan
			}
		}
		if err := scanner.Err(); err != nil {
			fmt.Println(err)
			errc <- err
		}
		errc <- nil
	}()
	return c, errc
}
1053876
func (p *parser) parseJoin() (*Decl, error) {
	joinDecl, err := p.consumeToken(JoinToken)
	if err != nil {
		return nil, err
	}

	// TABLE NAME
	tableDecl, err := p.parseAttribute()
	if err != nil {
		return nil, err
	}
	joinDecl.Add(tableDecl)

	// ON
	onDecl, err := p.consumeToken(OnToken)
	if err != nil {
		return nil, err
	}
	// onDecl := NewDecl(t)
	joinDecl.Add(onDecl)

	// ATTRIBUTE
	leftAttributeDecl, err := p.parseAttribute()
	if err != nil {
		return nil, err
	}
	onDecl.Add(leftAttributeDecl)

	// EQUAL
	equalAttr, err := p.consumeToken(EqualityToken)
	if err != nil {
		return nil, err
	}
	onDecl.Add(equalAttr)

	//ATTRIBUTE
	rightAttributeDecl, err := p.parseAttribute()
	if err != nil {
		return nil, err
	}
	onDecl.Add(rightAttributeDecl)

	return joinDecl, nil
}
1279497
func (dt *DateTime) SetBSON(raw bson.Raw) error {
	decoded := time.Time{}

	bsonErr := raw.Unmarshal(&decoded)
	if bsonErr != nil {
		return bsonErr
	}
	*dt = DateTime(decoded)
	return nil

}
717252
func ParseBoolFlag(s string) (bf BoolFlag, err error) {
	switch s {
	case "on":
		bf = true
	case "off":
		bf = false
	default:
		err = fmt.Errorf("invalid value ‘%s’ for BoolFlag", s)
	}

	return bf, err
}
1162417
func (b bindingsMap) GetBSON() (interface{}, error) {
	if b == nil || len(b) == 0 {
		// We need to return a non-nil map otherwise bson.Unmarshal
		// call will fail when reading the doc back.
		return make(map[string]string), nil
	}
	rawMap := make(map[string]string, len(b))
	for key, value := range b {
		newKey := utils.EscapeKey(key)
		rawMap[newKey] = value
	}

	return rawMap, nil
}
1033093
func (t *Tools) SetBSON(raw bson.Raw) error {
	if raw.Kind == 10 {
		// Preserve the nil value in that case.
		return bson.SetZero
	}
	var doc toolsDoc
	if err := raw.Unmarshal(&doc); err != nil {
		return err
	}
	t.Version = doc.Version
	t.URL = doc.URL
	t.Size = doc.Size
	t.SHA256 = doc.SHA256
	return nil
}
731168
func (p *Parser) parseUnaryExpr() (Expr, error) {
	// If the first token is a LPAREN then parse it as its own grouped expression.
	if tok, _, _ := p.ScanIgnoreWhitespace(); tok == LPAREN {
		expr, err := p.ParseExpr()
		if err != nil {
			return nil, err
		}

		// Expect an RPAREN at the end.
		if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != RPAREN {
			return nil, newParseError(tokstr(tok, lit), []string{")"}, pos)
		}

		return &ParenExpr{Expr: expr}, nil
	}
	p.Unscan()

	// Read next token.
	tok, pos, lit := p.ScanIgnoreWhitespace()
	switch tok {
	case IDENT:
		// If the next immediate token is a left parentheses, parse as function call.
		// Otherwise parse as a variable reference.
		if tok0, _, _ := p.Scan(); tok0 == LPAREN {
			return p.parseCall(lit)
		}

		p.Unscan() // Unscan the last token (wasn't an LPAREN)
		p.Unscan() // Unscan the IDENT token

		// Parse it as a VarRef.
		return p.ParseVarRef()
	case DISTINCT:
		// If the next immediate token is a left parentheses, parse as function call.
		// Otherwise parse as a Distinct expression.
		tok0, pos, lit := p.Scan()
		if tok0 == LPAREN {
			return p.parseCall("distinct")
		} else if tok0 == WS {
			tok1, pos, lit := p.ScanIgnoreWhitespace()
			if tok1 != IDENT {
				return nil, newParseError(tokstr(tok1, lit), []string{"identifier"}, pos)
			}
			return &Distinct{Val: lit}, nil
		}

		return nil, newParseError(tokstr(tok0, lit), []string{"(", "identifier"}, pos)
	case STRING:
		return &StringLiteral{Val: lit}, nil
	case NUMBER:
		v, err := strconv.ParseFloat(lit, 64)
		if err != nil {
			return nil, &ParseError{Message: "unable to parse number", Pos: pos}
		}
		return &NumberLiteral{Val: v}, nil
	case INTEGER:
		v, err := strconv.ParseInt(lit, 10, 64)
		if err != nil {
			// The literal may be too large to fit into an int64. If it is, use an unsigned integer.
			// The check for negative numbers is handled somewhere else so this should always be a positive number.
			if v, err := strconv.ParseUint(lit, 10, 64); err == nil {
				return &UnsignedLiteral{Val: v}, nil
			}
			return nil, &ParseError{Message: "unable to parse integer", Pos: pos}
		}
		return &IntegerLiteral{Val: v}, nil
	case TRUE, FALSE:
		return &BooleanLiteral{Val: (tok == TRUE)}, nil
	case DURATIONVAL:
		v, err := ParseDuration(lit)
		if err != nil {
			return nil, err
		}
		return &DurationLiteral{Val: v}, nil
	case MUL:
		wc := &Wildcard{}
		if tok, _, _ := p.Scan(); tok == DOUBLECOLON {
			tok, pos, lit := p.Scan()
			switch tok {
			case FIELD, TAG:
				wc.Type = tok
			default:
				return nil, newParseError(tokstr(tok, lit), []string{"field", "tag"}, pos)
			}
		} else {
			p.Unscan()
		}
		return wc, nil
	case REGEX:
		re, err := regexp.Compile(lit)
		if err != nil {
			return nil, &ParseError{Message: err.Error(), Pos: pos}
		}
		return &RegexLiteral{Val: re}, nil
	case BOUNDPARAM:
		k := strings.TrimPrefix(lit, "$")
		if len(k) == 0 {
			return nil, errors.New("empty bound parameter")
		}

		v := p.params[k]
		if v == nil {
			return nil, fmt.Errorf("missing parameter: %s", k)
		}

		switch v := v.(type) {
		case float64:
			return &NumberLiteral{Val: v}, nil
		case int64:
			return &IntegerLiteral{Val: v}, nil
		case string:
			return &StringLiteral{Val: v}, nil
		case bool:
			return &BooleanLiteral{Val: v}, nil
		default:
			return nil, fmt.Errorf("unable to bind parameter with type %T", v)
		}
	case ADD, SUB:
		mul := 1
		if tok == SUB {
			mul = -1
		}

		tok0, pos0, lit0 := p.ScanIgnoreWhitespace()
		switch tok0 {
		case NUMBER, INTEGER, DURATIONVAL, LPAREN, IDENT:
			// Unscan the token and use parseUnaryExpr.
			p.Unscan()

			lit, err := p.parseUnaryExpr()
			if err != nil {
				return nil, err
			}

			switch lit := lit.(type) {
			case *NumberLiteral:
				lit.Val *= float64(mul)
			case *IntegerLiteral:
				lit.Val *= int64(mul)
			case *UnsignedLiteral:
				if tok == SUB {
					// Because of twos-complement integers and the method we parse, math.MinInt64 will be parsed
					// as an UnsignedLiteral because it overflows an int64, but it fits into int64 if it were parsed
					// as a negative number instead.
					if lit.Val == uint64(math.MaxInt64+1) {
						return &IntegerLiteral{Val: int64(-lit.Val)}, nil
					}
					return nil, fmt.Errorf("constant -%d underflows int64", lit.Val)
				}
			case *DurationLiteral:
				lit.Val *= time.Duration(mul)
			case *VarRef, *Call, *ParenExpr:
				// Multiply the variable.
				return &BinaryExpr{
					Op:  MUL,
					LHS: &IntegerLiteral{Val: int64(mul)},
					RHS: lit,
				}, nil
			default:
				panic(fmt.Sprintf("unexpected literal: %T", lit))
			}
			return lit, nil
		default:
			return nil, newParseError(tokstr(tok0, lit0), []string{"identifier", "number", "duration", "("}, pos0)
		}
	default:
		return nil, newParseError(tokstr(tok, lit), []string{"identifier", "string", "number", "bool"}, pos)
	}
}
558914
func (p *parser) parseOperand() ast.Expr {
	if p.trace {
		defer un(trace(p, "Operand"))
	}

	switch p.tok {
	case token.IDENT:
		ident := p.parseIdent()
		p.resolve(ident)
		return ident

	case token.INT, token.FLOAT, token.IMAG, token.CHAR, token.STRING:
		x := &ast.BasicLit{p.pos, p.tok, p.lit}
		p.next()
		return x

	case token.LPAREN:
		lparen := p.pos
		p.next()
		p.exprLev++
		x := p.parseExpr()
		p.exprLev--
		rparen := p.expect(token.RPAREN)
		return &ast.ParenExpr{lparen, x, rparen}

	case token.FUNC:
		return p.parseFuncTypeOrLit()

	default:
		t := p.tryRawType(true) // could be type for composite literal or conversion
		if t != nil {
			return t
		}
	}

	pos := p.pos
	p.errorExpected(pos, "operand")
	p.next() // make progress
	return &ast.BadExpr{pos, p.pos}
}
216638
func DecodeBlob(o plumbing.EncodedObject) (*Blob, error) {
	b := &Blob{}
	if err := b.Decode(o); err != nil {
		return nil, err
	}

	return b, nil
}
1292717
func ReadOne(rd io.Reader) (BSON, error) {
	// Read length of document.
	docLen, err := readInt32(rd)
	if err != nil {
		return nil, err
	}

	// Sanity check length.
	if docLen > maxDocLen {
		return nil, errors.New("Doc exceeded maximum size.")
	}

	// Read the document.
	buf := make([]byte, int(docLen))
	binary.LittleEndian.PutUint32(buf, uint32(docLen))
	if _, err := io.ReadFull(rd, buf[4:]); err != nil {
		return nil, err
	}

	return buf, nil
}
258793
func (f *FlagSet) parseOne() (bool, error) {
	if len(f.args) == 0 {
		return false, nil
	}
	s := f.args[0]
	if len(s) == 0 || s[0] != '-' || len(s) == 1 {
		return false, nil
	}
	numMinuses := 1
	if s[1] == '-' {
		numMinuses++
		if len(s) == 2 { // "--" terminates the flags
			f.args = f.args[1:]
			return false, nil
		}
	}
	name := s[numMinuses:]
	if len(name) == 0 || name[0] == '-' || name[0] == '=' {
		return false, f.failf("bad flag syntax: %s", s)
	}

	// ignore go test flags
	if strings.HasPrefix(name, "test.") {
		return false, nil
	}

	// it's a flag. does it have an argument?
	f.args = f.args[1:]
	hasValue := false
	value := ""
	for i := 1; i < len(name); i++ { // equals cannot be first
		if name[i] == '=' {
			value = name[i+1:]
			hasValue = true
			name = name[0:i]
			break
		}
	}
	m := f.formal
	flag, alreadythere := m[name] // BUG
	if !alreadythere {
		if name == "help" || name == "h" { // special case for nice help message.
			f.usage()
			return false, ErrHelp
		}
		return false, f.failf("flag provided but not defined: -%s", name)
	}
	if fv, ok := flag.Value.(boolFlag); ok && fv.IsBoolFlag() { // special case: doesn't need an arg
		if hasValue {
			if err := fv.Set(value); err != nil {
				return false, f.failf("invalid boolean value %q for -%s: %v", value, name, err)
			}
		} else {
			if err := fv.Set("true"); err != nil {
				return false, f.failf("invalid boolean flag %s: %v", name, err)
			}
		}
	} else {
		// It must have a value, which might be the next argument.
		if !hasValue && len(f.args) > 0 {
			// value is the next arg
			hasValue = true
			value, f.args = f.args[0], f.args[1:]
		}
		if !hasValue {
			return false, f.failf("flag needs an argument: -%s", name)
		}
		if err := flag.Value.Set(value); err != nil {
			return false, f.failf("invalid value %q for flag -%s: %v", value, name, err)
		}
	}
	if f.actual == nil {
		f.actual = make(map[string]*Flag)
	}
	f.actual[name] = flag
	return true, nil
}
886802
func (p *parser) parseBracket() error {
	if p.peek() == '?' {
		return p.parseFilter()
	} else if p.peek() == '*' {
		p.scan() // eat *
		if p.scan() != ']' {
			return fmt.Errorf("expected closing bracket after [* at %d", p.column())
		}
		return p.prepareWildcard()
	}
	return p.parseArray()
}
1222694
func (p *parser) parseUnionExpr(n node) node {
	opnd := p.parsePathExpr(n)
Loop:
	for {
		if p.r.typ != itemUnion {
			break Loop
		}
		p.next()
		opnd2 := p.parsePathExpr(n)
		// Checking the node type that must be is node set type?
		opnd = newOperatorNode("|", opnd, opnd2)
	}
	return opnd
}
207944
func (p *responseParser) parseOkWithReply() (int, error) {
	line, err := p.readLine()
	if err != nil {
		return 0, err
	}

	if len(line) < 5 {
		return 0, ErrMalformed
	}

	sign := string(line[0])
	if sign == "+" && string(line[1:3]) == "OK" {
		count, err := strconv.Atoi(string(line[4:]))
		if err != nil {
			return 0, ErrMalformed
		}

		return count, nil
	}

	if sign != "-" {
		return 0, ErrMalformed
	}

	err, _ = p.errorFromLine(line)
	return 0, err
}
91952
func (a *ChannelAnnouncement) Decode(r io.Reader, pver uint32) error {
	err := ReadElements(r,
		&a.NodeSig1,
		&a.NodeSig2,
		&a.BitcoinSig1,
		&a.BitcoinSig2,
		&a.Features,
		a.ChainHash[:],
		&a.ShortChannelID,
		&a.NodeID1,
		&a.NodeID2,
		&a.BitcoinKey1,
		&a.BitcoinKey2,
	)
	if err != nil {
		return err
	}

	// Now that we've read out all the fields that we explicitly know of,
	// we'll collect the remainder into the ExtraOpaqueData field. If there
	// aren't any bytes, then we'll snip off the slice to avoid carrying
	// around excess capacity.
	a.ExtraOpaqueData, err = ioutil.ReadAll(r)
	if err != nil {
		return err
	}
	if len(a.ExtraOpaqueData) == 0 {
		a.ExtraOpaqueData = nil
	}

	return nil
}
1134576
func ToBsonMap(fields ...string) (selBson bson.M) {
	selBson = make(bson.M, len(fields))
	for _, s := range fields {
		selBson[s] = 1
	}
	return
}
1229792
func (p *parser) parseFuncTypeOrLit() ast.Expr {
	if p.trace {
		defer un(trace(p, "FuncTypeOrLit"))
	}

	typ, scope := p.parseFuncType()
	if p.tok != token.LBRACE {
		// function type only
		return typ
	}

	p.exprLev++
	body := p.parseBody(scope)
	p.exprLev--

	return &ast.FuncLit{typ, body}
}