Is it possible to disable boundary checks and how to allocate row contiguous memory and convert it


#1

Now, I know a lot of people will come and ask why do you even need this and to try better alternative. The use case is the following:
I have something which is sort of like a compiler (in the long future it could become a compiler plugin, but I doubt I’m capable of that). Now what it will give is a function + a memory manager. The memory manager will have a static map of how to allocate memory to different arrays in the function (including recycling memory). When performing the function, which includes iterating over arrays, the compiler before, in the spirit of Rust, will have guaranteed that there are no out of bounds indexing (as the actual code which does the computation is generated by the compiler). Since the whole application is for HPC I want to at least know how to disable boundary checks as well as how to make the memory manager allocate a large chunk of memory and then being able to cast a[x] to a pointer to f64 for instance, while a[b] to a pointer to i32.


#2

If you’re implementing something like this, then don’t implement bounds checks. Done :smile:

This isn’t available in stable Rust yet, but https://doc.rust-lang.org/stable/alloc/heap/


#3

You don’t, and you don’t.

Both of those are unsafe and violate Rust’s guarantees, so it won’t help you do them. That said, this is why unsafe exists: if you check the documentation for slices, you’ll see it has a method for unchecked indexing. I don’t believe there’s any stable, direct access to memory allocation, but you can just use a Vec for that.

If you don’t understand how to do that, then you should probably read and internalise The Rustonomicon. Dabbling in unsafe code (particularly involving pointer casts) requires you to know what you’re doing, and to fully understand the invariants you’re not allowed to break. A few random examples in a forum aren’t going to be sufficient.


#4

So I guess the point here was that standard indexing still does boundary checks even in unsafe blocks. However what Daniel pointed out there exists a get_unchecked, which I was not aware of.

I guess a Vec for allocation might be enough. I guess I will need something like transmutate to convert slices from raw u8 for instance to slices of another type. Thanks for the link to that second book, which I was also unaware. In general I know what I am doing and I have programmed it a bit in c++ before without any “discovered” bugs. Nevertheless, I am quite cautious with it as it is an area which I am internally scared of a bit.


#5

If you transmute(_), be careful to keep alignment.