// Receives one json string from the auto documentation, decode it and request
// to the server the protobuf descriptors. If the the  descriptors route are
// not set, this function identify the route responsible for providing the
// protobuf descriptors.
513747
func (pc *ProtoClient) getDescriptors(data string) error {
	d := []byte(data)
	var jsonmap interface{}
	if err := json.Unmarshal(d, &jsonmap); err != nil {
		return err
	}
	m := jsonmap.(map[string]interface{})
	keysSet := make(map[string]bool)
	getKeys(m, keysSet)

	// load predefined protos
	for _, commands := range pc.info.Commands {
		if commands.input != "" {
			keysSet[commands.input] = true
		}
		if commands.output != "" {
			keysSet[commands.output] = true
		}
	}

	// build commands reference
	handlers := m["handlers"].(map[string]interface{})
	for k, v := range handlers {
		cmdInfo := v.(map[string]interface{})
		in, out, err := getOutputInputNames(cmdInfo)
		if err != nil {
			return err
		}

		var command Command
		command.input = in
		command.output = out

		pc.info.Commands[k] = &command
		if pc.descriptorsRoute == "" && in == "protos.ProtoNames" && out == "protos.ProtoDescriptors" {
			pc.descriptorsRoute = k
		}
	}

	remotes := m["remotes"].(map[string]interface{})
	for k, v := range remotes {
		cmdInfo := v.(map[string]interface{})
		in, out, err := getOutputInputNames(cmdInfo)
		if err != nil {
			return err
		}

		var command Command
		command.input = in
		command.output = out

		pc.info.Commands[k] = &command
	}

	names := make([]string, 0, len(keysSet))
	for key := range keysSet {
		names = append(names, key)
	}

	protname := &protos.ProtoNames{
		Name: names,
	}

	encodedNames, err := proto.Marshal(protname)
	if err != nil {
		return err
	}
	_, err = pc.SendRequest(pc.descriptorsRoute, encodedNames)
	if err != nil {
		return err
	}

	response := <-pc.Client.IncomingMsgChan
	descriptors := &protos.ProtoDescriptors{}
	if err := proto.Unmarshal(response.Data, descriptors); err != nil {
		return err
	}

	// get all proto types
	descriptorArray := make([]*protobuf.FileDescriptorProto, 0)
	for i := range descriptors.Desc {
		fileDescriptorProto, err := unpackDescriptor(descriptors.Desc[i])
		if err != nil {
			return err
		}

		descriptorArray = append(descriptorArray, fileDescriptorProto)
		pc.descriptorsNames[names[i]] = true
	}

	if err = pc.buildProtosFromDescriptor(descriptorArray); err != nil {
		return err
	}

	return nil
}
871986
func marshal(resp http.ResponseWriter, pbResp proto.Message, mime string) error {
	resp.Header().Set("Content-Type", mime)
	switch mime {
	case mimeProto:
		body, err := proto.Marshal(pbResp)
		if err != nil {
			return err
		}
		if _, err := resp.Write(body); err != nil {
			return err
		}
	case mimeJSON:
		var m jsonpb.Marshaler
		var b bytes.Buffer
		if err := m.Marshal(&b, pbResp); err != nil {
			return err
		}
		if _, err := resp.Write(b.Bytes()); err != nil {
			return err
		}
	default:
		return errors.New("invalid interchange format")
	}
	return nil
}
244853
func (d *ProtobufDecoder) DecodeBroadcast(data []byte) (*BroadcastRequest, error) {
	var p BroadcastRequest
	err := p.Unmarshal(data)
	if err != nil {
		return nil, err
	}
	return &p, nil
}
524657
func (this BSON) JSON() (string, error) {
	m, err := this.Map()
	if err != nil {
		return "", err
	}
	j, err := json.Marshal(m)
	if err != nil {
		return "", err
	}
	return string(j), nil
}
150061
func (remote *RemoteDebugger) Protocol() (map[string]interface{}, error) {
	resp, err := responseError(remote.http.Get("/json/protocol", nil, nil))
	if err != nil {
		return nil, err
	}

	var proto map[string]interface{}
	if err = decode(resp, &proto); err != nil {
		return nil, err
	}

	return proto, nil
}
842339
func _proto_marshal(obj proto.Message) []byte {
	buf, err := proto.Marshal(obj)
	if err != nil {
		panic(err)
	}
	return buf
}
307842
func extractRequestInfoFromReq(req *http.Request) *RequestJSON {
	proto := "http://"
	if req.TLS != nil {
		proto = "https://"
	}
	return &RequestJSON{
		ClientIP:   req.RemoteAddr,
		HTTPMethod: req.Method,
		URL:        proto + req.Host + req.RequestURI,
		Referer:    req.Referer(),
		Headers:    parseRequestHeaders(req.Header),
	}
}
94853
func (b *Buffer) DecodeRawBytes(alloc bool) ([]byte, error) {
	val, err := b.buf.DecodeRawBytes(alloc)
	if err == nil {
		b.position += proto.SizeVarint(uint64(len(val))) + len(val)
	} else {
		err = errors.Wrap(err, "error decoding raw bytes with proto.Buffer")
	}
	return val, err
}
320417
func (route *Route) MarshalJSON() ([]byte, error) {
	var vindexName string
	if route.Vindex != nil {
		vindexName = route.Vindex.String()
	}
	marshalRoute := struct {
		Opcode                  RouteOpcode
		Keyspace                *vindexes.Keyspace   `json:",omitempty"`
		Query                   string               `json:",omitempty"`
		FieldQuery              string               `json:",omitempty"`
		Vindex                  string               `json:",omitempty"`
		Values                  []sqltypes.PlanValue `json:",omitempty"`
		OrderBy                 []OrderbyParams      `json:",omitempty"`
		TruncateColumnCount     int                  `json:",omitempty"`
		QueryTimeout            int                  `json:",omitempty"`
		ScatterErrorsAsWarnings bool                 `json:",omitempty"`
	}{
		Opcode:                  route.Opcode,
		Keyspace:                route.Keyspace,
		Query:                   route.Query,
		FieldQuery:              route.FieldQuery,
		Vindex:                  vindexName,
		Values:                  route.Values,
		OrderBy:                 route.OrderBy,
		TruncateColumnCount:     route.TruncateColumnCount,
		QueryTimeout:            route.QueryTimeout,
		ScatterErrorsAsWarnings: route.ScatterErrorsAsWarnings,
	}
	return jsonutil.MarshalNoEscape(marshalRoute)
}
39447
func (decoder *JSONTraceDecoderV1) Read(ctx context.Context, req *http.Request) error {
	var input signalfxformat.InputSpanList
	if err := easyjson.UnmarshalFromReader(req.Body, &input); err != nil {
		return errInvalidJSONTraceFormat
	}

	if len(input) == 0 {
		return nil
	}

	spans := make([]*trace.Span, 0, len(input))

	// Don't let an error converting one set of spans prevent other valid spans
	// in the same request from being rejected.
	var conversionErrs *traceErrs
	for _, is := range input {
		inputSpan := (*InputSpan)(is)
		if inputSpan.isDefinitelyZipkinV2() {
			s, err := inputSpan.fromZipkinV2()
			is.Span.Timestamp = signalfxformat.GetPointerToInt64(inputSpan.Timestamp)
			is.Span.Duration = signalfxformat.GetPointerToInt64(inputSpan.Duration)
			if err != nil {
				conversionErrs = conversionErrs.Append(err)
				continue
			}

			spans = append(spans, s)
		} else {
			derived, err := inputSpan.fromZipkinV1()
			if err != nil {
				conversionErrs = conversionErrs.Append(err)
				continue
			}

			// Zipkin v1 spans can map to multiple spans in Zipkin v2
			spans = append(spans, derived...)
		}
	}

	err := decoder.Sink.AddSpans(ctx, spans)
	return conversionErrs.ToError(err)
}
8967
func (p *Buffer) DecodeRawBytes(alloc bool) (buf []byte, err error) {
	n, err := p.DecodeVarint()
	if err != nil {
		return nil, err
	}

	nb := int(n)
	if nb < 0 {
		return nil, fmt.Errorf("proto: bad byte length %d", nb)
	}
	end := p.index + nb
	if end < p.index || end > len(p.buf) {
		return nil, io.ErrUnexpectedEOF
	}

	if !alloc {
		// todo: check if can get more uses of alloc=false
		buf = p.buf[p.index:end]
		p.index += nb
		return
	}

	buf = make([]byte, nb)
	copy(buf, p.buf[p.index:])
	p.index += nb
	return
}
981581
func (c *Client) DecodeScript(serializedScript []byte) (*btcjson.DecodeScriptResult, error) {
	return c.DecodeScriptAsync(serializedScript).Receive()
}
1293712
func Proto(rw http.ResponseWriter, status int, pb proto.Message) error {
	rw.Header().Set("Content-Type", "application/json")
	rw.WriteHeader(status)
	return jpb.Marshal(rw, pb)
}
130033
func (s *SerializableHttpRequest) ToJson() string {
	jsonVal, err := json.Marshal(s)
	if err != nil || jsonVal == nil {
		return fmt.Sprintf("Error marshalling SerializableHttpRequest to json: %s", err)
	}
	return string(jsonVal)
}
226456
func (p ProtobufStateSerializer) Deserialize(serialized string, state interface{}) error {
	bin, err := base64.StdEncoding.DecodeString(serialized)
	if err != nil {
		return err
	}
	err = proto.Unmarshal(bin, state.(proto.Message))

	return err
}
237537
func decodeRequest(in []byte) (*Request, error) {
	request := &Request{}

	if err := json.NewDecoder(bytes.NewReader(in)).Decode(request); err != nil {
		return nil, err
	}

	// @step: validate the node request
	if err := validateNodeRegistrationRequest(request); err != nil {
		return nil, err
	}

	return request, nil
}
590152
func protoToJSON(msg proto.Message) ([]byte, error) {
	if reflect.ValueOf(msg).IsNil() {
		panic("We're nil here")
	}
	var b bytes.Buffer
	m := jsonpb.Marshaler{
		EnumsAsInts:  false,
		EmitDefaults: true,
		Indent:       "  ",
		OrigName:     true,
	}
	err := m.Marshal(&b, msg)
	if err != nil {
		return nil, err
	}
	return b.Bytes(), nil
}