From 06f9b47996ac97eb466742954006435df461ffc2 Mon Sep 17 00:00:00 2001 From: Yoshiyuki Mineo Date: Mon, 14 Aug 2023 01:27:55 +0900 Subject: [PATCH] Introduce New function (#47) * feat(Sonyflake): define error variables * feat(Sonyflake): add New() function - minor logic improvements - return errors * tests(Sonyflake): remove old TestNilSonyflake test function in favour of the New() function coverage * gofmt * Update error messages and comments * Introduce New function --------- Co-authored-by: Quetzy Garcia --- README.md | 4 +-- sonyflake.go | 42 +++++++++++++++++++------ sonyflake_test.go | 79 +++++++++++++++++++++++++++++++++-------------- 3 files changed, 89 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index 9c9ebeb..0e6cdab 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 1c1402e..548b243 100644 --- a/sonyflake.go +++ b/sonyflake.go @@ -52,21 +52,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<