Merge branch '8784-dir-listings'
[arvados.git] / sdk / go / httpserver / id_generator.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: Apache-2.0
4
5 package httpserver
6
7 import (
8         "strconv"
9         "sync"
10         "time"
11 )
12
13 // IDGenerator generates alphanumeric strings suitable for use as
14 // unique IDs (a given IDGenerator will never return the same ID
15 // twice).
16 type IDGenerator struct {
17         // Prefix is prepended to each returned ID.
18         Prefix string
19
20         lastID int64
21         mtx    sync.Mutex
22 }
23
24 // Next returns a new ID string. It is safe to call Next from multiple
25 // goroutines.
26 func (g *IDGenerator) Next() string {
27         id := time.Now().UnixNano()
28         g.mtx.Lock()
29         if id <= g.lastID {
30                 id = g.lastID + 1
31         }
32         g.lastID = id
33         g.mtx.Unlock()
34         return g.Prefix + strconv.FormatInt(id, 36)
35 }