diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index cb5013f..c281d82 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -4,7 +4,7 @@ jobs: test: strategy: matrix: - go-version: [1.19.x, 1.20.x] + go-version: [1.20.x, 1.21.x] os: [ubuntu-latest] runs-on: ${{matrix.os}} steps: diff --git a/README.md b/README.md index 39ab7ed..bde8b0f 100644 --- a/README.md +++ b/README.md @@ -33,10 +33,10 @@ go get github.com/sony/sonyflake Usage ----- -The function NewSonyflake creates a new Sonyflake instance. +The function New creates a new Sonyflake instance. ```go -func NewSonyflake(st Settings) *Sonyflake +func New(st Settings) (*Sonyflake, error) ``` You can configure Sonyflake by the struct Settings: diff --git a/sonyflake.go b/sonyflake.go index d4394fe..a335824 100644 --- a/sonyflake.go +++ b/sonyflake.go @@ -53,21 +53,29 @@ type Sonyflake struct { machineID uint16 } +var ( + ErrStartTimeAhead = errors.New("start time is ahead of now") + ErrNoPrivateAddress = errors.New("no private ip address") + ErrOverTimeLimit = errors.New("over the time limit") + ErrInvalidMachineID = errors.New("invalid machine id") +) + var defaultInterfaceAddrs = net.InterfaceAddrs -// NewSonyflake returns a new Sonyflake configured with the given Settings. -// NewSonyflake returns nil in the following cases: +// New returns a new Sonyflake configured with the given Settings. +// New returns an error in the following cases: // - Settings.StartTime is ahead of the current time. // - Settings.MachineID returns an error. // - Settings.CheckMachineID returns false. -func NewSonyflake(st Settings) *Sonyflake { +func New(st Settings) (*Sonyflake, error) { + if st.StartTime.After(time.Now()) { + return nil, ErrStartTimeAhead + } + sf := new(Sonyflake) sf.mutex = new(sync.Mutex) sf.sequence = uint16(1<= 1<