// encodeRelayMessage wraps a message in the messageRelayType, adding the length and
// address of the end recipient to the front of the message
426172
func encodeRelayMessage(t messageType, addr net.UDPAddr, msg interface{}) ([]byte, error) {
	buf := bytes.NewBuffer(nil)
	handle := codec.MsgpackHandle{}
	encoder := codec.NewEncoder(buf, &handle)

	buf.WriteByte(uint8(messageRelayType))
	if err := encoder.Encode(relayHeader{DestAddr: addr}); err != nil {
		return nil, err
	}

	buf.WriteByte(uint8(t))
	err := encoder.Encode(msg)
	return buf.Bytes(), err
}
1179609
func (c *Conversation) dhKeyMessage() ([]byte, error) {
	c.initAKE()

	// TODO: where does this 40 come from?
	y, err := c.randMPI(make([]byte, 40)[:])

	if err != nil {
		return nil, err
	}

	c.setSecretExponent(y)
	wipeBigInt(y)

	return c.serializeDHKey(), nil
}
947886
func (bot TgBot) SimpleSendMessage(msg Message, text string) (res Message, err error) {
	ressm := bot.SendMessage(msg.Chat.ID, text, nil, nil, nil, nil)
	return splitResultInMessageError(ressm)
}
822399
func (c *Callbacks) OnCUserMessageSayTextChannel(fn func(*dota.CUserMessageSayTextChannel) error) {
	c.onCUserMessageSayTextChannel = append(c.onCUserMessageSayTextChannel, fn)
}
2256
func (m *Memberlist) encodeBroadcastNotify(node string, msgType messageType, msg interface{}, notify chan struct{}) {
	buf, err := encode(msgType, msg)
	if err != nil {
		m.logger.Printf("[ERR] memberlist: Failed to encode message for broadcast: %s", err)
	} else {
		m.queueBroadcast(node, buf.Bytes(), notify)
	}
}
179840
func messageToHex(msg wire.Message) (string, error) {
	var buf bytes.Buffer
	if err := msg.BtcEncode(&buf, maxProtocolVersion, wire.WitnessEncoding); err != nil {
		context := fmt.Sprintf("Failed to encode msg of type %T", msg)
		return "", internalRPCError(err.Error(), context)
	}

	return hex.EncodeToString(buf.Bytes()), nil
}
97422
func (handler *Handler) handleMessage(msg *pb.ChaincodeMessage, errc chan error) error {
	if msg.Type == pb.ChaincodeMessage_KEEPALIVE {
		chaincodeLogger.Debug("Sending KEEPALIVE response")
		handler.serialSendAsync(msg, nil) // ignore errors, maybe next KEEPALIVE will work
		return nil
	}
	chaincodeLogger.Debugf("[%s] Handling ChaincodeMessage of type: %s(state:%s)", shorttxid(msg.Txid), msg.Type, handler.state)

	var err error

	switch handler.state {
	case ready:
		err = handler.handleReady(msg, errc)
	case established:
		err = handler.handleEstablished(msg, errc)
	case created:
		err = handler.handleCreated(msg, errc)
	default:
		err = errors.Errorf("[%s] Chaincode handler cannot handle message (%s) with payload size (%d) while in state: %s", msg.Txid, msg.Type, len(msg.Payload), handler.state)
	}

	if err != nil {
		payload := []byte(err.Error())
		errorMsg := &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid}
		handler.serialSend(errorMsg)
		return err
	}

	return nil
}
810086
func (z *IterGen) EncodeMsg(en *msgp.Writer) (err error) {
	// map header, size 3
	// write "T0"
	err = en.Append(0x83, 0xa2, 0x54, 0x30)
	if err != nil {
		return
	}
	err = en.WriteUint32(z.T0)
	if err != nil {
		err = msgp.WrapError(err, "T0")
		return
	}
	// write "IntervalHint"
	err = en.Append(0xac, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x48, 0x69, 0x6e, 0x74)
	if err != nil {
		return
	}
	err = en.WriteUint32(z.IntervalHint)
	if err != nil {
		err = msgp.WrapError(err, "IntervalHint")
		return
	}
	// write "B"
	err = en.Append(0xa1, 0x42)
	if err != nil {
		return
	}
	err = en.WriteBytes(z.B)
	if err != nil {
		err = msgp.WrapError(err, "B")
		return
	}
	return
}
139850
func (z *GraphiteTagDelSeries) EncodeMsg(en *msgp.Writer) (err error) {
	// map header, size 2
	// write "Paths"
	err = en.Append(0x82, 0xa5, 0x50, 0x61, 0x74, 0x68, 0x73)
	if err != nil {
		return
	}
	err = en.WriteArrayHeader(uint32(len(z.Paths)))
	if err != nil {
		err = msgp.WrapError(err, "Paths")
		return
	}
	for za0001 := range z.Paths {
		err = en.WriteString(z.Paths[za0001])
		if err != nil {
			err = msgp.WrapError(err, "Paths", za0001)
			return
		}
	}
	// write "Propagate"
	err = en.Append(0xa9, 0x50, 0x72, 0x6f, 0x70, 0x61, 0x67, 0x61, 0x74, 0x65)
	if err != nil {
		return
	}
	err = en.WriteBool(z.Propagate)
	if err != nil {
		err = msgp.WrapError(err, "Propagate")
		return
	}
	return
}
593713
func (p *Buffer) DecodeMessage(pb Message) error {
	enc, err := p.DecodeRawBytes(false)
	if err != nil {
		return err
	}
	return NewBuffer(enc).Unmarshal(pb)
}
886237
func MarshalInternalMessage(m Message, s Serializer) ([]byte, error) {
	typ := getMessageType(m)
	buf, err := s.Marshal(m)
	if err != nil {
		return nil, errors.Wrap(err, "marshaling")
	}
	return append([]byte{typ}, buf...), nil
}
354372
func (r *Request) EncodeMsg(w *msgp.Writer) error {
	var bm msgp.Encodable

	if r.Body != nil {
		var ok bool
		bm, ok = r.Body.(msgp.Encodable)
		if !ok {
			return ErrNotEncodable
		}
	}

	var err error

	if err = w.WriteArrayHeader(RequestPackSize); err != nil {
		return err
	}

	if err = w.WriteInt(RequestType); err != nil {
		return err
	}

	if err = w.WriteString(r.ID); err != nil {
		return err
	}

	if err = w.WriteString(r.Method); err != nil {
		return err
	}

	// No body to encode. Write a zero-length params array.
	if bm == nil {
		return w.WriteArrayHeader(0)
	}

	// 1-item array containing the body.
	if err = w.WriteArrayHeader(1); err != nil {
		return err
	}

	return msgp.Encode(w, bm)
}
586449
func EncodeEvent(line map[string]string) []byte {
	buf := bp.Get().(*bytes.Buffer)
	defer bp.Put(buf)
	buf.Reset()
	binary.Write(buf, binary.BigEndian, uint32(0)) // Message Size
	binary.Write(buf, binary.BigEndian, uint32(0)) // Map Count

	// These fields should be present in every event
	_time := line["_time"]
	host := line["host"]
	source := line["source"]
	sourcetype := line["sourcetype"]
	index := line["index"]

	// These are optional
	channel, hasChannel := line["_channel"]
	conf, hasConf := line["_conf"]
	_, hasLineBreaker := line["_linebreaker"]
	_, hasDone := line["_done"]
	var indexFields string

	// Check time for subseconds
	if strings.ContainsRune(_time, '.') {
		timeparts := strings.Split(_time, ".")
		_time = timeparts[0]
		indexFields += "_subsecond::" + timeparts[1] + " "
	}

	for k, v := range line {
		switch k {
		case "source", "sourcetype", "host", "index", "_raw", "_time", "_channel", "_conf", "_linebreaker", "_done":
			break
		default:
			indexFields += k + "::" + v + " "
		}
	}

	maps := 7
	encodeKeyValue("_raw", line["_raw"], buf)
	if len(indexFields) > 0 {
		indexFields = strings.TrimRight(indexFields, " ")
		encodeKeyValue("_meta", indexFields, buf)
		maps++
	}
	if hasDone {
		encodeKeyValue("_done", "_done", buf)
		maps++
	}
	if hasLineBreaker {
		encodeKeyValue("_linebreaker", "_linebreaker", buf)
		maps++
	}
	encodeKeyValue("_hpn", "_hpn", buf)
	encodeKeyValue("_time", _time, buf)
	if hasConf {
		encodeKeyValue("_conf", conf, buf)
		maps++
	}
	encodeKeyValue("MetaData:Source", "source::"+source, buf)
	encodeKeyValue("MetaData:Host", "host::"+host, buf)
	encodeKeyValue("MetaData:Sourcetype", "sourcetype::"+sourcetype, buf)
	if hasChannel {
		encodeKeyValue("_channel", channel, buf)
		maps++
	}
	encodeKeyValue("_MetaData:Index", index, buf)

	binary.Write(buf, binary.BigEndian, uint32(0)) // Null terminate raw
	encodeString("_raw", buf)                      // Raw trailer

	ret := buf.Bytes()

	binary.BigEndian.PutUint32(ret, uint32(len(ret)-4)) // Don't include null terminator in message size
	binary.BigEndian.PutUint32(ret[4:], uint32(maps))   // Include extra map for _done key and one for _raw

	return ret
}
740590
func (a *InternalMessageInfo) Marshal(b []byte, msg Message, deterministic bool) ([]byte, error) {
	u := getMessageMarshalInfo(msg, a)
	ptr := toPointer(&msg)
	if ptr.isNil() {
		// We get here if msg is a typed nil ((*SomeMessage)(nil)),
		// so it satisfies the interface, and msg == nil wouldn't
		// catch it. We don't want crash in this case.
		return b, ErrNil
	}
	return u.marshal(b, ptr, deterministic)
}
1191011
func (ps *PubSub) onMessage(ctx context.Context, msg message) error {
	if ps.MaxMessageLen > 0 && len(msg.Data()) > ps.MaxMessageLen {
		msg.Ack()
		return fmt.Errorf("message longer than max_message_len (%d > %d)", len(msg.Data()), ps.MaxMessageLen)
	}

	var data []byte
	if ps.Base64Data {
		strData, err := base64.StdEncoding.DecodeString(string(msg.Data()))
		if err != nil {
			return fmt.Errorf("unable to base64 decode message: %v", err)
		}
		data = []byte(strData)
	} else {
		data = msg.Data()
	}

	metrics, err := ps.parser.Parse(data)
	if err != nil {
		msg.Ack()
		return err
	}

	if len(metrics) == 0 {
		msg.Ack()
		return nil
	}

	select {
	case <-ctx.Done():
		return ctx.Err()
	case ps.sem <- empty{}:
		break
	}

	ps.Lock()
	defer ps.Unlock()

	id := ps.acc.AddTrackingMetricGroup(metrics)
	if ps.undelivered == nil {
		ps.undelivered = make(map[telegraf.TrackingID]message)
	}
	ps.undelivered[id] = msg

	return nil
}
499577
func (r *RelayMessageOption) SetRelayMessage(p *RelayMessage) error {
	b, err := p.MarshalBinary()
	if err != nil {
		return err
	}

	*r = b
	return nil
}
13167
func (self *Client) CaptureMessage(message string, extra map[string]interface{}) (err error) {
	timestamp := time.Now().UTC()
	timestampStr := timestamp.Format(iso8601)

	packet := sentryRequest{
		Project:   self.Project,
		Message:   message,
		Timestamp: timestampStr,
		Level:     "error",
		Logger:    self.Logger,
		Extra:     extra,
	}

	buf := new(bytes.Buffer)
	b64Encoder := base64.NewEncoder(base64.StdEncoding, buf)
	writer := zlib.NewWriter(b64Encoder)
	jsonEncoder := json.NewEncoder(writer)

	if err := jsonEncoder.Encode(packet); err != nil {
		return err
	}

	err = writer.Close()
	if err != nil {
		return err
	}

	err = b64Encoder.Close()
	if err != nil {
		return err
	}

	_, err = self.sentryTransport.Send(buf.Bytes(), timestamp)
	if err != nil {
		return err
	}

	return nil
}