concept Mandelbrot in category rust

appears as: Mdelbrot
Rust in Action

This is an excerpt from Manning's book Rust in Action.

In a terminal window, execute the following commands to create a project that can render the Mandelbrot set.

Listing 2. 13. Rendering the Mandelbrot set (ch2/ch2-mandelbrot/src/main.rs)
use num::complex::Complex; #1

fn calculate_mandelbrot(  #2
  max_iters: usize,       #3
  x_min: f64,             #4
  x_max: f64,             #4
  y_min: f64,             #4
  y_max: f64,             #4
  width: usize,           #5
  height: usize,          #5
) -> Vec<Vec<usize>> {
  let mut all_rows: Vec<Vec<usize>> = Vec::with_capacity(width);  #6
  for img_y in 0..height {                                           #7
    let mut row: Vec<usize> = Vec::with_capacity(height);
    for img_x in 0..width {
      let cx = x_min + (x_max - x_min) * (img_x as f64 / width as f64);   #8
      let cy = y_min + (y_max - y_min) * (img_y as f64 / height as f64);  #8
      let escaped_at = mandelbrot_at_point(cx, cy, max_iters);          #9
      row.push(escaped_at);
    }
    all_rows.push(row);
  }
  all_rows
}

fn mandelbrot_at_point(cx: f64, cy: f64, max_iters: usize) -> usize {  #10
  let mut z = Complex { re: 0.0, im: 0.0 };      #11
  let c = Complex::new(cx, cy);                  #12

  for i in 0..=max_iters {
    if z.norm() > 2.0 {              #13
      return i;
    }
    z = z * z + c;                   #14
  }
  return max_iters;                  #15
}

fn render_mandelbrot(escape_vals: Vec<Vec<usize>>) {
  for row in escape_vals {
    let mut line = String::with_capacity(row.len());
    for column in row {
      let val = match column {
        0..=2 => ' ',
        2..=5 => '.',
        5..=10 => '•',
        11..=30 => '*',
        30..=100 => '+',
        100..=200 => 'x',
        200..=400 => '$',
        400..=700 => '#',
        _ => '%',
      };

      line.push(val);
    }
    println!("{}", line);
  }
}

fn main() {
  let mandelbrot = calculate_mandelbrot(1000, -2.0, 1.0, -1.0, 1.0, 100, 24);

  render_mandelbrot(mandelbrot);
}