| ... | @@ -515,15 +515,28 @@ test "math.negateCast" { | ... | @@ -515,15 +515,28 @@ test "math.negateCast" { |
| 515 | | 515 | |
| 516 | /// Cast an integer to a different integer type. If the value doesn't fit, | 516 | /// Cast an integer to a different integer type. If the value doesn't fit, |
| 517 | /// return an error. | 517 | /// return an error. |
| 518 | pub fn cast(comptime T: type, x: var) !T { | 518 | pub fn cast(comptime T: type, x: var) (error{Overflow}!T) { |
| 519 | comptime assert(@typeId(T) == builtin.TypeId.Int); // must pass an integer | 519 | comptime assert(@typeId(T) == builtin.TypeId.Int); // must pass an integer |
| 520 | if (x > @maxValue(T)) { | 520 | comptime assert(@typeId(@typeOf(x)) == builtin.TypeId.Int); // must pass an integer |
| | 521 | if (@maxValue(@typeOf(x)) > @maxValue(T) and x > @maxValue(T)) { |
| | 522 | return error.Overflow; |
| | 523 | } else if (@minValue(@typeOf(x)) < @minValue(T) and x < @minValue(T)) { |
| 521 | return error.Overflow; | 524 | return error.Overflow; |
| 522 | } else { | 525 | } else { |
| 523 | return T(x); | 526 | return T(x); |
| 524 | } | 527 | } |
| 525 | } | 528 | } |
| 526 | | 529 | |
| | 530 | test "math.cast" { |
| | 531 | if (cast(u8, u32(300))) |_| @panic("fail") else |err| assert(err == error.Overflow); |
| | 532 | if (cast(i8, i32(-200))) |_| @panic("fail") else |err| assert(err == error.Overflow); |
| | 533 | if (cast(u8, i8(-1))) |_| @panic("fail") else |err| assert(err == error.Overflow); |
| | 534 | if (cast(u64, i8(-1))) |_| @panic("fail") else |err| assert(err == error.Overflow); |
| | 535 | |
| | 536 | assert((try cast(u8, u32(255))) == u8(255)); |
| | 537 | assert(@typeOf(try cast(u8, u32(255))) == u8); |
| | 538 | } |
| | 539 | |
| 527 | pub fn floorPowerOfTwo(comptime T: type, value: T) T { | 540 | pub fn floorPowerOfTwo(comptime T: type, value: T) T { |
| 528 | var x = value; | 541 | var x = value; |
| 529 | | 542 | |