gitee.com/lh-her-team/common@v1.5.1/birdsnest/key.go (about) 1 // Package birdsnest key 2 package birdsnest 3 4 import ( 5 "encoding/hex" 6 "errors" 7 ) 8 9 var ( 10 // SeparatorString - 11 SeparatorString = "-" 12 // Separator herbt ca 13 Separator = byte(202) 14 // ErrKeyLengthCannotBeZero key length cannot be zero error 15 ErrKeyLengthCannotBeZero = errors.New("the key length cannot be 0") 16 // ErrNotTimestampKey not timestamp key error 17 ErrNotTimestampKey = errors.New("not timestamp txid") 18 // ErrTimestampKeyIsInvalid timestamp key is invalid 19 ErrTimestampKeyIsInvalid = errors.New("TxId nanosecond is invalid") 20 ) 21 22 // Key filter key 23 type Key interface { 24 // Parse the key 25 Parse() ([][]byte, error) 26 // Key bytes 27 Key() []byte 28 // Len The length of the key 29 Len() int 30 // String key to string 31 String() string 32 // GetNano get nanosecond 33 GetNano() int64 34 } 35 36 // TimestampKey Converting TxId directly using TimestampKey is not allowed, see ToTimestampKey 37 type TimestampKey []byte 38 39 // ToTimestampKey strings txid to timestamp key 40 func ToTimestampKey(txId string) (TimestampKey, error) { 41 b, err := hex.DecodeString(txId) 42 if err != nil { 43 return nil, err 44 } 45 if b[8] != Separator { 46 return nil, ErrNotTimestampKey 47 } 48 if bytes2nano(b[:8]) < 0 { 49 return nil, ErrTimestampKeyIsInvalid 50 } 51 key := TimestampKey(b) 52 return key, nil 53 } 54 55 // ToStrings TimestampKey to string 56 func ToStrings(keys []Key) []string { 57 result := make([]string, len(keys)) 58 for i := range keys { 59 result[i] = keys[i].String() 60 } 61 return result 62 } 63 64 // Len length 65 func (k TimestampKey) Len() int { 66 return len(k) 67 } 68 69 // Key to bytes 70 func (k TimestampKey) Key() []byte { 71 return k 72 } 73 74 func (k TimestampKey) String() string { 75 return hex.EncodeToString(k) 76 } 77 78 // GetNano get nanosecond 79 func (k TimestampKey) GetNano() int64 { 80 return bytes2nano(k[:8]) 81 } 82 83 // Parse parse 84 func (k TimestampKey) Parse() ([][]byte, error) { 85 if len(k) == 0 { 86 return nil, ErrKeyLengthCannotBeZero 87 } 88 if k[8] != Separator { 89 return nil, ErrNotTimestampKey 90 } 91 if k.GetNano() < 0 { 92 return nil, ErrTimestampKeyIsInvalid 93 } 94 return [][]byte{k[:8], k[8:32]}, nil 95 }