1 /*
2  * Hunt - A refined core library for D programming language.
3  *
4  * Copyright (C) 2018-2019 HuntLabs
5  *
6  * Website: https://www.huntlabs.net/
7  *
8  * Licensed under the Apache-2.0 License.
9  *
10  */
11 
12 module hunt.concurrency.atomic.AtomicHelper;
13 
14 import core.atomic;
15 
16 class AtomicHelper {
17     static void store(T)(ref T stuff, T newVal) {
18         core.atomic.atomicStore(*(cast(shared)&stuff), newVal);
19     }
20 
21     static T load(T)(ref T val) {
22         return core.atomic.atomicLoad(*(cast(shared)&val));
23     }
24 
25     static bool compareAndSet(T, V1, V2)(ref T stuff, V1 testVal, lazy V2 newVal) {
26         return core.atomic.cas(cast(shared)&stuff, cast(shared)testVal, cast(shared)newVal);
27     }
28 
29     static T increment(T, U)(ref T stuff, U delta = 1) if (__traits(isIntegral, T)) {
30         return core.atomic.atomicOp!("+=")(stuff, delta);
31     }
32 
33     static T decrement(T, U)(ref T stuff, U delta = 1) if (__traits(isIntegral, T)) {
34         return core.atomic.atomicOp!("-=")(stuff, delta);
35     }
36 
37     static T getAndAdd(T, U)(ref T stuff, U delta) {
38         T v = increment(stuff, delta);
39         return v - delta;
40     }
41 
42     static T getAndSet(T, U)(ref T stuff, U newValue) {
43         
44         //TODO: Tasks pending completion -@zxp at 12/16/2018, 11:15:45 AM
45         // exchange
46         // https://issues.dlang.org/show_bug.cgi?id=15007
47         T v = stuff;
48         store(stuff, newValue);
49         return v;
50     }
51 
52     static T getAndIncrement(T)(ref T stuff) {
53         return getAndAdd(stuff, 1);
54     }
55 
56     static T getAndDecrement(T)(ref T stuff) {
57         return getAndAdd(stuff, -1);
58     }
59 }
60