rand0m
rand0m

Reputation: 13

How to fill a Vec with u64::max_value()

Is there a way in rust to fill a vec it with a range that has for limit u64::max_value ?

fn main() {
    let vals: Vec<u64> = (2..u64::max_value()).collect();
    println!("{:?}", vals.len());
}

compiler throws: thread 'main' panicked at 'capacity overflow', src/liballoc/raw_vec.rs:777:5

Upvotes: 0

Views: 488

Answers (2)

Boiethios
Boiethios

Reputation: 42829

I suppose that your computer has a 64 bits architecture. That means that it can address at most 2^64 bytes (in practice, that's less).

Now, since the size of an u64 is 8 bytes, you're trying to reserve 8 * 2^64 bytes. Your computer cannot even address such an amount of bytes!

Also, you're trying to allocate several millions of terabytes in the RAM. That's not a reasonable amount of memory.

The line that panics in the std lib is the following:

let alloc_size = capacity.checked_mul(elem_size).unwrap_or_else(|| capacity_overflow());

It verifies that the capacity (the number of items) multiplied by the size of your element (8 bytes as I said) does not overflow. That's the programmatic way to represent my former reasoning.

Upvotes: 5

mcarton
mcarton

Reputation: 30061

No.

u64::max_value() is a huge number. You don't have that much memory. No one does.

Upvotes: 4

Related Questions