summaryrefslogtreecommitdiff
path: root/src/uuid.go
blob: 6c4b8f63d13351b2df08bd7916f71f9334d0b3e8 (plain) (blame)
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package uuid

import (
	"crypto/rand"
	"encoding/hex"
	"errors"
	"fmt"
	"io"
	"os"
	"strings"
)



const (
	ByteCount     = 16
	dashCount     = 4
	encodedLength = (ByteCount * 2) + dashCount
)

var (
	dashIndexes  = []int{ 8, 13, 18, 23 }
	randomReader = rand.Reader

	ErrBadLength       = errors.New(
		"uuid: str isn't of the correct length",
	)
	ErrBadDashCount    = errors.New("uuid: Bad count of dashes in string")
	ErrBadDashPosition = errors.New("uuid: Bad char in string")
)



type UUID [ByteCount]byte



func NewFrom(r io.Reader) (UUID, error) {
	var uuid UUID
	_, err := io.ReadFull(r, uuid[:])
	if err != nil {
		return UUID{}, err
	}
	uuid[6] = (uuid[6] & 0x0f) | 0x40 // v4
	uuid[8] = (uuid[8] & 0x3f) | 0x80 // variant 10
	return uuid, nil
}

func New() UUID {
	uuid, err := NewFrom(randomReader)
	if err != nil {
		panic(err)
	}
	return uuid
}

func (uuid UUID) String() string {
	dst := [encodedLength]byte {
		0, 0, 0, 0,
		0, 0, 0, 0,
		'-',
		0, 0, 0, 0,
		'-',
		0, 0, 0, 0,
		'-',
		0, 0, 0, 0,
		'-',
		0, 0, 0, 0,
		0, 0, 0, 0,
		0, 0, 0, 0,
	}

	hex.Encode(dst[ 0:8],  uuid[0:4])
	hex.Encode(dst[ 9:13], uuid[4:6])
	hex.Encode(dst[14:18], uuid[6:8])
	hex.Encode(dst[19:23], uuid[8:10])
	hex.Encode(dst[24:36], uuid[10:])

	return string(dst[:])
}

func FromString(str string) (UUID, error) {
	if len(str) != encodedLength {
		return UUID{}, ErrBadLength
	}

	if strings.Count(str, "-") != dashCount {
		return UUID{}, ErrBadDashCount
	}

	for _, idx := range dashIndexes {
		if str[idx] != '-' {
			return UUID{}, ErrBadDashPosition
		}
	}

	hexstr := strings.Join(strings.Split(str, "-"), "")
	data, err := hex.DecodeString(hexstr)
	if err != nil {
		return UUID{}, err
	}

	return [ByteCount]byte(data), nil
}



func Main() {
	if len(os.Args) < 2 {
		fmt.Println(New().String())
	} else {
		_, err := FromString(strings.TrimSpace(os.Args[1]))
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(3)
		}
	}
}