All files / src/impl AtomicReference.impl.ts

100% Statements 16/16
100% Branches 2/2
100% Functions 8/8
100% Lines 16/16

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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75                  25x 1230x               25x           4591x             1199x             1012x 1005x 1005x   7x               9x 9x 9x             4x       1230x       1230x     1230x        
import { OptionalType, RequiredType } from "@jonloucks/contracts-ts/api/Types";
import { AtomicReference } from "@jonloucks/contracts-ts/auxiliary/AtomicReference";
 
/**
 * Factory method to create an AtomicReference
 * 
 * @param initialValue the initial value for the AtomicReference
 * @returns the new AtomicReference implementation
 */
export function create<T>(initialValue?: OptionalType<T>): RequiredType<AtomicReference<T>> {
  return AtomicReferenceImpl.internalCreate(initialValue);
}
 
// ---- Implementation details below ----
 
/**
 * AtomicReference implementation.
 */
export class AtomicReferenceImpl<T> implements AtomicReference<T> {
 
  /**
   * AtomicReference.get override
   */
  get(): OptionalType<T> {
    return this.#value;
  }
 
  /** 
   * AtomicReference.set override
   */
  set(newValue: OptionalType<T>): void {
    this.#value = newValue;
  }
 
  /** 
   * AtomicReference.compareAndSet override
   */
  compareAndSet(expectedValue: OptionalType<T>, newValue: OptionalType<T>): boolean {
    if (this.#value === expectedValue) {
      this.#value = newValue;
      return true;
    } else {
      return false;
    }
  }
 
  /** 
   * AtomicReference.getAndSet override
   */
  getAndSet(newValue: OptionalType<T>): OptionalType<T> {
    const previousValue = this.#value;
    this.#value = newValue;
    return previousValue;
  }
 
  /** 
   * Object.toString override
   */
  toString(): string {
    return `Reference[${String(this.get())}]`;
  }
 
  static internalCreate<T>(initialValue?: OptionalType<T>): AtomicReference<T> {
    return new AtomicReferenceImpl<T>(initialValue);
  }
 
  private constructor(initialValue?: OptionalType<T>) {
    this.#value = initialValue;
  }
 
  #value: OptionalType<T>;
}