Example #1
0
// Encode encodes a packet to be sent from the server to client into an array of
// bytes. The values of each field are encoded into the byte array according to
// their type.
//
// Once all of the data is serialized, the length and ID will be written in
// front of it, according to the specification given in `connection.go` from
// L41-L46.
//
// If an error occurs during encoding, an empty byte array and that
// error will be returned.
func (d *Dealer) Encode(h packet.Holder) ([]byte, error) {
	out := new(bytes.Buffer)
	out.Write(util.Uvarint(uint32(h.ID())))

	v := reflect.ValueOf(h)

	for i := 0; i < v.NumField(); i++ {
		ftype, ok := v.Field(i).Interface().(types.Type)
		if !ok {
			// XXX(taylor): special-casing
			ftype = types.JSON{V: v.Field(i).Interface()}
		}

		if _, err := ftype.Encode(out); err != nil {
			return nil, err
		}
	}

	return append(
		util.Uvarint(uint32(out.Len())),
		out.Bytes()...,
	), nil
}
Example #2
0
func (s String) Encode(w io.Writer) (int, error) {
	var n int
	var err error

	length := util.Uvarint(uint32(len(s)))

	written, err := w.Write(length)
	n += written
	if err != nil {
		return written, err
	}

	written, err = w.Write([]byte(s))
	n += written
	if err != nil {
		return written, err
	}

	return written, nil
}
Example #3
0
func (u UVarint) Encode(w io.Writer) (int, error) {
	return w.Write(util.Uvarint(uint32(u)))
}