cairo icon indicating copy to clipboard operation
cairo copied to clipboard

feat: u251 type

Open enitrat opened this issue 1 year ago • 4 comments

Feature Request

Describe the Feature Request When developing contracts for Starknet, deciding what data type to use is not always a straightforward process. Most application don't need to use 256 bits, so using u256 - which is composed by two felts - is sometimes overkill, and not optimized. However, the closest other integer type is u128, which might be too small. Using felt252 is not a great solution, as it lacks over/underflow checks, comparison operators, etc.

Describe Preferred Solution A u250 or u251 type which wraps a single felt252 and implements basic integer traits, like PartialEq, Div, Rem, Add, etc.

Describe Alternatives

Related Code

Additional Context

If the feature request is approved, would you be willing to submit a PR? (Help can be provided if you need assistance submitting a PR)

  • [ ] Yes
  • [ ] No

enitrat avatar Jul 30 '23 10:07 enitrat

can you please add a standard use case where u128 is actually not large enough - while u250 would have been? (do note that multiplications and so would be very problematic with such a type).

Also note - that if you are sure your number is not too large - you can do all your operations in u256 - and than convert it to felt252 for storage and message passing.

orizi avatar Jul 31 '23 07:07 orizi

Is the computation overhead of using u256 (composed of two felts) small enough to consider it meaningless, if it doesn't have to be stored onchain?

If yes, then indeed I could just convert it to a felt252 before storing the data onchain. Thanks

enitrat avatar Jul 31 '23 08:07 enitrat

i'm mostly saying this as - let us start with a workable solution - and consider optimisations only later if we understand they are required.

orizi avatar Jul 31 '23 08:07 orizi

From my experience:

  • u128 has almost always been large enough for computation
  • u256 operations are, not surprisingly, MUCH less performant than u128 / u64
  • the primary point at which the lack of a u250-ish type is problematic is when bitpacking to take advantage of as much of a storage felt252 as possible (i.e. doing a lot of bit shifts with u256 is extremely inefficient)

clexmond avatar Aug 04 '23 13:08 clexmond