gitee.com/go-spring2/spring-base@v1.1.3/atomic/duration.go (about) 1 /* 2 * Copyright 2012-2019 the original author or authors. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * https://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package atomic 18 19 import ( 20 "sync/atomic" 21 "time" 22 23 "gitee.com/go-spring2/spring-base/json" 24 ) 25 26 // A Duration is an atomic time.Duration value. 27 type Duration struct { 28 _ nocopy 29 _ align64 30 v int64 31 } 32 33 // Add atomically adds delta to x and returns the new value. 34 func (x *Duration) Add(delta time.Duration) time.Duration { 35 return time.Duration(atomic.AddInt64(&x.v, int64(delta))) 36 } 37 38 // Load atomically loads and returns the value stored in x. 39 func (x *Duration) Load() time.Duration { 40 return time.Duration(atomic.LoadInt64(&x.v)) 41 } 42 43 // Store atomically stores val into x. 44 func (x *Duration) Store(val time.Duration) { 45 atomic.StoreInt64(&x.v, int64(val)) 46 } 47 48 // Swap atomically stores new into x and returns the old value. 49 func (x *Duration) Swap(new time.Duration) time.Duration { 50 return time.Duration(atomic.SwapInt64(&x.v, int64(new))) 51 } 52 53 // CompareAndSwap executes the compare-and-swap operation for x. 54 func (x *Duration) CompareAndSwap(old, new time.Duration) bool { 55 return atomic.CompareAndSwapInt64(&x.v, int64(old), int64(new)) 56 } 57 58 // MarshalJSON returns the JSON encoding of x. 59 func (x *Duration) MarshalJSON() ([]byte, error) { 60 return json.Marshal(x.Load()) 61 }