Matthias Andreas Benkard | 832a54e | 2019-01-29 09:27:38 +0100 | [diff] [blame^] | 1 | // Copyright 2011 Google Inc. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | package uuid |
| 6 | |
| 7 | import ( |
| 8 | "encoding/binary" |
| 9 | ) |
| 10 | |
| 11 | // NewUUID returns a Version 1 UUID based on the current NodeID and clock |
| 12 | // sequence, and the current time. If the NodeID has not been set by SetNodeID |
| 13 | // or SetNodeInterface then it will be set automatically. If the NodeID cannot |
| 14 | // be set NewUUID returns nil. If clock sequence has not been set by |
| 15 | // SetClockSequence then it will be set automatically. If GetTime fails to |
| 16 | // return the current NewUUID returns nil. |
| 17 | func NewUUID() UUID { |
| 18 | if nodeID == nil { |
| 19 | SetNodeInterface("") |
| 20 | } |
| 21 | |
| 22 | now, seq, err := GetTime() |
| 23 | if err != nil { |
| 24 | return nil |
| 25 | } |
| 26 | |
| 27 | uuid := make([]byte, 16) |
| 28 | |
| 29 | time_low := uint32(now & 0xffffffff) |
| 30 | time_mid := uint16((now >> 32) & 0xffff) |
| 31 | time_hi := uint16((now >> 48) & 0x0fff) |
| 32 | time_hi |= 0x1000 // Version 1 |
| 33 | |
| 34 | binary.BigEndian.PutUint32(uuid[0:], time_low) |
| 35 | binary.BigEndian.PutUint16(uuid[4:], time_mid) |
| 36 | binary.BigEndian.PutUint16(uuid[6:], time_hi) |
| 37 | binary.BigEndian.PutUint16(uuid[8:], seq) |
| 38 | copy(uuid[10:], nodeID) |
| 39 | |
| 40 | return uuid |
| 41 | } |