github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/datasize/bitsize.go (about) 1 /* 2 * Copyright (C) 2017 The "MysteriumNetwork/node" Authors. 3 * 4 * This program is free software: you can redistribute it and/or modify 5 * it under the terms of the GNU General Public License as published by 6 * the Free Software Foundation, either version 3 of the License, or 7 * (at your option) any later version. 8 * 9 * This program is distributed in the hope that it will be useful, 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 * GNU General Public License for more details. 13 * 14 * You should have received a copy of the GNU General Public License 15 * along with this program. If not, see <http://www.gnu.org/licenses/>. 16 */ 17 18 package datasize 19 20 import ( 21 "fmt" 22 ) 23 24 // BitSize represents data size in various units. 25 type BitSize float64 26 27 const ( 28 // Bit represents 1 bit. 29 Bit BitSize = 1 30 // B is short for Byte. 31 B = 8 * Bit 32 // KiB is short for Kibibyte. 33 KiB = 1024 * B 34 // MiB is short for Mebibyte. 35 MiB = 1024 * KiB 36 // GiB is short for Gibibyte. 37 GiB = 1024 * MiB 38 // TiB is short for Tebibyte. 39 TiB = 1024 * GiB 40 // PiB is short for Pebibyte. 41 PiB = 1024 * TiB 42 // EiB is short for Exbibyte. 43 EiB = 1024 * PiB 44 ) 45 46 var units = []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"} 47 48 // FromBytes creates BitSize from bytes value. 49 func FromBytes(bytes uint64) BitSize { 50 return BitSize(bytes * B.Bits()) 51 } 52 53 // Bits returns size in bits. 54 func (size BitSize) Bits() uint64 { 55 return uint64(size) 56 } 57 58 // Bytes returns size in bytes. 59 func (size BitSize) Bytes() uint64 { 60 return uint64(float64(size) / float64(B.Bits())) 61 } 62 63 // String returns a human readable representation of bytes. 64 func (size BitSize) String() string { 65 if size < B { 66 // No fraction on bits 67 return fmt.Sprintf("%d%s", uint64(size), "b") 68 } 69 if size < KiB { 70 // No fraction on bytes 71 return fmt.Sprintf("%d%s", size.Bytes(), "B") 72 } 73 val := float64(size.Bytes()) 74 i := 0 75 maxUnit := len(units) - 1 76 for val >= 1024 && i < maxUnit { 77 val = val / 1024 78 i++ 79 } 80 return fmt.Sprintf("%.1f%s", val, units[i]) 81 }