github.com/haraldrudell/parl@v0.4.176/ints/unsigned_test.go (about) 1 /* 2 © 2022–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/) 3 ISC License 4 */ 5 6 // Package ints provide manipulation of integer types. 7 package ints 8 9 import ( 10 "errors" 11 "math" 12 "testing" 13 14 "github.com/haraldrudell/parl/perrors" 15 ) 16 17 func TestUnsigned(t *testing.T) { 18 var u8max, i8min, i8max = uint8(math.MaxUint8), int8(math.MinInt8), int8(math.MaxInt8) 19 var u64one, u64max = uint64(1), uint64(math.MaxUint64) 20 21 var u64 uint64 22 var u8, u8zeroValue uint8 23 var err error 24 25 // uint8 should fit uint64 26 u64, err = Unsigned[uint64](u8max, "") 27 if err != nil { 28 t.Errorf("uint8 err: %s", perrors.Short(err)) 29 } 30 if u64 != uint64(u8max) { 31 t.Errorf("uint8 %d exp %d", u64, uint64(u8max)) 32 } 33 34 // small uint64 should fit uint8 35 u8, err = Unsigned[uint8](u64one, "") 36 if err != nil { 37 t.Errorf("small err: %s", perrors.Short(err)) 38 } 39 if u8 != uint8(u64one) { 40 t.Errorf("small %d exp %d", u8, uint8(u64one)) 41 } 42 43 // positive int8 should fit uint8 44 u8, err = Unsigned[uint8](i8max, "") 45 if err != nil { 46 t.Errorf("i8max err: %s", perrors.Short(err)) 47 } 48 if u8 != uint8(i8max) { 49 t.Errorf("i8max %d exp %d", u8, uint8(i8max)) 50 } 51 52 // negative value should error 53 u8, err = Unsigned[uint8](i8min, "") 54 if err == nil { 55 t.Error("negative missing error") 56 } else if !errors.Is(err, ErrNegative) { 57 t.Errorf("negative error not ErrNegative: %s", perrors.Short(err)) 58 } 59 if u8 != u8zeroValue { 60 t.Errorf("negative %d exp %d", u8, u8zeroValue) 61 } 62 63 // too large value should error 64 u8, err = Unsigned[uint8](u64max, "") 65 if err == nil { 66 t.Error("large missing error") 67 } else if !errors.Is(err, ErrTooLarge) { 68 t.Errorf("large error not ErrTooLarge: %s", perrors.Short(err)) 69 } 70 if u8 != u8zeroValue { 71 t.Errorf("large %d exp %d", u8, u8zeroValue) 72 } 73 }