For representing full identifiers of system and member. Signed-off-by: Yonah <contrib@gensokyo.uk>
90 lines
2.3 KiB
Go
90 lines
2.3 KiB
Go
package ident
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"encoding/binary"
|
|
"unsafe"
|
|
)
|
|
|
|
// M represents a unique member identifier.
|
|
type M struct {
|
|
// A per-system value incremented by some unspecified amount every time the
|
|
// metadata of a member first appears to the backend.
|
|
Serial uint64
|
|
// An instant in time, some time after the corresponding member metadata
|
|
// first appeared to the backend, represented in nanoseconds since
|
|
// 1970-01-01.
|
|
Time uint64
|
|
// Randomly generated value. The implementation must guarantee that the same
|
|
// value cannot be emitted for a Time value.
|
|
ID uint64
|
|
|
|
// Underlying system.
|
|
System S
|
|
}
|
|
|
|
func (*M) ident() {}
|
|
|
|
const (
|
|
// SizeMember is the size of the binary representation of [M].
|
|
SizeMember = SizeSystem * 2
|
|
// EncodedSizeMember is the size of the string representation of [M].
|
|
EncodedSizeMember = SizeMember / 3 * 4
|
|
)
|
|
|
|
// EncodedSize returns the number of bytes appended by Encode.
|
|
func (*M) EncodedSize() int { return EncodedSizeMember }
|
|
|
|
// Encode appends the canonical string representation of mid to dst and returns
|
|
// the extended buffer.
|
|
func (mid *M) Encode(dst []byte) []byte {
|
|
var buf [SizeMember - SizeSystem]byte
|
|
|
|
p := buf[:]
|
|
binary.LittleEndian.PutUint64(p, mid.Serial)
|
|
p = p[8:]
|
|
binary.LittleEndian.PutUint64(p, mid.Time)
|
|
p = p[8:]
|
|
binary.LittleEndian.PutUint64(p, mid.ID)
|
|
dst = base64.URLEncoding.AppendEncode(dst, buf[:])
|
|
|
|
return mid.System.Encode(dst)
|
|
}
|
|
|
|
// String returns the canonical string representation of mid.
|
|
func (mid *M) String() string {
|
|
s := mid.Encode(nil)
|
|
return unsafe.String(unsafe.SliceData(s), len(s))
|
|
}
|
|
|
|
// MarshalText returns the result of Encode.
|
|
func (mid *M) MarshalText() (data []byte, err error) {
|
|
return mid.Encode(nil), nil
|
|
}
|
|
|
|
// UnmarshalText strictly decodes data into mid.
|
|
func (mid *M) UnmarshalText(data []byte) error {
|
|
if len(data) != EncodedSizeMember {
|
|
return &UnexpectedSizeError{data, EncodedSizeMember}
|
|
}
|
|
|
|
var buf [SizeMember - SizeSystem]byte
|
|
if n, err := base64.URLEncoding.Decode(
|
|
buf[:],
|
|
data[:EncodedSizeMember-EncodedSizeSystem],
|
|
); err != nil {
|
|
return err
|
|
} else if n != SizeMember-SizeSystem {
|
|
return ErrNewline
|
|
}
|
|
|
|
p := buf[:]
|
|
mid.Serial = binary.LittleEndian.Uint64(p)
|
|
p = p[8:]
|
|
mid.Time = binary.LittleEndian.Uint64(p)
|
|
p = p[8:]
|
|
mid.ID = binary.LittleEndian.Uint64(p)
|
|
|
|
return mid.System.UnmarshalText(data[EncodedSizeMember-EncodedSizeSystem:])
|
|
}
|