1package uuid
2
3import (
4	"fmt"
5)
6
7// Sequence represents an iterated value to help ensure unique UUID generations
8// values across the same domain, server restarts and clock issues.
9type Sequence uint16
10
11// Node represents the last node id setup used by the generator.
12type Node []byte
13
14// Store is used for storage of UUID generation history to ensure continuous
15// running of the UUID generator between restarts and to monitor synchronicity
16// while generating new V1 or V2 UUIDs.
17type Store struct {
18	Timestamp
19	Sequence
20	Node
21}
22
23// String returns a string representation of the Store.
24func (o Store) String() string {
25	return fmt.Sprintf("Timestamp[%s]-Sequence[%d]-Node[%x]", o.Timestamp, o.Sequence, o.Node)
26}
27
28// Saver is an interface to setup a non volatile store within your system
29// if you wish to use V1 and V2 UUIDs based on your node id and a constant time
30// it is highly recommended to implement this.
31// A default implementation has been provided. FileSystemStorage, the default
32// behaviour of the package is to generate random sequences where a Saver is not
33// specified.
34type Saver interface {
35	// Read is run once, use this to setup your UUID state machine
36	// Read should also return the UUID state from the non volatile store
37	Read() (Store, error)
38
39	// Save saves the state to the non volatile store and is called only if
40	Save(Store)
41
42	// Init allows default setup of a new Saver
43	Init() Saver
44}
45
46// RegisterSaver register's a uuid.Saver implementation to the default package
47// uuid.Generator. If you wish to save the generator state, this function must
48// be run before any calls to V1 or V2 UUIDs. uuid.RegisterSaver cannot be run
49// in conjunction with uuid.Init. You may implement the uuid.Saver interface
50// or use the provided uuid.Saver's from the uuid/savers package.
51func RegisterSaver(saver Saver) (err error) {
52	notOnce := true
53	once.Do(func() {
54		generator.Lock()
55		generator.Saver = saver
56		generator.Unlock()
57		err = generator.init()
58		notOnce = false
59		return
60	})
61	if notOnce {
62		panic("uuid: Register* methods cannot be called more than once.")
63	}
64	return
65}
66