// parseHeap parses a heapz legacy or a growthz profile and
// returns a newly populated Profile.
962813
func parseHeap(b []byte) (p *Profile, err error) {
	r := bytes.NewBuffer(b)
	l, err := r.ReadString('\n')
	if err != nil {
		return nil, errUnrecognized
	}

	sampling := ""

	if header := heapHeaderRE.FindStringSubmatch(l); header != nil {
		p = &Profile{
			SampleType: []*ValueType{
				{Type: "objects", Unit: "count"},
				{Type: "space", Unit: "bytes"},
			},
			PeriodType: &ValueType{Type: "objects", Unit: "bytes"},
		}

		var period int64
		if len(header[6]) > 0 {
			if period, err = strconv.ParseInt(string(header[6]), 10, 64); err != nil {
				return nil, errUnrecognized
			}
		}

		switch header[5] {
		case "heapz_v2", "heap_v2":
			sampling, p.Period = "v2", period
		case "heapprofile":
			sampling, p.Period = "", 1
		case "heap":
			sampling, p.Period = "v2", period/2
		default:
			return nil, errUnrecognized
		}
	} else if header = growthHeaderRE.FindStringSubmatch(l); header != nil {
		p = &Profile{
			SampleType: []*ValueType{
				{Type: "objects", Unit: "count"},
				{Type: "space", Unit: "bytes"},
			},
			PeriodType: &ValueType{Type: "heapgrowth", Unit: "count"},
			Period:     1,
		}
	} else if header = fragmentationHeaderRE.FindStringSubmatch(l); header != nil {
		p = &Profile{
			SampleType: []*ValueType{
				{Type: "objects", Unit: "count"},
				{Type: "space", Unit: "bytes"},
			},
			PeriodType: &ValueType{Type: "allocations", Unit: "count"},
			Period:     1,
		}
	} else {
		return nil, errUnrecognized
	}

	if LegacyHeapAllocated {
		for _, st := range p.SampleType {
			st.Type = "alloc_" + st.Type
		}
	} else {
		for _, st := range p.SampleType {
			st.Type = "inuse_" + st.Type
		}
	}

	locs := make(map[uint64]*Location)
	for {
		l, err = r.ReadString('\n')
		if err != nil {
			if err != io.EOF {
				return nil, err
			}

			if l == "" {
				break
			}
		}

		if isSpaceOrComment(l) {
			continue
		}
		l = strings.TrimSpace(l)

		if sectionTrigger(l) != unrecognizedSection {
			break
		}

		value, blocksize, addrs, err := parseHeapSample(l, p.Period, sampling)
		if err != nil {
			return nil, err
		}
		var sloc []*Location
		for i, addr := range addrs {
			// Addresses from stack traces point to the next instruction after
			// each call.  Adjust by -1 to land somewhere on the actual call
			// (except for the leaf, which is not a call).
			if i > 0 {
				addr--
			}
			loc := locs[addr]
			if locs[addr] == nil {
				loc = &Location{
					Address: addr,
				}
				p.Location = append(p.Location, loc)
				locs[addr] = loc
			}
			sloc = append(sloc, loc)
		}

		p.Sample = append(p.Sample, &Sample{
			Value:    value,
			Location: sloc,
			NumLabel: map[string][]int64{"bytes": {blocksize}},
		})
	}

	if err = parseAdditionalSections(l, r, p); err != nil {
		return nil, err
	}
	return p, nil
}
639068
func parseMap(r reflect.Value, node *XMLNode, tag reflect.StructTag) error {
	if r.IsNil() {
		r.Set(reflect.MakeMap(r.Type()))
	}

	if tag.Get("flattened") == "" { // look at all child entries
		for _, entry := range node.Children["entry"] {
			parseMapEntry(r, entry, tag)
		}
	} else { // this element is itself an entry
		parseMapEntry(r, node, tag)
	}

	return nil
}
854526
func parseHeader(buf []byte, cursor *int, msg *Message) error {
	if err := parsePriority(buf, cursor, msg); err != nil {
		return err
	}

	if err := parseVersion(buf, cursor, msg); err != nil {
		return err
	}

	if err := parseTimestamp(buf, cursor, msg); err != nil {
		return err
	}

	var err error
	if msg.Hostname, err = parseNextField(buf, cursor); err != nil {
		return err
	}

	if msg.AppName, err = parseNextField(buf, cursor); err != nil {
		return err
	}

	if msg.ProcID, err = parseNextField(buf, cursor); err != nil {
		return err
	}

	if msg.MsgID, err = parseNextField(buf, cursor); err != nil {
		return err
	}

	return nil
}
203452
func profileRead(p *pprof.Profile, debug int) func(context.Context) ([]byte, time.Time, error) {
	return func(_ context.Context) ([]byte, time.Time, error) {
		var b bytes.Buffer
		err := p.WriteTo(&b, debug)
		if err != nil {
			return nil, time.Time{}, err
		}

		return b.Bytes(), time.Now(), nil
	}
}
654067
func parseThread(b []byte) (*Profile, error) {
	r := bytes.NewBuffer(b)

	var line string
	var err error
	for {
		// Skip past comments and empty lines seeking a real header.
		line, err = r.ReadString('\n')
		if err != nil {
			return nil, err
		}
		if !isSpaceOrComment(line) {
			break
		}
	}

	if m := threadzStartRE.FindStringSubmatch(line); m != nil {
		// Advance over initial comments until first stack trace.
		for {
			line, err = r.ReadString('\n')
			if err != nil {
				if err != io.EOF {
					return nil, err
				}

				if line == "" {
					break
				}
			}
			if sectionTrigger(line) != unrecognizedSection || line[0] == '-' {
				break
			}
		}
	} else if t := threadStartRE.FindStringSubmatch(line); len(t) != 4 {
		return nil, errUnrecognized
	}

	p := &Profile{
		SampleType: []*ValueType{{Type: "thread", Unit: "count"}},
		PeriodType: &ValueType{Type: "thread", Unit: "count"},
		Period:     1,
	}

	locs := make(map[uint64]*Location)
	// Recognize each thread and populate profile samples.
	for sectionTrigger(line) == unrecognizedSection {
		if strings.HasPrefix(line, "---- no stack trace for") {
			line = ""
			break
		}
		if t := threadStartRE.FindStringSubmatch(line); len(t) != 4 {
			return nil, errUnrecognized
		}

		var addrs []uint64
		line, addrs, err = parseThreadSample(r)
		if err != nil {
			return nil, errUnrecognized
		}
		if len(addrs) == 0 {
			// We got a --same as previous threads--. Bump counters.
			if len(p.Sample) > 0 {
				s := p.Sample[len(p.Sample)-1]
				s.Value[0]++
			}
			continue
		}

		var sloc []*Location
		for i, addr := range addrs {
			// Addresses from stack traces point to the next instruction after
			// each call.  Adjust by -1 to land somewhere on the actual call
			// (except for the leaf, which is not a call).
			if i > 0 {
				addr--
			}
			loc := locs[addr]
			if locs[addr] == nil {
				loc = &Location{
					Address: addr,
				}
				p.Location = append(p.Location, loc)
				locs[addr] = loc
			}
			sloc = append(sloc, loc)
		}

		p.Sample = append(p.Sample, &Sample{
			Value:    []int64{1},
			Location: sloc,
		})
	}

	if err = parseAdditionalSections(line, r, p); err != nil {
		return nil, err
	}

	return p, nil
}
776624
func ParseMap(data string) (map[string]string, error) {
	keys, values, err := ParseOrderedMap(data)
	if err != nil {
		return nil, err
	}
	res := make(map[string]string, len(keys))
	for i, key := range keys {
		res[key] = values[i]
	}
	return res, 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)
	}
}
1164845
func Parse(exp *string) (criteria.Expression, error) {
	if exp == nil || len(*exp) == 0 {
		return criteria.Literal(true), nil
	}
	var unmarshalled map[string]interface{}
	err := json.Unmarshal([]byte(*exp), &unmarshalled)
	if err != nil {
		return nil, errors.WithStack(err)
	}
	var result *criteria.Expression
	if len(unmarshalled) > 0 {
		for key, value := range unmarshalled {
			current := criteria.Equals(criteria.Field(key), criteria.Literal(value))
			if result == nil {
				result = &current
			} else {
				current = criteria.And(*result, current)
				result = &current
			}
		}
		return *result, nil
	}
	return criteria.Literal(true), nil
}
413089
func (parser *StandardResultParser) ParseFacetCounts(response *SolrResponse, sr *SolrResult) {
	if facetCounts, ok := response.Response["facet_counts"].(map[string]interface{}); ok {
		sr.FacetCounts = facetCounts
	}
}
7557
func parseQueryMeta(resp *http.Response, q *QueryMeta) error {
	header := resp.Header

	// Parse the X-Consul-Index (if it's set - hash based blocking queries don't
	// set this)
	if indexStr := header.Get("X-Consul-Index"); indexStr != "" {
		index, err := strconv.ParseUint(indexStr, 10, 64)
		if err != nil {
			return fmt.Errorf("Failed to parse X-Consul-Index: %v", err)
		}
		q.LastIndex = index
	}
	q.LastContentHash = header.Get("X-Consul-ContentHash")

	// Parse the X-Consul-LastContact
	last, err := strconv.ParseUint(header.Get("X-Consul-LastContact"), 10, 64)
	if err != nil {
		return fmt.Errorf("Failed to parse X-Consul-LastContact: %v", err)
	}
	q.LastContact = time.Duration(last) * time.Millisecond

	// Parse the X-Consul-KnownLeader
	switch header.Get("X-Consul-KnownLeader") {
	case "true":
		q.KnownLeader = true
	default:
		q.KnownLeader = false
	}

	// Parse X-Consul-Translate-Addresses
	switch header.Get("X-Consul-Translate-Addresses") {
	case "true":
		q.AddressTranslationEnabled = true
	default:
		q.AddressTranslationEnabled = false
	}

	// Parse Cache info
	if cacheStr := header.Get("X-Cache"); cacheStr != "" {
		q.CacheHit = strings.EqualFold(cacheStr, "HIT")
	}
	if ageStr := header.Get("Age"); ageStr != "" {
		age, err := strconv.ParseUint(ageStr, 10, 64)
		if err != nil {
			return fmt.Errorf("Failed to parse Age Header: %v", err)
		}
		q.CacheAge = time.Duration(age) * time.Second
	}

	return nil
}
1030377
func (c *Parser) ParseHeaders() error {
	id, size, err := c.IDnSize()
	if err != nil {
		return err
	}
	c.ID = id
	if c.ID != RiffID {
		return fmt.Errorf("%s - %s", c.ID, ErrFmtNotSupported)
	}
	c.Size = size
	if err := binary.Read(c.r, binary.BigEndian, &c.Format); err != nil {
		return err
	}

	return nil
}
1020712
func ParsePhase(target string) (Phase, bool) {
	for p, name := range phaseNames {
		if target == name {
			return Phase(p), true
		}
	}
	return UNKNOWN, false
}
1177102
func parseThread(b []byte) (*Profile, error) {
	s := bufio.NewScanner(bytes.NewBuffer(b))
	// Skip past comments and empty lines seeking a real header.
	for s.Scan() && isSpaceOrComment(s.Text()) {
	}

	line := s.Text()
	if m := threadzStartRE.FindStringSubmatch(line); m != nil {
		// Advance over initial comments until first stack trace.
		for s.Scan() {
			if line = s.Text(); isMemoryMapSentinel(line) || strings.HasPrefix(line, "-") {
				break
			}
		}
	} else if t := threadStartRE.FindStringSubmatch(line); len(t) != 4 {
		return nil, errUnrecognized
	}

	p := &Profile{
		SampleType: []*ValueType{{Type: "thread", Unit: "count"}},
		PeriodType: &ValueType{Type: "thread", Unit: "count"},
		Period:     1,
	}

	locs := make(map[uint64]*Location)
	// Recognize each thread and populate profile samples.
	for !isMemoryMapSentinel(line) {
		if strings.HasPrefix(line, "---- no stack trace for") {
			line = ""
			break
		}
		if t := threadStartRE.FindStringSubmatch(line); len(t) != 4 {
			return nil, errUnrecognized
		}

		var addrs []uint64
		var err error
		line, addrs, err = parseThreadSample(s)
		if err != nil {
			return nil, err
		}
		if len(addrs) == 0 {
			// We got a --same as previous threads--. Bump counters.
			if len(p.Sample) > 0 {
				s := p.Sample[len(p.Sample)-1]
				s.Value[0]++
			}
			continue
		}

		var sloc []*Location
		for i, addr := range addrs {
			// Addresses from stack traces point to the next instruction after
			// each call. Adjust by -1 to land somewhere on the actual call
			// (except for the leaf, which is not a call).
			if i > 0 {
				addr--
			}
			loc := locs[addr]
			if locs[addr] == nil {
				loc = &Location{
					Address: addr,
				}
				p.Location = append(p.Location, loc)
				locs[addr] = loc
			}
			sloc = append(sloc, loc)
		}

		p.Sample = append(p.Sample, &Sample{
			Value:    []int64{1},
			Location: sloc,
		})
	}

	if err := parseAdditionalSections(s, p); err != nil {
		return nil, err
	}

	cleanupDuplicateLocations(p)
	return p, nil
}
122802
func (p *Parser) parseAppName() (string, error) {
	return parseUpToLen(p.buff, &p.cursor, p.l, 48, ErrInvalidAppName)
}
983080
func getHeapProfile(w http.ResponseWriter, r *http.Request) {
	// Ensure up-to-date data.
	runtime.GC()
	w.Header().Set("Content-Type", "application/octet-stream")
	if err := pprof.Lookup("heap").WriteTo(w, 0); err != nil {
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		w.WriteHeader(http.StatusInternalServerError)
		fmt.Fprintf(w, "Could not get heap profile: %s\n", err)
	}
}
1189760
func Parse(r io.Reader) (*Profile, error) {
	data, err := ioutil.ReadAll(r)
	if err != nil {
		return nil, err
	}
	return ParseData(data)
}
404485
func parseHaveVal(val string) (size uint64, err error) {
	pipei := strings.Index(val, "|")
	if pipei >= 0 {
		// filter out the "indexed" suffix
		val = val[:pipei]
	}
	return strconv.ParseUint(val, 10, 32)
}