chore: add docs

This commit is contained in:
Kyren223
2024-10-24 20:06:04 +03:00
parent a7f743f035
commit d294b53e68
4 changed files with 14 additions and 11 deletions

View File

@@ -77,6 +77,7 @@ func (e PacketType) IsSupported() bool {
}
}
// True for all packets that a server may push passively to the client.
func (e PacketType) IsPush() bool {
switch e {
case PacketError, PacketSendMessage:

View File

@@ -34,8 +34,6 @@ var (
tlsConfig *tls.Config
)
var ErrClosedNilListener error = errors.New("server: close on nil listener")
func init() {
cert, err := tls.X509KeyPair(certPEM, keyPEM)
if err != nil {
@@ -54,6 +52,8 @@ type server struct {
sessMu sync.RWMutex
}
// Creates a new server on the given port.
// Will generate a unique node ID automatically, will crash if there are no available IDs.
func NewServer(port uint16) server {
assert.Assert(nodeId <= snowflake.NodeMax, "maximum amount of servers reached")
node := snowflake.NewNode(nodeId)
@@ -89,6 +89,11 @@ func (s *server) Node() *snowflake.Node {
return s.node
}
// Starts listening and accepting clients on the server's port.
//
// The given context is used for cancellation,
// note that the server will wait for all active connections to close before
// returning, this is a blocking operation.
func (s *server) ListenAndServe(ctx context.Context) {
listener, err := tls.Listen("tcp4", ":"+strconv.Itoa(int(s.Port)), tlsConfig)
if err != nil {

View File

@@ -52,6 +52,8 @@ func (n *Node) String() string {
return fmt.Sprintf("Node%v(epoch: %v, step: %v, time: %v)", n.node, n.epoch, n.step, n.time)
}
// Creates a new node for generating unique IDs.
// To gurantee uniqueness, the given node ID must be unique.
func NewNode(node int64) *Node {
assert.Assert(nodeBits+stepBits == 22, "node and step bits must add up to 22")
assert.Assert(0 <= node && node <= NodeMax, "node must be within 0 and NodeMax", "node", node)
@@ -67,6 +69,7 @@ func NewNode(node int64) *Node {
}
}
// Generates a unique snowflake ID.
func (n *Node) Generate() ID {
n.mu.Lock()
defer n.mu.Unlock()
@@ -90,7 +93,7 @@ func (n *Node) Generate() ID {
// Json marshling to avoid inprecision of json number (float64)
func (id ID) MarshalJSON() ([]byte, error) {
buffer := make([]byte, 0, 22) // 2 quotes, 19 digits for 2^63, 1 sign
buffer := make([]byte, 0, 22) // 2 quotes, 19 digits, 1 sign
buffer = append(buffer, '"')
buffer = strconv.AppendInt(buffer, int64(id), 10)
buffer = append(buffer, '"')

View File

@@ -1,11 +1,5 @@
package utils
func Clamp(value, min, max int64) int64 {
if value < min {
return min
}
if value > max {
return max
}
return value
func Clamp(value, minimum, maximum int64) int64 {
return min(max(value, minimum), maximum)
}