8 Commits

7 changed files with 169 additions and 77 deletions

31
container/option.go Normal file
View File

@@ -0,0 +1,31 @@
package ucontainer
// Option can either hold a value, or nothing.
type Option[T any] struct {
value T
exists bool
}
// O creates a new option with the specified value.
func O[T any] (value T) Option[T] {
return Option[T] {
value: value,
exists: true,
}
}
// Void returns an option with no value.
func Void[T any] () Option[T] {
return Option[T] { }
}
// Exists returns if the value is currently set.
func (option Option[T]) Exists () bool {
return option.exists
}
// Value returns the value and true if the value exists. If not, it returns the
// zero value and false.
func (option Option[T]) Value () (T, bool) {
return option.value, option.exists
}

View File

@@ -1,31 +0,0 @@
package ucontainer
// Optional can either hold a value, or nothing.
type Optional[T any] struct {
value T
exists bool
}
// O creates a new optional with the specified value.
func O[T any] (value T) Optional[T] {
return Optional[T] {
value: value,
exists: true,
}
}
// Void returns an optional with no value.
func Void[T any] () Optional[T] {
return Optional[T] { }
}
// Exists returns if the value is currently set.
func (optional Optional[T]) Exists () bool {
return optional.exists
}
// Value returns the value and true if the value exists. If not, it returns the
// zero value and false.
func (optional Optional[T]) Value () (T, bool) {
return optional.value, optional.exists
}

38
sync/atomic/generic.go Normal file
View File

@@ -0,0 +1,38 @@
package uatomic
import "sync/atomic"
// Atom is a generic wrapper for atomic.Value.
type Atom[T comparable] struct {
value atomic.Value
}
type atomWrapper[T comparable] struct { value T }
// CompareAndSwap executes the compare-and-swap operation for the Atom.
func (atom *Atom[T]) CompareAndSwap(old, neww T) (swapped bool) {
return atom.value.CompareAndSwap(
atomWrapper[T] { value: old },
atomWrapper[T] { value: neww })
}
func (atom *Atom[T]) Load() T {
return castSafe[T](atom.value.Load())
}
func (atom *Atom[T]) Store(val T) {
atom.value.Store(val)
}
func (atom *Atom[T]) Swap(neww T) T {
return castSafe[T](atom.value.Swap(neww))
}
func castSafe[T comparable](value any) T {
var zero T
if value == nil {
return zero
} else {
return value.(T)
}
}

View File

@@ -1,6 +1,6 @@
package usync package usync
import "sync" import "sync/atomic"
// Error defines errors that this package can produce // Error defines errors that this package can produce
type Error string; const ( type Error string; const (
@@ -12,83 +12,74 @@ func (err Error) Error () string {
return string(err) return string(err)
} }
// if you know of a better way, i'd like to hear of it. otherwise, STFU!!!!
// Gate wraps a channel and allows the receiver to abruptly stop receiving // Gate wraps a channel and allows the receiver to abruptly stop receiving
// messages without causing the sender to lock up. // messages without causing the sender to lock up.
type Gate[T any] struct { type Gate[T any] struct {
channel chan T channel atomic.Value
lock sync.RWMutex
open bool
bufferSize int bufferSize int
} }
// NewGate creates a new gate with no buffer. // NewGate creates a new gate with no buffer.
func NewGate[T any] () Gate[T] { func NewGate[T any] () Gate[T] {
return Gate[T] { return NewBufferedGate[T](0)
channel: make(chan T),
open: true,
}
} }
// NewBufferedGate creates a new gate with a buffer. // NewBufferedGate creates a new gate with a buffer.
func NewBufferedGate[T any] (buffer int) Gate[T] { func NewBufferedGate[T any] (buffer int) Gate[T] {
return Gate[T] { gate := Gate[T] {
channel: make(chan T, buffer),
open: true,
bufferSize: buffer, bufferSize: buffer,
} }
gate.channel.Store(make(chan T, buffer))
return gate
} }
// Send sends and item to the channel, returning whether the item was sent. // Send sends and item to the channel, returning whether the item was sent.
func (this *Gate[T]) Send (item T) bool { func (this *Gate[T]) Send (item T) (ok bool) {
this.lock.RLock() channel := this.load()
defer this.lock.RUnlock() if channel == nil { return false }
if !this.open { return false } // if the channel send panics, "return true" never gets run so it just
this.channel <- item // returns false after recovering
defer func() { recover() }()
channel <- item
return true return true
} }
// Receive returns a receive-only channel that can be used to receive items. // Receive returns a receive-only channel that can be used to receive items.
func (this *Gate[T]) Receive () <- chan T { func (this *Gate[T]) Receive () <- chan T {
this.lock.RLock() return this.load()
defer this.lock.RUnlock()
return this.channel
} }
// Close closes the gate, drains all remaining messages, and closes the channel. // Close closes the gate, unblocking any send or receive operations.
func (this *Gate[T]) Close () error { func (this *Gate[T]) Close () error {
this.lock.Lock() channel := this.channel.Swap((chan T)(nil)).(chan T)
if !this.open { return ErrAlreadyClosed } if channel == nil { return ErrAlreadyClosed }
this.open = false close(channel)
this.lock.Unlock()
for len(this.channel) > 0 { <- this.channel }
close(this.channel)
return nil return nil
} }
// Reset re-opens the gate if it is closed, and creates a new channel. // Reset re-opens the gate if it is closed, and creates a new channel.
func (this *Gate[T]) Reset () error { func (this *Gate[T]) Reset () error {
this.lock.Lock() this.channel.Store(make(chan T, this.bufferSize))
defer this.lock.Unlock()
this.open = true
if this.channel != nil { close(this.channel) }
this.channel = make(chan T, this.bufferSize)
return nil return nil
} }
// Open returns whether the gate is open. // Open returns whether the gate is open.
func (this *Gate[T]) Open () bool { func (this *Gate[T]) Open () bool {
this.lock.RLock() return this.load() != nil
defer this.lock.RUnlock()
return this.open
} }
// Len returns the amount of items in the channel. // Len returns the amount of items in the channel.
func (this *Gate[T]) Len () int { func (this *Gate[T]) Len () int {
return len(this.channel) return len(this.load())
} }
// Cap returns the amount of items the channel can hold. // Cap returns the amount of items the channel can hold.
func (this *Gate[T]) Cap () int { func (this *Gate[T]) Cap () int {
return cap(this.channel) return cap(this.load())
} }
func (this *Gate[T]) load() chan T {
return this.channel.Load().(chan T)
}

63
sync/gate_test.go Normal file
View File

@@ -0,0 +1,63 @@
package usync
import "time"
import "errors"
import "testing"
func TestGate(test *testing.T) {
gate := NewGate[int]()
go func() {
for number := range 21 {
test.Log("send", number)
gate.Send(number)
}
test.Log("send done")
}()
for correct := range 21 {
got := <- gate.Receive()
test.Log("RECV", correct, got)
if correct != got {
test.Fatal("RECV not equal")
}
}
test.Log("RECV done")
}
func TestGateCloseEarly(test *testing.T) {
gate := NewGate[int]()
sendDone := make(chan struct { })
go func() {
for number := range 21 {
test.Log("send", number)
gate.Send(number)
}
test.Log("send done")
close(sendDone)
}()
for correct := range 15 {
got := <- gate.Receive()
test.Log("RECV", correct, got)
if correct != got {
test.Fatal("RECV not equal")
}
}
test.Log("RECV done, closing gate... DOOR STUCK!! PLS I BEG OF YOU!!")
gate.Close()
test.Log("RECV closed gate yay :)))")
timeout := time.NewTimer(time.Second * 4)
select {
case <- sendDone:
case <- timeout.C:
test.Fatal("timed out waiting for sender goroutine to stop")
}
}
func TestGateCloseIdempotent(test *testing.T) {
gate := NewGate[int]()
err := gate.Close()
if err != nil { test.Fatal(err) }
err = gate.Close()
if !errors.Is(err, ErrAlreadyClosed) {
test.Fatal("wrong error: ", err)
}
}

View File

@@ -39,12 +39,12 @@ func (this *Monitor[T]) Borrow () (T, func ()) {
// updated value. The intended use of this function is like this: // updated value. The intended use of this function is like this:
// //
// value, done := monitor.BorrowReturn() // value, done := monitor.BorrowReturn()
// defer done(value) // defer done(&value)
func (this *Monitor[T]) BorrowReturn () (T, func (T)) { func (this *Monitor[T]) BorrowReturn () (T, func (*T)) {
this.mutex.Lock() this.mutex.Lock()
return this.value, func (value T) { return this.value, func (value *T) {
defer this.mutex.Unlock() defer this.mutex.Unlock()
this.value = value this.value = *value
} }
} }
@@ -86,12 +86,12 @@ func (this *RWMonitor[T]) Borrow () (T, func ()) {
// updated value. The intended use of this function is like this: // updated value. The intended use of this function is like this:
// //
// value, done := monitor.BorrowReturn() // value, done := monitor.BorrowReturn()
// defer done(value) // defer done(&value)
func (this *RWMonitor[T]) BorrowReturn () (T, func (T)) { func (this *RWMonitor[T]) BorrowReturn () (T, func (*T)) {
this.mutex.Lock() this.mutex.Lock()
return this.value, func (value T) { return this.value, func (value *T) {
defer this.mutex.Unlock() defer this.mutex.Unlock()
this.value = value this.value = *value
} }
} }

View File

@@ -13,8 +13,8 @@ func TestMonitor (test *testing.T) {
} () } ()
func () { func () {
value, done := mon.BorrowReturn() value, done := mon.BorrowReturn()
defer done(&value)
value += 3 value += 3
defer done(value)
} () } ()
func () { func () {
value, done := mon.Borrow() value, done := mon.Borrow()
@@ -56,8 +56,8 @@ func TestRWMonitor (test *testing.T) {
} () } ()
func () { func () {
value, done := mon.BorrowReturn() value, done := mon.BorrowReturn()
defer done(&value)
value += 3 value += 3
defer done(value)
} () } ()
func () { func () {
value, done := mon.RBorrow() value, done := mon.RBorrow()