0
0
mirror of https://github.com/rls-moe/nyx synced 2025-08-19 06:18:38 +00:00

MVP, no mod tools or anything but it works

This commit is contained in:
Tim Schuster
2017-03-12 20:37:53 +01:00
parent 70b12c516a
commit 69b0d20825
186 changed files with 44200 additions and 0 deletions

View File

@@ -0,0 +1,20 @@
MIT License
Copyright (c) 2017 Arke Works
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1 @@
You can find the original generator at https://github.com/arke-works/arke/blob/master/snowflakes/generator.go

View File

@@ -0,0 +1,75 @@
package snowflakes
import (
"errors"
"sync"
"time"
)
const (
counterLen = 10
counterMask = -1 ^ (-1 << counterLen)
)
var (
errNoFuture = errors.New("Start Time cannot be set in the future")
)
// Generator is a fountain for new snowflakes. StartTime must be
// initialized to a past point in time and Instance ID can be any
// positive value or 0.
//
// If any value is not correctly set, new IDs cannot be produced.
type Generator struct {
StartTime int64
mutex *sync.Mutex
sequence int32
now int64
}
// NewID generates a new, unique snowflake value
//
// Up to 8192 snowflakes per second can be requested
// If exhausted, it blocks and sleeps until a new second
// of unix time starts.
//
// The return value is signed but always positive.
//
// Additionally, the return value is monotonic for a single
// instance and weakly monotonic for many instances.
func (g *Generator) NewID() (int64, error) {
if g.mutex == nil {
g.mutex = new(sync.Mutex)
}
if g.StartTime > time.Now().Unix() {
return 0, errNoFuture
}
g.mutex.Lock()
defer g.mutex.Unlock()
var (
now int64
flake int64
)
now = int64(time.Now().Unix())
if now == g.now {
g.sequence = (g.sequence + 1) & counterMask
if g.sequence == 0 {
for now <= g.now {
now = int64(time.Now().Unix())
time.Sleep(time.Microsecond * 100)
}
}
} else {
g.sequence = 0
}
g.now = now
flake = int64(
((now - g.StartTime) << counterLen) |
int64(g.sequence))
return flake, nil
}