Categorygithub.com/rck/unit
modulepackage
0.0.3
Repository: https://github.com/rck/unit.git
Documentation: pkg.go.dev

# README

GO Report GoDoc

unit

Unit is a library to parse user defined units in go. It was written with sizes in mind, but everything where the numeric part can be converted to an int64 is possible.

It can be used standalone, but also implements the flag interfaces.

Installing

go get -u github.com/rck/unit

Next, include unit in your application:

import "github.com/rck/unit"

Example

package main

import (
	"flag"
	"fmt"
	"log"

	"github.com/rck/unit"
)

func main() {
	size := unit.MustNewUnit(unit.DefaultUnits).MustNewValue(1, unit.None)
	flag.Var(size, "s", "Parse a size")
	flag.Parse()
	fmt.Println(size.Value)

	myUnits := unit.DefaultUnits
	myUnits["kB"] = unit.DefaultUnits["KB"]

	u, err := unit.NewUnit(myUnits)
	if err != nil {
		log.Fatalf("Could not create unit based on mapping: %v\n", err)
	}
	if v, err := u.ValueFromString("+1024K"); err == nil {
		fmt.Println(v.Value, v)
		switch v.ExplicitSign {
		case unit.Positive:
			fmt.Println("Explicit positive sign")
		case unit.Negative:
			fmt.Println("Explicit negative sign")
		case unit.None:
			fmt.Println("No xxplicit sign")
		default:
			fmt.Println("This can not happen :-)")
		}
	}

	// if called with -s 20M, prints:
	// 20971520
	// 1048576 +1M
	// Explicit positive sign
}

LICENSE

This project is licensed under the same terms as u-root.

# Functions

MustNewUnit is like NewUnit but panics if the mapping 'm' is not valid.
NewUnit returns a new Unit given a mapping 'm'.

# Constants

E is 1024 P.
G is 1024 M.
K is 1024 byte.
M is 1024 K.
Negative signals that an explicit negative sign is set.
None signals that no explicit sign is set.
P is 1024 T.
Positive signals that an explicit positive sign is set.
T is 1024 G.

# Variables

DefaultUnits is the default unit mapping as used by many standard cli-tools.

# Structs

Unit is a map of unit names to conversion multipliers.
Value is any value that can be represented by a unit.

# Type aliases

Sign is the sign associated with a unit's value.