README.md raw

atomic

Type-safe atomic operations for Go primitive types. This package provides convenient wrappers around Go's sync/atomic package to ensure safe concurrent access to shared variables.

Features

Installation

go get next.orly.dev/pkg/utils/atomic

Usage

The atomic package provides type-safe wrappers around Go's standard sync/atomic operations:

Basic Operations

import "next.orly.dev/pkg/utils/atomic"

// Integer types
var counter atomic.Uint64
counter.Store(42)
value := counter.Load()  // 42
counter.Add(8)          // 50

// Boolean operations
var flag atomic.Bool
flag.Store(true)
if flag.Load() {
    // Handle true case
}

// Pointer operations
var ptr atomic.Pointer[string]
ptr.Store(&someString)
loadedPtr := ptr.Load()

Advanced Operations

// Compare and swap
var value atomic.Int64
value.Store(100)
swapped := value.CompareAndSwap(100, 200)  // true, value is now 200

// Swap operations
oldValue := value.Swap(300)  // oldValue = 200, new value = 300

// Atomic add/subtract
delta := value.Add(50)  // Add 50, return new value (350)
value.Sub(25)           // Subtract 25, value is now 325

Supported Types

TypeDescription
BoolAtomic boolean operations
Int3232-bit signed integer
Int6464-bit signed integer
Uint3232-bit unsigned integer
Uint6464-bit unsigned integer
UintptrPointer-sized unsigned integer
Float6464-bit floating point
Pointer[T]Generic pointer type

Generic Pointer Example

// Type-safe pointer operations
var config atomic.Pointer[Config]
config.Store(&myConfig)

// Load with type safety
currentConfig := config.Load()
if currentConfig != nil {
    // Use config with full type safety
}

API Reference

All atomic types implement a consistent interface:

Additional methods by type:

Integer Types (Int32, Int64, Uint32, Uint64):

Float64:

Testing

The atomic package includes comprehensive tests:

Running Tests

# Run atomic package tests
go test ./pkg/utils/atomic

# Run with verbose output
go test -v ./pkg/utils/atomic

# Run with race detection
go test -race ./pkg/utils/atomic

# Run with coverage
go test -cover ./pkg/utils/atomic

Integration Testing

Part of the full test suite:

# Run all tests including atomic
./scripts/test.sh

# Run specific package tests
go test ./pkg/utils/...

Test Coverage

Tests cover:

Performance

The atomic wrappers have zero runtime overhead compared to direct sync/atomic calls. The Go compiler inlines all wrapper methods, resulting in identical generated code.

Development

Building

go build ./pkg/utils/atomic

Code Quality

Examples

See the test files for comprehensive usage examples and edge cases.

License

Part of the next.orly.dev project. See main LICENSE file.