How to split and use heap memory distributed in mass using Rust?

I have read a lot about Rust lately, but I'm still just starting to oxidize. My brain retains most of its C / C ++ reflexes, so forgive me if this question does not matter due to how everything is done in Rust.

Is it possible at all (preferably?) To allocate a block of arbitrary size on the heap, and then compare the data structure above it with bindings that have smaller pieces of memory?

Using C99, you can write this:

typedef unsigned char BYTE; typedef struct { size_t size; BYTE payload[]; } flex; // ... flex * flex_new(size_t _size) { flex *f = malloc(sizeof(flex) + _size * sizeof(BYTE)); f->size = _size; return f; } 

Flexible length arrays can be useful, for example. when implementing memory pools with chunks of variable size or when allocating memory on a heap dedicated to threading. A data structure requiring size is known only at runtime, is allocated in an "atomic" way, and its elements are packed adjacent to each other.

I am wondering if a similar Rust implementation is possible (without unsafe constructs), and if so, how it looks. Maybe the compiler can output some information using the lifetime specifiers in the definition of struct ?

+5
source share
1 answer

In terms of β€œflexible length arrays,” you can use Vec::with_capacity to highlight more than your immediate need:

 let mut vec: Vec<int> = Vec::with_capacity(10); // The vector contains no items, even though it has capacity for more assert_eq!(vec.len(), 0); // These are all done without reallocating... for i in range(0i, 10) { vec.push(i); } // ...but this may make the vector reallocate vec.push(11); 

For a more general case, TypedArena is what you would like to use.

+2
source

Source: https://habr.com/ru/post/1209442/


All Articles