Add generic atomic value
This commit is contained in:
		
							parent
							
								
									c4e2a0f641
								
							
						
					
					
						commit
						afcc57aa70
					
				
							
								
								
									
										38
									
								
								sync/atomic/generic.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										38
									
								
								sync/atomic/generic.go
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,38 @@ | ||||
| package uatomic | ||||
| 
 | ||||
| import "sync/atomic" | ||||
| 
 | ||||
| // Atom is a generic wrapper for atomic.Value. | ||||
| type Atom[T comparable] struct { | ||||
| 	value atomic.Value | ||||
| } | ||||
| 
 | ||||
| type atomWrapper[T comparable] struct { value T } | ||||
| 
 | ||||
| // CompareAndSwap executes the compare-and-swap operation for the Atom. | ||||
| func (atom *Atom[T]) CompareAndSwap(old, neww T) (swapped bool) { | ||||
| 	return atom.value.CompareAndSwap( | ||||
| 		atomWrapper[T] { value: old }, | ||||
| 		atomWrapper[T] { value: neww }) | ||||
| } | ||||
| 
 | ||||
| func (atom *Atom[T]) Load() T { | ||||
| 	return castSafe[T](atom.value.Load) | ||||
| } | ||||
| 
 | ||||
| func (atom *Atom[T]) Store(val T) { | ||||
| 	atom.value.Store(val) | ||||
| } | ||||
| 
 | ||||
| func (atom *Atom[T]) Swap(neww T) T { | ||||
| 	return castSafe[T](atom.value.Swap(neww)) | ||||
| } | ||||
| 
 | ||||
| func castSafe[T comparable](value any) T { | ||||
| 	var zero T | ||||
| 	if value == nil { | ||||
| 		return zero | ||||
| 	} else { | ||||
| 		return value.(T) | ||||
| 	} | ||||
| } | ||||
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user