github.com/XiaoMi/Gaea@v1.2.5/util/util.go (about) 1 // Copyright 2019 The Gaea Authors. All Rights Reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package util 16 17 import ( 18 "fmt" 19 "strconv" 20 "sync/atomic" 21 "time" 22 ) 23 24 // BoolIndex rolled array switch mark 25 type BoolIndex struct { 26 index int32 27 } 28 29 // Set set index value 30 func (b *BoolIndex) Set(index bool) { 31 if index { 32 atomic.StoreInt32(&b.index, 1) 33 } else { 34 atomic.StoreInt32(&b.index, 0) 35 } 36 } 37 38 // Get return current, next, current bool value 39 func (b *BoolIndex) Get() (int32, int32, bool) { 40 index := atomic.LoadInt32(&b.index) 41 if index == 1 { 42 return 1, 0, true 43 } 44 return 0, 1, false 45 } 46 47 // ItoString interface to string 48 func ItoString(a interface{}) (bool, string) { 49 switch a.(type) { 50 case nil: 51 return false, "NULL" 52 case []byte: 53 return true, string(a.([]byte)) 54 default: 55 return false, fmt.Sprintf("%v", a) 56 } 57 } 58 59 // Int2TimeDuration convert int to Time.Duration 60 func Int2TimeDuration(t int) (time.Duration, error) { 61 tmp := strconv.Itoa(t) 62 tmp = tmp + "s" 63 idleTimeout, err := time.ParseDuration(tmp) 64 if err != nil { 65 return 0, err 66 67 } 68 return idleTimeout, nil 69 }