I am a bit new to Rust and have written the following code:
fn main() {
println!("Generating the logistic map");
//Calculate a few points of the logistic map,
let map: [[i64; 700]; 700] = generate();
println!("Generated the logistic map");
//then use the resulting array to generate a black-and-white image.
paint(map);
}
fn generate<const LEN:usize>() -> [[i64; LEN]; LEN] {
let min_x = 3.;
let max_x = 4.;
// let min_y = 0.;
// let max_y = 4.;
let pre_iterations = 1000;
let iterations = 10000;
//Generate the logistic map
let mut map = [[0; LEN]; LEN];
//Loop for every line
for i in 0..LEN {
let factor = min_x + (max_x - min_x) * (i as f64 / LEN as f64);
let mut value = 0.5;
//Run for a few iterations without saving the values
for _ in 0..pre_iterations {
value = factor * value * (1. - value);
}
//Run for a few iterations while saving the values
for _ in 0..iterations {
value = factor * value * (1. - value);
//Save the value
let x = (value * LEN as f64) as usize;
map[i][x] += 1; //Increment the value at the given position
}
}
map
}
fn paint<const LEN:usize>(map: [[i64; LEN]; LEN]) {
//Create a new image
let mut img = image::ImageBuffer::new(LEN as u32, LEN as u32);
//Loop for every pixel
for x in 0..(LEN as u32) {
for y in 0..(LEN as u32) {
//Get the value at the given position
let value = map[y as usize][x as usize];
let white_value = 260;
//Set the pixel to white, if the value is above a certain threshold
if value > white_value {
// *pixel = image::Luma([255u8]);
img.put_pixel(x, y, image::Luma([255u8]));
}
else {
// *pixel = image::Luma([value as u8]);
img.put_pixel(x, y, image::Luma([value as u8]));
}
}
}
println!("Painted the image");
//Save the image
let result = img.save("logistic_map.png");
match result {
Ok(_) => println!("Image saved successfully"),
Err(e) => println!("Error while saving image: {}", e),
}
}
It works and gives out the desired image, but when I change the size from 700 to 720, it runs up until the "painted the image" and then segfaults, with the image being empty (0 Bytes).
Interestingly, if I change the size to 750 or greater, the code segfaults without even reaching the first line.
I didn't find anything online, so I wanted to ask here: what is going on? (The const generic is just for ease of use, if all LEN were replaced, it would work just the same.)