Using isize vs usize


#1

This is a followsup to I32 vs isize, u32 vs usize .

The discuss there was very helpful, as my code no longer has *32 vs *size confusion.

One issue I still have is taht of ‘isize’ vs ‘usize’. The issue is as follows:

  1. indexing always wants usize

  2. often, I need to store ‘offsets’, which can be negative

My current solution is:

  1. make everythign isize

  2. pay an “as usize” syntactical penalty every time I have to index

=====

Alternatives / suggestions ?


#2

If this occurs a lot, it may be time for a simple expression macro to encapsulate this. I’ve used ix!(). If your indexing range is less than half of usize then this definition might work for you:

macro_rules! ix {
    ($e: expr) => {
        let val = $e;
        assert!(val >= 0);  // Checks that e is integer and non-negative
        (val as usize)
    }
}

Credits: If memory serves, @HadrienG suggested this to me when I had a similar query.
Edit: “non-negative”, rather than “positive”.


#3

@TomP : very nice macro solution. Thanks!


#4

BTW, if you’re targeting 64-bit machines, you may change assert!(val >= 0) to debug_assert!(val >= 0) for performance. There’s still a bounds check in the indexing, and any negative isize value cast as usize will be so large, that it will certainly exceed the upper bound of anything you can physically store on 64-bit machines for foreseeable future.