diff --git a/marshal.go b/marshal.go index 14bd340..59d7385 100644 --- a/marshal.go +++ b/marshal.go @@ -36,3 +36,30 @@ func (uuid *UUID) UnmarshalBinary(data []byte) error { copy(uuid[:], data) return nil } + +// MarshalBinaryLittleEndian implements encoding.BinaryMarshaler. +func (uuid UUID) MarshalBinaryLittleEndian() ([]byte, error) { + var uuidLittleEndian UUID = UUID { + // convert first 3 fields from big-endian to little-endian + uuid[3], uuid[2], uuid[1], uuid[0], + uuid[5], uuid[4], + uuid[7], uuid[6], + } + // all the rest fields keep byte order + copy(uuidLittleEndian[8:], uuid[8:]) + return uuidLittleEndian[:], nil +} + +// UnmarshalBinaryLittleEndian implements encoding.BinaryUnmarshaler. +func (uuid *UUID) UnmarshalBinaryLittleEndian(data []byte) error { + if len(data) != 16 { + return fmt.Errorf("invalid UUID (got %d bytes)", len(data)) + } + // convert first 3 fields from little-endian to big-endian + uuid[0] = data[3]; uuid[1] = data[2]; uuid[2] = data[1]; uuid[3] = data[0] + uuid[4] = data[5]; uuid[5] = data[4] + uuid[6] = data[7]; uuid[7] = data[6] + // all the rest fields keep byte order + copy(uuid[8:], data[8:]) + return nil +} diff --git a/uuid.go b/uuid.go index 60d26bb..c12e46b 100644 --- a/uuid.go +++ b/uuid.go @@ -157,6 +157,14 @@ func FromBytes(b []byte) (uuid UUID, err error) { return uuid, err } +// FromBytesLittleEndian creates a new UUID from a byte slice with little-endian +// byte encoding for the first three fields. Returns an error if the slice +// does not have a length of 16. The bytes are copied from the slice. +func FromBytesLittleEndian(b []byte) (uuid UUID, err error) { + err = uuid.UnmarshalBinaryLittleEndian(b) + return uuid, err +} + // Must returns uuid if err is nil and panics otherwise. func Must(uuid UUID, err error) UUID { if err != nil {