Saturating arithmetic for Crystal
The Saturating
generic type lets you impose saturating arithmetic on any
Number
type. This means that in any case when the wrapped type would overflow
or underflow, it instead clamps to the relevant boundary (the type's MAX
in
case of overflow or MIN
in case of underflow).
The code snippet below demonstrates this concept with an Int32:
n = Saturating(Int32).new(Int32::MAX - 2)
n += 20 # => 2147483647 (Int32::MAX)
m = Saturating(Int32).new(Int32::MIN + 3)
m -= 30 # => -2147483648 (Int32::MIN)
This shard currently uses an initial pure-Crystal approach. However, saturating arithmetic is implemented already in LLVM, which undergirds Crystal. I'd like to create bindings to these functions eventually, replacing the current implementation but keeping the same interface.
- Fork it (https://github.com/respitesage/saline/fork)
- 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
- Benjamin Wade - creator and maintainer