Repository navigation
ulid: avoid allocation in Make #139
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 3 commits
5224ed9
3d32314
6fe93b7
ac1fa91
be89982
c0bae8b
abec379
91cf12c
d590126
7dc6ab9
c537502
5c9e9ba
f3a7829
92f7145
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -132,9 +132,9 @@ func MustNewDefault(t time.Time) ULID { | |
| return MustNew(Timestamp(t), defaultEntropy) | ||
| } | ||
|
|
||
| var defaultEntropy = func() io.Reader { | ||
| var defaultEntropy = func() *lockedMonotonicEntropy { | ||
| rng := rand.New(rand.NewSource(time.Now().UnixNano())) | ||
| return &LockedMonotonicReader{MonotonicReader: Monotonic(rng, 0)} | ||
| return &lockedMonotonicEntropy{MonotonicEntropy: Monotonic(rng, 0)} | ||
| }() | ||
|
|
||
| // DefaultEntropy returns a thread-safe per process monotonically increasing | ||
|
|
@@ -145,11 +145,16 @@ func DefaultEntropy() io.Reader { | |
|
|
||
| // Make returns a ULID with the current time in Unix milliseconds and | ||
| // monotonically increasing entropy for the same millisecond. | ||
| // It is safe for concurrent use, leveraging a sync.Pool underneath for minimal | ||
| // contention. | ||
| // It is safe for concurrent use. | ||
| func Make() (id ULID) { | ||
| // NOTE: MustNew can't panic since DefaultEntropy never returns an error. | ||
| return MustNew(Now(), defaultEntropy) | ||
| ms := Now() | ||
| if err := id.SetTime(ms); err != nil { | ||
| panic(err) | ||
| } | ||
| if err := defaultEntropy.monotonicRead(ms, id[6:]); err != nil { | ||
| panic(err) | ||
| } | ||
| return id | ||
| } | ||
|
|
||
| // Parse parses an encoded ULID, returning an error in case of failure. | ||
|
|
@@ -611,25 +616,66 @@ func (r *LockedMonotonicReader) MonotonicRead(ms uint64, p []byte) (err error) { | |
| // MonotonicEntropy is an opaque type that provides monotonic entropy. | ||
| type MonotonicEntropy struct { | ||
| io.Reader | ||
| ms uint64 | ||
| inc uint64 | ||
| entropy uint80 | ||
| rand [8]byte | ||
| rng rng | ||
| ms uint64 | ||
| inc uint64 | ||
| entropy uint80 | ||
| initialized bool // A zero entropy seed is valid state, not an uninitialized value. | ||
| seed [10]byte | ||
| rand [8]byte | ||
| rng rng | ||
| } | ||
|
|
||
| // MonotonicRead implements the MonotonicReader interface. | ||
| func (m *MonotonicEntropy) MonotonicRead(ms uint64, entropy []byte) (err error) { | ||
| if !m.entropy.IsZero() && m.ms == ms { | ||
| if m.initialized && m.ms == ms { | ||
| err = m.increment() | ||
| m.entropy.AppendTo(entropy) | ||
| } else if _, err = io.ReadFull(m.Reader, entropy); err == nil { | ||
| m.ms = ms | ||
| m.entropy.SetBytes(entropy) | ||
| m.initialized = true | ||
| } | ||
| return err | ||
| } | ||
|
|
||
| // monotonicRead is the Make fast path. It never passes the output slice to an | ||
| // entropy reader; on a new timestamp it reads into the receiver's buffer first. | ||
| func (m *MonotonicEntropy) monotonicRead(ms uint64, entropy []byte) error { | ||
| if m.initialized && m.ms == ms { | ||
| err := m.increment() | ||
| m.entropy.AppendTo(entropy) | ||
| return err | ||
| } | ||
|
|
||
| n, err := io.ReadFull(m.Reader, m.seed[:]) | ||
| copy(entropy, m.seed[:n]) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| m.ms = ms | ||
| m.entropy.SetBytes(m.seed[:]) | ||
| m.initialized = true | ||
| return nil | ||
| } | ||
|
|
||
| // lockedMonotonicEntropy serializes access to the process-wide entropy state. | ||
| type lockedMonotonicEntropy struct { | ||
| mu sync.Mutex | ||
| *MonotonicEntropy | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Also, please use a named field here instead of embedding, and explicitly define Read so that it takes the lock before using MonotonicEntropy.
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The comment here is also wrong, it wraps any monotonic entropy source, not only the specific singleton mentioned.
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. PR head: The wrapper now stores
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. PR head: I changed the wrapper comment to describe synchronization of the wrapped monotonic source rather than implying it only applies to the process singleton. |
||
| } | ||
|
|
||
| func (r *lockedMonotonicEntropy) MonotonicRead(ms uint64, p []byte) error { | ||
| r.mu.Lock() | ||
| defer r.mu.Unlock() | ||
| return r.MonotonicEntropy.MonotonicRead(ms, p) | ||
| } | ||
|
|
||
| func (r *lockedMonotonicEntropy) monotonicRead(ms uint64, p []byte) error { | ||
| r.mu.Lock() | ||
| defer r.mu.Unlock() | ||
| return r.MonotonicEntropy.monotonicRead(ms, p) | ||
| } | ||
|
|
||
| // increment the previous entropy number with a random number | ||
| // of up to m.inc (inclusive). | ||
| func (m *MonotonicEntropy) increment() error { | ||
|
|
@@ -716,7 +762,3 @@ func (u *uint80) Add(n uint64) (overflow bool) { | |
| } | ||
| return u.Hi < hi | ||
| } | ||
|
|
||
| func (u uint80) IsZero() bool { | ||
| return u.Hi == 0 && u.Lo == 0 | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,88 @@ | ||
| // Copyright 2016 The Oklog Authors | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| package ulid | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "errors" | ||
| "testing" | ||
| ) | ||
|
|
||
| // These tests replace process-wide entropy and must not run in parallel. | ||
| func setDefaultMonotonicEntropy(t *testing.T, entropy MonotonicEntropy) { | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This isn't valid, and even if it was I don't think these tests are testing anything useful. Please remove this test file.
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. PR head: The earlier |
||
| t.Helper() | ||
|
|
||
| defaultEntropy.mu.Lock() | ||
| original := *defaultEntropy.MonotonicEntropy | ||
| *defaultEntropy.MonotonicEntropy = entropy | ||
| defaultEntropy.mu.Unlock() | ||
|
|
||
| t.Cleanup(func() { | ||
| defaultEntropy.mu.Lock() | ||
| *defaultEntropy.MonotonicEntropy = original | ||
| defaultEntropy.mu.Unlock() | ||
| }) | ||
| } | ||
|
|
||
| func TestMakeSharesDefaultEntropy(t *testing.T) { | ||
| seed := make([]byte, 10) | ||
| setDefaultMonotonicEntropy(t, MonotonicEntropy{ | ||
| Reader: bytes.NewReader(bytes.Repeat([]byte{0}, 20)), | ||
| inc: 1, | ||
| }) | ||
|
|
||
| id := Make() | ||
| if !bytes.Equal(id[6:], seed) { | ||
| t.Fatalf("Make entropy: got %v, want %v", id[6:], seed) | ||
| } | ||
|
|
||
| next, err := New(id.Time(), DefaultEntropy()) | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
|
|
||
| want := id | ||
| for i := len(want) - 1; i >= 6; i-- { | ||
| want[i]++ | ||
| if want[i] != 0 { | ||
| break | ||
| } | ||
| } | ||
| if next != want { | ||
| t.Fatalf("New after Make: got %v, want %v", next, want) | ||
| } | ||
| } | ||
|
|
||
| func TestMakePanicsOnEntropyReadError(t *testing.T) { | ||
| want := errors.New("entropy read failed") | ||
| setDefaultMonotonicEntropy(t, MonotonicEntropy{ | ||
| Reader: errorEntropyReader{err: want}, | ||
| inc: 1, | ||
| }) | ||
|
|
||
| defer func() { | ||
| if got := recover(); got != want { | ||
| t.Fatalf("Make panic: got %v, want %v", got, want) | ||
| } | ||
| }() | ||
| _ = Make() | ||
| } | ||
|
|
||
| type errorEntropyReader struct { | ||
| err error | ||
| } | ||
|
|
||
| func (r errorEntropyReader) Read([]byte) (int, error) { | ||
| return 0, r.err | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why did you make the changes in a separate method, rather than just updating MonotonicRead? Please respond plainly.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actually this is worth saying explicitly: Make isn't some special bespoke thing, it's just a little helper over the exported package API for a common use case, constructing a ULID (New()) with the current system time (Now()) and a reasonable monotonic entropy source (DefaultEntropy) without having to provide either of those params explicitly. Avoiding allocs is great but that optimization shouldn't just be in one specific helper function, it should be available so users can leverage it too, and so shouldn't rely on an unexported method that only this package can call...
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
PR head:
f3a782943b10f59e3914700fd062725a3ba9d830. Response to this feedback.The existing exported
MustNewDefault(time.Time)now reaches the same value path, so callers with a timestamp can use the optimization through a public helper without new API. I left directNewandMustNewgeneric because they accept arbitrary readers; those direct default-entropy calls remain generic and are not claimed allocation-free.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
PR head:
f3a782943b10f59e3914700fd062725a3ba9d830. Response to this feedback.The value path is separate so
Make's returned entropy slice is not passed through the generic reader interface, whereNew'sMonotonicReaderpath makes it escape. The fast path reads new seed bytes into wrapper-owned storage and copies them to the value; the genericMonotonicReadmethod remains for public reader dispatch.