| 1 | package slack |
| 2 | |
| 3 | import "sync/atomic" |
| 4 | |
| 5 | // IDGenerator provides an interface for generating integer ID values. |
| 6 | type IDGenerator interface { |
| 7 | Next() int |
| 8 | } |
| 9 | |
| 10 | // NewSafeID returns a new instance of an IDGenerator which is safe for |
| 11 | // concurrent use by multiple goroutines. |
| 12 | func NewSafeID(startID int) IDGenerator { |
| 13 | return &safeID{ |
| 14 | nextID: int64(startID), |
| 15 | } |
| 16 | } |
| 17 | |
| 18 | type safeID struct { |
| 19 | nextID int64 |
| 20 | } |
| 21 | |
| 22 | // make sure safeID implements the IDGenerator interface. |
| 23 | var _ IDGenerator = (*safeID)(nil) |
| 24 | |
| 25 | // Next implements IDGenerator.Next. |
| 26 | func (s *safeID) Next() int { |
| 27 | id := atomic.AddInt64(&s.nextID, 1) |
| 28 | |
| 29 | return int(id) |
| 30 | } |