github.com/neatlab/neatio@v1.7.3-0.20220425043230-d903e92fcc75/utilities/common/math/integer_test.go (about)

     1  package math
     2  
     3  import (
     4  	"testing"
     5  )
     6  
     7  type operation byte
     8  
     9  const (
    10  	sub operation = iota
    11  	add
    12  	mul
    13  )
    14  
    15  func TestOverflow(t *testing.T) {
    16  	for i, test := range []struct {
    17  		x        uint64
    18  		y        uint64
    19  		overflow bool
    20  		op       operation
    21  	}{
    22  
    23  		{MaxUint64, 1, true, add},
    24  		{MaxUint64 - 1, 1, false, add},
    25  
    26  		{0, 1, true, sub},
    27  		{0, 0, false, sub},
    28  
    29  		{0, 0, false, mul},
    30  		{10, 10, false, mul},
    31  		{MaxUint64, 2, true, mul},
    32  		{MaxUint64, 1, false, mul},
    33  	} {
    34  		var overflows bool
    35  		switch test.op {
    36  		case sub:
    37  			_, overflows = SafeSub(test.x, test.y)
    38  		case add:
    39  			_, overflows = SafeAdd(test.x, test.y)
    40  		case mul:
    41  			_, overflows = SafeMul(test.x, test.y)
    42  		}
    43  
    44  		if test.overflow != overflows {
    45  			t.Errorf("%d failed. Expected test to be %v, got %v", i, test.overflow, overflows)
    46  		}
    47  	}
    48  }
    49  
    50  func TestHexOrDecimal64(t *testing.T) {
    51  	tests := []struct {
    52  		input string
    53  		num   uint64
    54  		ok    bool
    55  	}{
    56  		{"", 0, true},
    57  		{"0", 0, true},
    58  		{"0x0", 0, true},
    59  		{"12345678", 12345678, true},
    60  		{"0x12345678", 0x12345678, true},
    61  		{"0X12345678", 0x12345678, true},
    62  
    63  		{"0123456789", 123456789, true},
    64  		{"0x00", 0, true},
    65  		{"0x012345678abc", 0x12345678abc, true},
    66  
    67  		{"abcdef", 0, false},
    68  		{"0xgg", 0, false},
    69  
    70  		{"18446744073709551617", 0, false},
    71  	}
    72  	for _, test := range tests {
    73  		var num HexOrDecimal64
    74  		err := num.UnmarshalText([]byte(test.input))
    75  		if (err == nil) != test.ok {
    76  			t.Errorf("ParseUint64(%q) -> (err == nil) = %t, want %t", test.input, err == nil, test.ok)
    77  			continue
    78  		}
    79  		if err == nil && uint64(num) != test.num {
    80  			t.Errorf("ParseUint64(%q) -> %d, want %d", test.input, num, test.num)
    81  		}
    82  	}
    83  }
    84  
    85  func TestMustParseUint64(t *testing.T) {
    86  	if v := MustParseUint64("12345"); v != 12345 {
    87  		t.Errorf(`MustParseUint64("12345") = %d, want 12345`, v)
    88  	}
    89  }
    90  
    91  func TestMustParseUint64Panic(t *testing.T) {
    92  	defer func() {
    93  		if recover() == nil {
    94  			t.Error("MustParseBig should've panicked")
    95  		}
    96  	}()
    97  	MustParseUint64("ggg")
    98  }