Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for little-endian byte order representation. #75

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
27 changes: 27 additions & 0 deletions marshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
8 changes: 8 additions & 0 deletions uuid.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down