[Experiment] Wrap integer into SafeBox(T)
to prevent/raise on overflow. Inspired by this gist.
Note: Do not use in production! You have been warned.
Add this to your application's shard.yml
:
dependencies:
overflow:
github: petoem/overflow.cr
This shard links against libclang_rt.builtins-*.a
which is part of compiler-rt
. It is needed to fix this error related to Int128
multiplication.
You will have to install clang
because it is used to discover the location of the compiler runtime library. Above file is provided by package compiler-rt on ArchLinux and libclang-common on Debian (both dependencies of clang
package). Hence, installing clang
should be enough.
overflow.cr
shard provides SafeBox(T)
, which helps you prevent integer overflow.
Operations like +, -, *
on an integer stored inside SafeBox(T)
are done using LLVM Intrinsics and SafeBox(T)#to_*
methods are checked for overflow too.
All other method calls are forwarded to the integer value
stored inside using forward_missing_to
macro.
require "overflow"
# Short example
struct Color
getter r : SafeBox(UInt8)
getter g : SafeBox(UInt8)
getter b : SafeBox(UInt8)
def initialize(@r, @g ,@b); end
end
# Create cyan color
cyan = Color.new 0_u8.to_sb, 255_u8.to_sb, 255_u8.to_sb
# Lets look what it stores ...
pp cyan # => Color(
# @b=SafeBox(UInt8)(@type=UInt8, @value=255_u8),
# @g=SafeBox(UInt8)(@type=UInt8, @value=255_u8),
# @r=SafeBox(UInt8)(@type=UInt8, @value=0_u8))
# and now make it a bit more blue.
blue = cyan.b + 20 # SafeBox(UInt8) uadd Int32 (IntegerOverflow)
# Oops ... to much blue.
That's it for now.
- In a computation e.g.
a + b
, the right operand type is always extended or trimmed to the left operand type.
- Fork it
- Create your feature branch (git checkout -b my-new-feature)
- Commit your changes (git commit -am 'Add some feature')
- Push to the branch (git push origin my-new-feature)
- Create a new Pull Request
- petoem Michael Petö - creator, maintainer