Debian Codegraph @

go/pkg/proton/uuid.go

raw
1 /*
2 Licensed to the Apache Software Foundation (ASF) under one
3 or more contributor license agreements. See the NOTICE file
4 distributed with this work for additional information
5 regarding copyright ownership. The ASF licenses this file
6 to you under the Apache License, Version 2.0 (the
7 "License"); you may not use this file except in compliance
8 with the License. You may obtain a copy of the License at
9
10 http://www.apache.org/licenses/LICENSE-2.0
11
12 Unless required by applicable law or agreed to in writing,
13 software distributed under the License is distributed on an
14 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 KIND, either express or implied. See the License for the
16 specific language governing permissions and limitations
17 under the License.
18 */
19
20 package proton
21
22 import (
23 "fmt"
24 "math/rand"
25 "sync"
26 "time"
27 )
28
29 // UUID is a 16-byte Universally Unique Identifier
30 type UUID [16]byte
31
32 // String gives a UUID in standard string format.
33 func (u UUID) String() string {
34 return fmt.Sprintf("%X-%X-%X-%X-%X", u[0:4], u[4:6], u[6:8], u[8:10], u[10:])
35 }
36
37 // Don't mess with the default random source.
38 var randomSource = rand.NewSource(time.Now().UnixNano())
39 var randomLock sync.Mutex
40
41 func random() byte {
42 randomLock.Lock()
43 defer randomLock.Unlock()
44 return byte(randomSource.Int63())
45 }
46
47 // UUID4 returns a randomly-generated (version 4) UUID, as per RFC4122
48 func UUID4() UUID {
49 var u UUID
50 for i := 0; i < len(u); i++ {
51 u[i] = random()
52 }
53 // See /https://tools.ietf.org/html/rfc4122#section-4.4
54 u[6] = (u[6] & 0x0F) | 0x40 // Version bits to 4
55 u[8] = (u[8] & 0x3F) | 0x80 // Reserved bits (top two) set to 01
56 return u
57 }