Compare commits

...

10 Commits

8 changed files with 284 additions and 19 deletions

View File

@ -1,31 +1,31 @@
package ucontainer
// Optional is an optional value.
// Optional can either hold a value, or nothing.
type Optional[T any] struct {
value T
exists bool
}
// Value returns the value and true if the value exists. If not, it returns the
// last set value and false.
func (this *Optional[T]) Value () (T, bool) {
return this.value, this.exists
// O creates a new optional with the specified value.
func O[T any] (value T) Optional[T] {
return Optional[T] {
value: value,
exists: true,
}
}
// Set sets the value.
func (this *Optional[T]) Set (value T) {
this.value = value
this.exists = true
}
// Unset unsets the value.
func (this *Optional[T]) Unset () {
var zero T
this.value = zero
this.exists = false
// 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 (this *Optional[T]) Exists () bool {
return this.exists
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
}

View File

@ -3,6 +3,15 @@ package ucontainer
// Set is a set of unique items, built on top of map.
type Set[T comparable] map[T] struct { }
// NewSet creates a new set that contains all specified items.
func NewSet[T comparable] (items ...T) Set[T] {
set := make(Set[T])
for _, item := range items {
set.Add(item)
}
return set
}
// Empty returns true if there are no items in the set.
func (set Set[T]) Empty () bool {
return set == nil || len(set) == 0

2
go.mod
View File

@ -1,3 +1,3 @@
module git.tebibyte.media/sashakoshka/goutil
go 1.20.0
go 1.22.0

View File

@ -1,6 +1,23 @@
package ucolor
import "testing"
import "image/color"
func TestTransparent (test *testing.T) {
if Transparent(color.NRGBA { A: 255 }) {
test.Fatal("false positive")
}
if !Transparent(color.NRGBA { A: 0 }) {
test.Fatal("false negative")
}
}
func TestToRGBA (test *testing.T) {
rgba := ToRGBA(color.NRGBA { R: 123, G: 100, B: 23, A: 230 })
if rgba != (color.RGBA { R: 111, G: 90, B: 20, A: 230 }) {
test.Fatalf("wrong value: %v", rgba)
}
}
func TestPremultiply (test *testing.T) {
r, g, b, a := Premultiply(0xFFFF, 0xFFFF, 0xFFFF, 0x8888)

94
sync/gate.go Normal file
View File

@ -0,0 +1,94 @@
package usync
import "sync"
// Error defines errors that this package can produce
type Error string; const (
ErrAlreadyClosed Error = "AlreadyClosed"
)
// Error fullfills the error interface.
func (err Error) Error () string {
return string(err)
}
// Gate wraps a channel and allows the receiver to abruptly stop receiving
// messages without causing the sender to lock up.
type Gate[T any] struct {
channel chan T
lock sync.RWMutex
open bool
bufferSize int
}
// NewGate creates a new gate with no buffer.
func NewGate[T any] () Gate[T] {
return Gate[T] {
channel: make(chan T),
open: true,
}
}
// NewBufferedGate creates a new gate with a buffer.
func NewBufferedGate[T any] (buffer int) Gate[T] {
return Gate[T] {
channel: make(chan T, buffer),
open: true,
bufferSize: buffer,
}
}
// Send sends and item to the channel, returning whether the item was sent.
func (this *Gate[T]) Send (item T) bool {
this.lock.RLock()
defer this.lock.RUnlock()
if !this.open { return false }
this.channel <- item
return true
}
// Receive returns a receive-only channel that can be used to receive items.
func (this *Gate[T]) Receive () <- chan T {
this.lock.RLock()
defer this.lock.RUnlock()
return this.channel
}
// Close closes the gate, drains all remaining messages, and closes the channel.
func (this *Gate[T]) Close () error {
this.lock.Lock()
if !this.open { return ErrAlreadyClosed }
this.open = false
this.lock.Unlock()
for len(this.channel) > 0 { <- this.channel }
close(this.channel)
return nil
}
// Reset re-opens the gate if it is closed, and creates a new channel.
func (this *Gate[T]) Reset () error {
this.lock.Lock()
defer this.lock.Unlock()
this.open = true
if this.channel != nil { close(this.channel) }
this.channel = make(chan T, this.bufferSize)
return nil
}
// Open returns whether the gate is open.
func (this *Gate[T]) Open () bool {
this.lock.RLock()
defer this.lock.RUnlock()
return this.open
}
// Len returns the amount of items in the channel.
func (this *Gate[T]) Len () int {
return len(this.channel)
}
// Cap returns the amount of items the channel can hold.
func (this *Gate[T]) Cap () int {
return cap(this.channel)
}

36
sync/locker.go Normal file
View File

@ -0,0 +1,36 @@
package usync
import "sync"
// Locker guards access to a value
type Locker[T any] struct {
value T
mutex sync.Mutex
}
// NewLocker creates a new locker with the specified value.
func NewLocker[T any] (value T) Locker[T] {
return Locker[T] {
value: value,
}
}
// Set sets the value of the locker.
func (this *Locker[T]) Set (value T) {
this.mutex.Lock()
defer this.mutex.Unlock()
this.value = value
}
// Borrow borrows the value from the locker, and returns a function that must
// immediately be deferred, like this:
//
// value, done := locker.Borrow()
// defer done()
//
// From the time Borrow is called to the time the done function is called, it is
// safe to access the locked object from within the current goroutine.
func (this *Locker[T]) Borrow () (T, func ()) {
this.mutex.Lock()
return this.value, this.mutex.Unlock
}

85
sync/select.go Normal file
View File

@ -0,0 +1,85 @@
package usync
import "slices"
import "context"
import "reflect"
// ChannelRecv is a type constraint that includes all channel types that can be
// recieved from.
type ChannelRecv[T any] interface {
~chan T | ~<- chan T
}
// A type-safe wrapper around reflect.Select. Taken from:
// https://stackoverflow.com/questions/19992334
func Select[T any, C ChannelRecv[T]] (ctx context.Context, channels ...C) (int, T, bool) {
var zero T
// add all channels as select cases
cases := make([]reflect.SelectCase, len(channels) + 1)
for i, ch := range channels {
cases[i] = reflect.SelectCase {
Dir: reflect.SelectRecv,
Chan: reflect.ValueOf(ch),
}
}
// add ctx.Done() as another select case to stop listening when the
// context is closed
cases[len(channels)] = reflect.SelectCase {
Dir: reflect.SelectRecv,
Chan: reflect.ValueOf(ctx.Done()),
}
// read from the channel
chosen, value, ok := reflect.Select(cases)
if !ok {
if ctx.Err() != nil {
return -1, zero, false
}
return chosen, zero, false
}
// cast return value
if ret, ok := value.Interface().(T); ok {
return chosen, ret, true
}
return chosen, zero, false
}
// Combine returns a channel that continuously returns the result of the select
// until all input sources are exhauste, or the context is canceled.
func Combine[T any, C ChannelRecv[T]] (ctx context.Context, channels ...C) <- chan T {
channel := make(chan T)
// our silly slection routine
go func () {
for {
if len(channels) < 2 {
// only the context is left, stop everything
close(channel)
return
}
// read new value
chosen, value, ok := Select(ctx, channels...)
if ok {
// we have a value
channel <- value
} else {
// a channel has been closed and we need to do
// something about it
if chosen == len(channels) - 1 {
// the context has expired, stop
// everything
close(channel)
return
} else {
// a normal channel has closed, remove
// it from the list
channels = slices.Delete(channels, chosen, chosen + 1)
}
}
}
} ()
return channel
}

24
sync/select_test.go Normal file
View File

@ -0,0 +1,24 @@
package usync
import "time"
import "testing"
import "context"
func TestSelect (test *testing.T) {
// https://stackoverflow.com/questions/19992334
c1 := make(chan int)
c2 := make(chan int)
c3 := make(chan int)
chs := []chan int { c1, c2, c3 }
go func () {
time.Sleep(time.Second)
c2 <- 42
} ()
ctx, done := context.WithTimeout(context.Background(), 5 * time.Second)
defer done()
chosen, val, ok := Select(ctx, chs...)
if !ok { test.Fatal("not ok") }
if 1 != chosen { test.Fatal("expected 1, got", chosen) }
if 42 != val { test.Fatal("expected 42, got", val) }
}