All files / src/auxiliary AtomicReference.ts

100% Statements 3/3
100% Branches 0/0
100% Functions 1/1
100% Lines 3/3

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 541x                                                                                                   1x 19x    
import { OptionalType, RequiredType, guardFunctions } from "@jonloucks/contracts-ts/api/Types";
 
/**
 * @module auxiliary/AtomicReference
 * @description
 * 
 * AtomicReference is not truly atomic in this implementation due to JavaScript/TypeScript limitations.
 * However, it provides a thread-safe interface for reference operations using standard object equality.
 */
 
/**
 * Responsibility: An atomic reference interface for thread-safe reference operations.
 * Note: typescript limitations prevent full atomicity guarantees.
 */
export interface AtomicReference<T> {
 
    /**
     * Get the current reference value.
     */
    get(): OptionalType<T>;
 
    /**
     * Set the current reference value.
     * @param newValue the new reference value
     */
    set(newValue: OptionalType<T>): void
 
    /**
     * Atomically sets the value to the given updated value if the current value == the expected value.
     * @param expectedValue the expected current value
     * @param newValue the requested new value
     * @return true if successful. False return indicates that the actual value was not equal to the expected value.
     */
    compareAndSet(expectedValue: OptionalType<T>, newValue: OptionalType<T>): boolean;
 
    /**
     * Atomically sets to the given value and returns the previous value.
     * 
     * @param newValue the new value
     * @return the previous value
     */
    getAndSet(newValue: OptionalType<T>): OptionalType<T>;
}
 
/**
 * Type guard for AtomicReference interface.
 * 
 * @param instance the instance to check
 * @returns true if the instance implements AtomicReference
 */
export function guard<T>(instance: unknown): instance is RequiredType<AtomicReference<T>> {
    return guardFunctions(instance, "compareAndSet", "getAndSet", "get", "set");
}