1//  Copyright (c) 2014 Couchbase, Inc.
2//  Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
3//  except in compliance with the License. You may obtain a copy of the License at
4//    http://www.apache.org/licenses/LICENSE-2.0
5//  Unless required by applicable law or agreed to in writing, software distributed under the
6//  License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
7//  either express or implied. See the License for the specific language governing permissions
8//  and limitations under the License.
9
10package common
11
12import (
13	"bytes"
14	crypt "crypto/rand"
15	"encoding/binary"
16	"io"
17	rnd "math/rand"
18	"strconv"
19)
20
21type UUID []byte
22
23func NewUUID() (UUID, error) {
24	uuid := make([]byte, 8)
25	n, err := io.ReadFull(crypt.Reader, uuid)
26	if n != len(uuid) || err != nil {
27		return UUID(nil), err
28	}
29	return UUID(uuid), nil
30}
31
32func (u UUID) Uint64() uint64 {
33	return binary.LittleEndian.Uint64(([]byte)(u))
34}
35
36func (u UUID) Str() string {
37	var buf bytes.Buffer
38	for i := 0; i < len(u); i++ {
39		if i > 0 {
40			buf.WriteString(":")
41		}
42		buf.WriteString(strconv.FormatUint(uint64(u[i]), 16))
43	}
44	return buf.String()
45}
46
47func SeedProcess() {
48	uuid, err := NewUUID()
49	if err != nil {
50		seed := uuid.Uint64()
51		rnd.Seed(int64(seed))
52	}
53}
54