-
Notifications
You must be signed in to change notification settings - Fork 11
/
uuid.go
103 lines (86 loc) · 2.34 KB
/
uuid.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// Copyright © 2022 Kaleido, Inc.
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package fftypes
import (
"context"
"database/sql/driver"
"encoding/binary"
"github.com/google/uuid"
"github.com/hyperledger/firefly-common/pkg/i18n"
)
// UUID is a wrapper on a UUID implementation, ensuring Value handles nil
type UUID uuid.UUID
func ParseUUID(ctx context.Context, uuidStr string) (*UUID, error) {
u, err := uuid.Parse(uuidStr)
if err != nil {
return nil, i18n.WrapError(context.Background(), err, i18n.MsgInvalidUUID)
}
uuid := UUID(u)
return &uuid, nil
}
func MustParseUUID(uuidStr string) *UUID {
uuid := UUID(uuid.MustParse(uuidStr))
return &uuid
}
func NewUUID() *UUID {
u := UUID(uuid.New())
return &u
}
func (u *UUID) String() string {
if u == nil {
return ""
}
return (*uuid.UUID)(u).String()
}
func (u UUID) MarshalText() ([]byte, error) {
return (uuid.UUID)(u).MarshalText()
}
func (u *UUID) UnmarshalText(b []byte) error {
return (*uuid.UUID)(u).UnmarshalText(b)
}
func (u UUID) MarshalBinary() ([]byte, error) {
return (uuid.UUID)(u).MarshalBinary()
}
func (u *UUID) UnmarshalBinary(b []byte) error {
return (*uuid.UUID)(u).UnmarshalBinary(b)
}
func (u *UUID) HashBucket(buckets int) int {
if u == nil {
return 0
}
// Take the last random 4 bytes and mod it against the bucket count to generate
// a deterministic hash bucket allocation for the UUID V4
return int(binary.BigEndian.Uint64((*u)[8:]) % uint64(buckets))
}
func (u *UUID) Value() (driver.Value, error) {
if u == nil {
return nil, nil
}
return (uuid.UUID)(*u).Value()
}
func (u *UUID) Scan(src interface{}) error {
return (*uuid.UUID)(u).Scan(src)
}
func (u *UUID) Equals(u2 *UUID) bool {
switch {
case u == nil && u2 == nil:
return true
case u == nil || u2 == nil:
return false
default:
return *u == *u2
}
}