diff --git a/xcontext/mutex.go b/xcontext/mutex.go new file mode 100644 index 0000000..e1dc1ba --- /dev/null +++ b/xcontext/mutex.go @@ -0,0 +1,37 @@ +package xcontext + +type Mutex struct { + ch chan struct{} +} + +func NewMutex() *Mutex { + return &Mutex{ + ch: make(chan struct{}, 1), + } +} + +func (m *Mutex) TryLock() bool { + select { + case m.ch <- struct{}{}: + return true + default: + return false + } +} + +func (m *Mutex) Lock(ctx context.Context) error { + select { + case <-ctx.Done(): + return fmt.Errorf("failed to acquire lock: %w", ctx.Err()) + case m.ch <- struct{}{}: + return nil + } +} + +func (m *Mutex) Unlock() { + select { + case <-m.ch: + default: + panic("xcontext.Mutex: Unlock before Lock") + } +} diff --git a/xsync/xsync.go b/xsync/xsync.go deleted file mode 100644 index 7bb88b0..0000000 --- a/xsync/xsync.go +++ /dev/null @@ -1,37 +0,0 @@ -package xsync - -type ContextMutex struct { - ch chan struct{} -} - -func NewContextMutex() *ContextMutex { - return &ContextMutex{ - ch: make(chan struct{}, 1), - } -} - -func (cm *ContextMutex) TryLock() bool { - select { - case cm.ch <- struct{}{}: - return true - default: - return false - } -} - -func (cm *ContextMutex) Lock(ctx context.Context) error { - select { - case <-ctx.Done(): - return fmt.Errorf("failed to acquire lock: %w", ctx.Err()) - case cm.ch <- struct{}{}: - return nil - } -} - -func (cm *ContextMutex) Unlock() { - select { - case <-cm.ch: - default: - panic("xsync.ContextMutex: Unlock before Lock") - } -}