27 Commits

Author SHA1 Message Date
c6f54927b0 sync: Add Locker type 2024-12-04 20:02:54 -05:00
0f9d8fb102 sync: Select, Combine work with more channel types 2024-12-04 20:00:19 -05:00
09aa19e7c1 sync: Add Select, Combine 2024-12-02 14:34:39 -05:00
9fd40a37b8 sync: Don't panic on double close of Gate, return error instead 2024-11-11 11:38:59 -05:00
709f41a974 sync: Add a Reset method to Gate which re-opens it. 2024-11-05 17:12:50 -05:00
f40eca261b Add sync package containing Gate 2024-10-31 17:46:28 -04:00
e5b35f3fcc Improvements to Optional type 2024-10-30 23:54:11 -04:00
e6a94c487e Add a variadic constructor for container.Set 2024-09-20 17:07:16 -04:00
0f903cc8ec Upgrade to go 1.22 2024-09-12 03:25:16 -04:00
19fcdb4a7d Test more things in color 2024-09-12 03:18:42 -04:00
6bfa97e6aa Fix color.Premultiply 2024-09-12 03:13:35 -04:00
f647b544e2 Add tests for some color functions 2024-09-12 03:13:15 -04:00
1911987c59 Downgrade to go1.20 2024-09-12 03:12:43 -04:00
ad5efe57d4 Change of to to 2024-09-10 18:12:04 -04:00
dfbb609ad6 Improve README 2024-09-10 18:11:11 -04:00
2964fb8f9f Add godoc badge to README 2024-09-10 18:09:37 -04:00
68d969419a Add package level doc comments 2024-09-10 18:03:32 -04:00
d274e91941 Add Cycler 2024-09-10 17:57:27 -04:00
9655da5841 HSV uses Premultiply and Unpremultiply functions 2024-09-10 17:42:45 -04:00
2b1f5d5c65 Remove fmt import 2024-09-10 17:39:27 -04:00
9dd35c1dff Add Premultiply and Unpremultiply functions 2024-09-10 17:39:06 -04:00
6e5e9faa72 Fix color package name 2024-09-10 17:15:00 -04:00
a899d12756 Add HSV, HSVA 2024-09-10 16:49:12 -04:00
1547391126 Add optional container 2024-09-10 16:47:20 -04:00
fc1af9f4a1 Memo marks itself as valid on update 2024-09-10 16:45:17 -04:00
baad6aa227 Memo.Invalidate zeros out the held value automatically
InvalidateTo is no longer needed
2024-09-10 16:45:17 -04:00
e94de08d4f Downgrade to go1.21.0 2024-06-26 11:55:46 -04:00
17 changed files with 543 additions and 9 deletions

View File

@@ -1,3 +1,7 @@
# goutil
Extension of the standard library.
[![Go Reference](https://pkg.go.dev/badge/git.tebibyte.media/sashakoshka/goutil.svg)](https://pkg.go.dev/git.tebibyte.media/sashakoshka/goutil)
Goutil provides extensions to the Go standard library. This repository mimics
its package/directory structure, prefixing all package names with 'u' to
differentiate them from their standard library counterparts.

2
container/doc.go Normal file
View File

@@ -0,0 +1,2 @@
// Package ucontainer extends container and implements generic container types.
package ucontainer

View File

@@ -20,6 +20,7 @@ func NewMemo[T any] (update func () T) Memo[T] {
func (this *Memo[T]) Value () T {
if !this.valid {
this.cache = this.update()
this.valid = true
}
return this.cache
}
@@ -27,13 +28,8 @@ func (this *Memo[T]) Value () T {
// Invalidate marks the Memo's value as invalid, which will cause it to be
// updated the next time Value is called.
func (this *Memo[T]) Invalidate () {
var zero T
this.cache = zero
this.valid = false
}
// InvalidateTo invalidates the Memo and sets its value. The new value will be
// entirely inaccessible. This is only intended to be used for setting a
// reference to nil
func (this *Memo[T]) InvalidateTo (value T) {
this.Invalidate()
this.cache = value
}

31
container/optional.go Normal file
View File

@@ -0,0 +1,31 @@
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
}

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.22.4
go 1.22.0

View File

@@ -18,3 +18,21 @@ func ToRGBA (c color.Color) color.RGBA {
uint8(a >> 8),
}
}
// Premultiply applies alpha-premultiplication that colors must apply as per
// color.Color.RGBA. This is an intrinsically lossy proccess.
func Premultiply (ur, ug, ub, ua uint32) (r, g, b, a uint32) {
return (ur * ua) / 0xFFFF,
(ug * ua) / 0xFFFF,
(ub * ua) / 0xFFFF,
ua
}
// Unpremultiply reverses alpha-premultiplication that colors must apply as per
// color.Color.RGBA. This may or may not return the precise original color.
func Unpremultiply (r, g, b, a uint32) (ur, ug, ub, ua uint32) {
return (r / a) * 0xFFFF,
(g / a) * 0xFFFF,
(b / a) * 0xFFFF,
a
}

34
image/color/color_test.go Normal file
View File

@@ -0,0 +1,34 @@
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)
if r != 0x8888 || g != 0x8888 || b != 0x8888 || a != 0x8888 {
test.Fatalf("wrong value: %08x %08x %08x %08x", r, g, b, a)
}
}
func TestUnpremultiply (test *testing.T) {
r, g, b, a := Unpremultiply(0x8888, 0x8888, 0x8888, 0x8888)
if r != 0xFFFF || g != 0xFFFF || b != 0xFFFF || a != 0x8888 {
test.Fatalf("wrong value: %08x %08x %08x %08x", r, g, b, a)
}
}

2
image/color/doc.go Normal file
View File

@@ -0,0 +1,2 @@
// Package ucolor extends image/color.
package ucolor

167
image/color/hsv.go Normal file
View File

@@ -0,0 +1,167 @@
package ucolor
import "image/color"
// HSV represents a color with hue, saturation, and value components. Each
// component C is in range 0 <= C <= 1.
type HSV struct {
H float64
S float64
V float64
}
// HSVA is an HSV color with an added 8-bit alpha component. The alpha component
// ranges from 0x0000 (fully transparent) to 0xFFFF (opaque), and has no bearing
// on the other components.
type HSVA struct {
H float64
S float64
V float64
A uint16
}
var (
HSVModel color.Model = color.ModelFunc(hsvModel)
HSVAModel color.Model = color.ModelFunc(hsvaModel)
)
func (hsv HSV) RGBA () (r, g, b, a uint32) {
// Adapted from:
// https://www.cs.rit.edu/~ncs/color/t_convert.html
component := func (x float64) uint32 {
return uint32(float64(0xFFFF) * x)
}
s := clamp01(hsv.S)
v := clamp01(hsv.V)
if s == 0 {
light := component(v)
return light, light, light, 0xFFFF
}
h := clamp01(hsv.H) * 360
sector := int(h / 60)
// otherwise when given 1.0 for H, sector would overflow to 6
if sector > 5 { sector = 5 }
offset := (h / 60) - float64(sector)
p := component(v * (1 - s))
q := component(v * (1 - s * offset))
t := component(v * (1 - s * (1 - offset)))
va := component(v)
switch sector {
case 0: return va, t, p, 0xFFFF
case 1: return q, va, p, 0xFFFF
case 2: return p, va, t, 0xFFFF
case 3: return p, q, va, 0xFFFF
case 4: return t, p, va, 0xFFFF
default: return va, p, q, 0xFFFF
}
}
func (hsva HSVA) RGBA () (r, g, b, a uint32) {
r, g, b, a = HSV {
H: hsva.H,
S: hsva.S,
V: hsva.V,
}.RGBA()
return Premultiply(r, g, b, uint32(hsva.A))
}
// Canon returns the color but with the H, S, and V fields are constrained to
// the range 0.0-1.0
func (hsv HSV) Canon () HSV {
hsv.H = clamp01(hsv.H)
hsv.S = clamp01(hsv.S)
hsv.V = clamp01(hsv.V)
return hsv
}
// Canon returns the color but with the H, S, and V fields are constrained to
// the range 0.0-1.0
func (hsva HSVA) Canon () HSVA {
hsva.H = clamp01(hsva.H)
hsva.S = clamp01(hsva.S)
hsva.V = clamp01(hsva.V)
return hsva
}
func clamp01 (x float64) float64 {
if x > 1.0 { return 1.0 }
if x < 0.0 { return 0.0 }
return x
}
func hsvModel (c color.Color) color.Color {
switch c := c.(type) {
case HSV: return c
case HSVA: return HSV { H: c.H, S: c.S, V: c.V }
default:
r, g, b, _ := Unpremultiply(c.RGBA())
return rgbToHSV(r, g, b)
}
}
func hsvaModel (c color.Color) color.Color {
switch c := c.(type) {
case HSV: return HSVA { H: c.H, S: c.S, V: c.V, A: 0xFFFF }
case HSVA: return c
default:
r, g, b, a := c.RGBA()
hsv := rgbToHSV(r, g, b)
return HSVA {
H: hsv.H,
S: hsv.S,
V: hsv.V,
A: uint16(a),
}
}
}
func rgbToHSV (r, g, b uint32) HSV {
// Adapted from:
// https://www.cs.rit.edu/~ncs/color/t_convert.html
component := func (x uint32) float64 {
return clamp01(float64(x) / 0xFFFF)
}
cr := component(r)
cg := component(g)
cb := component(b)
var maxComponent float64
if cr > maxComponent { maxComponent = cr }
if cg > maxComponent { maxComponent = cg }
if cb > maxComponent { maxComponent = cb }
var minComponent = 1.0
if cr < minComponent { minComponent = cr }
if cg < minComponent { minComponent = cg }
if cb < minComponent { minComponent = cb }
hsv := HSV {
V: maxComponent,
}
delta := maxComponent - minComponent
if delta == 0 {
// hsva.S is undefined, so hue doesn't matter
return hsv
}
hsv.S = delta / maxComponent
switch {
case cr == maxComponent: hsv.H = (cg - cb) / delta
case cg == maxComponent: hsv.H = 2 + (cb - cr) / delta
case cb == maxComponent: hsv.H = 4 + (cr - cg) / delta
}
hsv.H *= 60
if hsv.H < 0 { hsv.H += 360 }
hsv.H /= 360
return hsv
}

2
image/path/doc.go Normal file
View File

@@ -0,0 +1,2 @@
// Package upath implements operations on slices of image.Points.
package upath

28
io/cycler.go Normal file
View File

@@ -0,0 +1,28 @@
package uio
import "io"
// Cycler stores any io.Closer. When the value is replaced, the old value is
// closed.
type Cycler struct {
value io.Closer
}
// Value returns the value of the Cycler. If there is no value, nil is returned.
func (this *Cycler) Value () io.Closer {
return this.value
}
// Set replaces the value of the Cycler, closing the previous one if it exists.
func (this *Cycler) Set (value io.Closer) error {
err := this.value.Close()
this.value = value
return err
}
// Close closes the Cycler's value early. It will be set to nil.
func (this *Cycler) Close () error {
return this.Set(nil)
}

2
io/doc.go Normal file
View File

@@ -0,0 +1,2 @@
// Package uio extends io.
package uio

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) }
}