Created
December 4, 2014 09:26
-
-
Save arnehormann/7eb5e16748af08680ca3 to your computer and use it in GitHub Desktop.
Support code for tests in confactor/envflags
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io" | |
"math/big" | |
"os" | |
) | |
func generateIntBounds(w io.Writer) { | |
// set variables to upper bound | |
var ( | |
b byte = ^byte(0) | |
u uint = ^uint(0) | |
u8 uint8 = ^uint8(0) | |
u16 uint16 = ^uint16(0) | |
u32 uint32 = ^uint32(0) | |
u64 uint64 = ^uint64(0) | |
i int = int(u >> 1) | |
i8 int8 = int8(u8 >> 1) | |
i16 int16 = int16(u16 >> 1) | |
i32 int32 = int32(u32 >> 1) | |
i64 int64 = int64(u64 >> 1) | |
) | |
fmt.Fprintf(w, "tests := map[string]struct{lowin, highin, lwout, highout string}{\n") | |
for _, ptr := range []interface{}{ | |
&b, | |
&u, &u8, &u16, &u32, &u64, | |
&i, &i8, &i16, &i32, &i64, | |
} { | |
v, err := ValueOf(ptr) | |
if err != nil { | |
panic(err) | |
} | |
max := v.String() | |
signed := v.Set("-"+max) == nil | |
lo, li, hi, ho, ok := getIntBounds(max, signed) | |
if !ok { | |
panic("could not convert bounds") | |
} | |
fmt.Fprintf(w, "{&%T, %q, %q, %q, %q},\n", ptr, li, hi, lo, ho) | |
} | |
fmt.Fprintf(w, "}\n") | |
} | |
func getIntBounds(max string, signed bool) (lowout, lowin, highin, highout string, ok bool) { | |
// use math/big to also generate outer bounds of int64 / uint64 | |
m1 := big.NewInt(-1) | |
p1 := big.NewInt(1) | |
tmp := big.NewInt(0) | |
highin = max | |
lowin = "0" | |
if signed { | |
tmp, ok = tmp.SetString("-"+highin, 10) | |
if !ok { | |
return | |
} | |
tmp = tmp.Add(tmp, m1) | |
lowin = tmp.String() | |
} | |
lowout = tmp.Add(tmp, m1).String() | |
tmp, ok = tmp.SetString(highin, 10) | |
if !ok { | |
return | |
} | |
highout = tmp.Add(tmp, p1).String() | |
return | |
} | |
func main() { | |
generateIntBounds(os.Stdout) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment