func MarshalComposite()

in internal/encoding/encode.go [287:344]


func MarshalComposite(wr *buffer.Buffer, code AMQPType, fields []MarshalField) error {
	// lastSetIdx is the last index to have a non-omitted field.
	// start at -1 as it's possible to have no fields in a composite
	lastSetIdx := -1

	// marshal each field into it's index in rawFields,
	// null fields are skipped, leaving the index nil.
	for i, f := range fields {
		if f.Omit {
			continue
		}
		lastSetIdx = i
	}

	// write header only
	if lastSetIdx == -1 {
		wr.Append([]byte{
			0x0,
			byte(TypeCodeSmallUlong),
			byte(code),
			byte(TypeCodeList0),
		})
		return nil
	}

	// write header
	WriteDescriptor(wr, code)

	// write fields
	wr.AppendByte(byte(TypeCodeList32))

	// write temp size, replace later
	sizeIdx := wr.Len()
	wr.Append([]byte{0, 0, 0, 0})
	preFieldLen := wr.Len()

	// field count
	wr.AppendUint32(uint32(lastSetIdx + 1))

	// write null to each index up to lastSetIdx
	for _, f := range fields[:lastSetIdx+1] {
		if f.Omit {
			wr.AppendByte(byte(TypeCodeNull))
			continue
		}
		err := Marshal(wr, f.Value)
		if err != nil {
			return err
		}
	}

	// fix size
	size := uint32(wr.Len() - preFieldLen)
	buf := wr.Bytes()
	binary.BigEndian.PutUint32(buf[sizeIdx:], size)

	return nil
}