diff options
author | Paul Borman <borman@google.com> | 2011-08-08 11:45:10 -0700 |
---|---|---|
committer | Paul Borman <borman@google.com> | 2011-08-08 11:45:10 -0700 |
commit | e130d97558da97862b63559fa31be05c88ce3cc7 (patch) | |
tree | 0ef4d1d6ab8ed9f108ad5091c0da5246959f5e70 /version1.go | |
download | google-uuid-e130d97558da97862b63559fa31be05c88ce3cc7.tar.gz |
Initial checking of the go-uuid code.
Diffstat (limited to 'version1.go')
-rw-r--r-- | version1.go | 52 |
1 files changed, 52 insertions, 0 deletions
diff --git a/version1.go b/version1.go new file mode 100644 index 0000000..6f92fda --- /dev/null +++ b/version1.go @@ -0,0 +1,52 @@ +// Copyright 2011 Google Inc. All rights reserved. +// Author: borman@google.com (Paul Borman) +// +// 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 uuid + +import ( + "encoding/binary" +) + +// NewUUID returns a Version 1 UUID based on the current NodeID and clock +// sequence, and the current time. If the NodeID has not been set by SetNodeID +// or SetNodeInterface then it will be set automatically. If the NodeID cannot +// be set NewUUID returns nil. If clock sequence has not been set by +// SetClockSequence then it will be set automatically. If GetTime fails to +// return the current NewUUID returns nil. +func NewUUID() UUID { + if nodeID == nil { + SetNodeInterface("") + } + + now, err := GetTime() + if err != nil { + return nil + } + + uuid := make([]byte, 16) + + time_low := uint32(now & 0xffffffff) + time_mid := uint16((now >> 32) & 0xffff) + time_hi := uint16((now >> 48) & 0x0fff) + time_hi |= 0x1000 // Version 1 + + binary.BigEndian.PutUint32(uuid[0:], time_low) + binary.BigEndian.PutUint16(uuid[4:], time_mid) + binary.BigEndian.PutUint16(uuid[6:], time_hi) + binary.BigEndian.PutUint16(uuid[8:], clock_seq) + copy(uuid[10:], nodeID) + + return uuid +} |