4 Commits

Author SHA1 Message Date
58052e8679 sync: Add RWLocker from previous repo 2024-12-18 08:53:55 -07:00
1a13d59a05 sync: Add package-level doc comment 2024-12-14 23:58:31 -05:00
7141c6cef4 Migrate go.mod 2024-12-14 23:54:16 -05:00
a6348ad530 Update README.md 2024-12-14 23:06:25 -05:00
4 changed files with 49 additions and 6 deletions

View File

@@ -1,7 +1,7 @@
# goutil
# go-util
[![Go Reference](https://pkg.go.dev/badge/git.tebibyte.media/sashakoshka/goutil.svg)](https://pkg.go.dev/git.tebibyte.media/sashakoshka/goutil)
[![Go Reference](https://pkg.go.dev/badge/git.tebibyte.media/sashakoshka/go-util.svg)](https://pkg.go.dev/git.tebibyte.media/sashakoshka/go-util)
Goutil provides extensions to the Go standard library. This repository mimics
its package/directory structure, prefixing all package names with 'u' to
Util 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
go.mod
View File

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

2
sync/doc.go Normal file
View File

@@ -0,0 +1,2 @@
// Package usync extends sync.
package usync

View File

@@ -2,7 +2,7 @@ package usync
import "sync"
// Locker guards access to a value
// Locker guards access to a value. It must not be copied after first use.
type Locker[T any] struct {
value T
mutex sync.Mutex
@@ -34,3 +34,44 @@ func (this *Locker[T]) Borrow () (T, func ()) {
this.mutex.Lock()
return this.value, this.mutex.Unlock
}
// RWLocker guards separate read/write access to a value.
type RWLocker[T any] struct {
value T
mutex sync.RWMutex
}
// NewRWLocker creates a new locker with the specified value. It must not be
// copied after first use.
func NewRWLocker[T any] (value T) RWLocker[T] {
return RWLocker[T] {
value: value,
}
}
// Set sets the value of the locker.
func (this *RWLocker[T]) Set (value T) {
this.mutex.Lock()
defer this.mutex.Unlock()
this.value = value
}
// Borrow borrows the value from the locker for write access, 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 *RWLocker[T]) Borrow () (T, func ()) {
this.mutex.Lock()
return this.value, this.mutex.Unlock
}
// RBorrow is like Borrow, but returns the item for read access only. Do not
// under any circumstances write to an item returned from this method.
func (this *RWLocker[T]) RBorrow () (T, func ()) {
this.mutex.Lock()
return this.value, this.mutex.Unlock
}