Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add feature to convert bytesizes #7

Merged
merged 5 commits into from
May 14, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
172 changes: 172 additions & 0 deletions convert/bytesize.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
package convert

import (
"fmt"
"math"
"regexp"
"strconv"
"strings"
)

type Bytesize struct {
Data int
Unit string
}
type Unit struct {
symbol string
name string
base int
exponential int
}

var ByteUnits = []Unit{
// https://en.wikipedia.org/wiki/Byte#Unit_symbol

// SI + Byte
{"B", "Byte", 1, 1},
{"kB", "Kilobyte", 10, 3},
{"MB", "Megabyte", 10, 6},
{"GB", "Gigabyte", 10, 9},
{"TB", "Terabyte", 10, 12},
{"PB", "Petabyte", 10, 15},
{"EB", "Exabyte", 10, 18},
{"ZB", "Zettabyte", 10, 21},
{"YB", "Yottabyte", 10, 24},

// IEC
{"KiB", "Kibibyte", 2, 10},
{"MiB", "Mebibyte", 2, 20},
{"GiB", "Gibibyte", 2, 30},
{"TiB", "Tebibyte", 2, 40},
{"PiB", "Pebibyte", 2, 50},
{"EiB", "Exbibyte", 2, 60},
{"ZiB", "Zebibyte", 2, 70},
{"YiB", "Yobibyte", 2, 80},
}

var ByteUnitMap map[string]Unit

func init() {
// build ByteUnitMap
ByteUnitMap = map[string]Unit{}
for _, unit := range ByteUnits {
ByteUnitMap[unit.symbol] = unit
}
}

func (b *Bytesize) String() string {
return b.ToHumanReadable()
}

func (b *Bytesize) Dump() {
fmt.Println("Data: ", b.Data)
fmt.Println("Unit: ", b.Unit)
}

func (b *Bytesize) cleanUnits(input string) string {
// cleanup based on UnitMap
for key, value := range ByteUnitMap {
if strings.EqualFold(key, input) || strings.EqualFold(value.symbol, input) || strings.EqualFold(value.name, input) {
input = value.symbol
}
}

return input
}

func ParseBytes(data interface{}) (error, *Bytesize) {
b := &Bytesize{}

// given data is int; set it directly
if s, ok := data.(int); ok {
b.Data = s
b.Unit = "B"
} else if s, ok := data.(string); ok { // given data is string; we have to correct
i, err := strconv.Atoi(s)
if err == nil {
b.Data = i
b.Unit = "B"
} else {
re := regexp.MustCompile(`^(\d+)\s*(\w+)$`)
found := re.FindStringSubmatch(s)
if len(found) == 0 {
return fmt.Errorf("could not parse input into number and optional unit"), nil
}
b.Data, _ = strconv.Atoi(found[1])
b.Unit = b.cleanUnits(found[2])
}
}

return nil, b
}

func (b *Bytesize) calc(targetUnit string) float64 {
// clean units
b.Unit = b.cleanUnits(b.Unit)

// convert given values to bytes
// example: 1000 MB -> Bytes
// c := 1000 * match.Pow(10, 6)
// Result: 1.000.000.000
c := float64(b.Data) * math.Pow(
float64(ByteUnitMap[b.Unit].base),
float64(ByteUnitMap[b.Unit].exponential),
)

// calculate from bytes to target unit
// example: Bytes -> Gigabytes
// x := 1.000.000.000 / (match.Pow(10, 9))
// Result: 1
x := c / (math.Pow(
float64(ByteUnitMap[targetUnit].base),
float64(ByteUnitMap[targetUnit].exponential),
))

return x
}

func (b *Bytesize) ToKilobyte() float64 { return b.calc("kB") }
func (b *Bytesize) ToMegabyte() float64 { return b.calc("MB") }
func (b *Bytesize) ToGigabyte() float64 { return b.calc("GB") }
func (b *Bytesize) ToTerabyte() float64 { return b.calc("TB") }
func (b *Bytesize) ToPetabyte() float64 { return b.calc("PB") }
func (b *Bytesize) ToExabyte() float64 { return b.calc("EB") }
func (b *Bytesize) ToZettabyte() float64 { return b.calc("ZB") }
func (b *Bytesize) ToYottabyte() float64 { return b.calc("YB") }

func (b *Bytesize) ToKibibyte() float64 { return b.calc("KiB") }
func (b *Bytesize) ToMebibyte() float64 { return b.calc("MiB") }
func (b *Bytesize) ToGibibyte() float64 { return b.calc("GiB") }
func (b *Bytesize) ToTebibyte() float64 { return b.calc("TiB") }
func (b *Bytesize) ToPebibyte() float64 { return b.calc("PiB") }
func (b *Bytesize) ToExbibyte() float64 { return b.calc("EiB") }
func (b *Bytesize) ToZebibyte() float64 { return b.calc("ZiB") }
func (b *Bytesize) ToYobibyte() float64 { return b.calc("YiB") }

func (b *Bytesize) ToHumanReadable() string {
// clean units
b.Unit = b.cleanUnits(b.Unit)

// convert given values to bytes
c := float64(b.Data) * math.Pow(
float64(ByteUnitMap[b.Unit].base),
float64(ByteUnitMap[b.Unit].exponential),
)

// calc logarithm
log10 := math.Log10(c)
log10tolerant := log10 - 2

// search ByteUnitMap for the right exponential
var newUnit = b.Unit
// TODO: limit to SI units?
for key, value := range ByteUnitMap {
if float64(value.exponential) <= log10 && float64(value.exponential) >= log10tolerant {
newUnit = key
break
}
}

// re-calculate
return fmt.Sprintf("%g %s", b.calc(newUnit), newUnit)
}
67 changes: 67 additions & 0 deletions convert/bytesize_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package convert

import (
"fmt"
"github.com/stretchr/testify/assert"
"testing"
)

func ExampleParseBytes() {
err, b := ParseBytes("100MB")
if err != nil {
panic(err)
}

fmt.Println(b)
fmt.Println(b.ToHumanReadable())
fmt.Println(b.ToKilobyte())
fmt.Println(b.ToGigabyte())
// Output: 100 MB
// 100 MB
// 100000
// 0.1
}

func TestParseBytes(t *testing.T) {
var b *Bytesize
var err error

err, b = ParseBytes(1)
assert.NoError(t, err)
assert.Equal(t, 1, b.Data)
assert.Equal(t, "B", b.Unit)

err, b = ParseBytes("1")
assert.NoError(t, err)
assert.Equal(t, 1, b.Data)
assert.Equal(t, "B", b.Unit)

err, b = ParseBytes("1mb")
assert.NoError(t, err)
assert.Equal(t, 1, b.Data)
assert.Equal(t, "MB", b.Unit)

// t.Skip("missing error handling")
err, b = ParseBytes("foobar")
assert.Error(t, err)
}

func TestBytesize_String(t *testing.T) {
err, b := ParseBytes("100mb")
assert.NoError(t, err)
assert.Equal(t, "100 MB", b.String())

err, b = ParseBytes("100mb")
assert.NoError(t, err)
assert.Equal(t, "100 MB", fmt.Sprint(b))
}

func TestBytesize_ToHumanReadable(t *testing.T) {
err, b := ParseBytes("900MB")
assert.NoError(t, err)
assert.Equal(t, "900 MB", b.ToHumanReadable())

err, b = ParseBytes("1000mb")
assert.NoError(t, err)
assert.Equal(t, "1 GB", b.ToHumanReadable())
}