github.com/ledgerwatch/erigon-lib@v1.0.0/common/bytes.go (about) 1 /* 2 Copyright 2021 The Erigon contributors 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 http://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 common 18 19 import ( 20 "fmt" 21 ) 22 23 func ByteCount(b uint64) string { 24 const unit = 1024 25 if b < unit { 26 return fmt.Sprintf("%dB", b) 27 } 28 bGb, exp := MBToGB(b) 29 return fmt.Sprintf("%.1f%cB", bGb, "KMGTPE"[exp]) 30 } 31 32 func MBToGB(b uint64) (float64, int) { 33 const unit = 1024 34 if b < unit { 35 return float64(b), 0 36 } 37 38 div, exp := uint64(unit), 0 39 for n := b / unit; n >= unit; n /= unit { 40 div *= unit 41 exp++ 42 } 43 44 return float64(b) / float64(div), exp 45 } 46 47 func Copy(b []byte) []byte { 48 if b == nil { 49 return nil 50 } 51 c := make([]byte, len(b)) 52 copy(c, b) 53 return c 54 } 55 56 func EnsureEnoughSize(in []byte, size int) []byte { 57 if cap(in) < size { 58 newBuf := make([]byte, size) 59 copy(newBuf, in) 60 return newBuf 61 } 62 return in[:size] // Reuse the space if it has enough capacity 63 } 64 65 func BitLenToByteLen(bitLen int) (byteLen int) { 66 return (bitLen + 7) / 8 67 }