Skip to content

Instantly share code, notes, and snippets.

@ilopX
Created April 13, 2023 03:06
Show Gist options
  • Save ilopX/098e2f85dcdaea38be8e41242039be36 to your computer and use it in GitHub Desktop.
Save ilopX/098e2f85dcdaea38be8e41242039be36 to your computer and use it in GitHub Desktop.
use std::ops::Range;
use std::rc::Rc;
fn main() {
let mut world = World::new(4);
world.get_cell(1).print();
world.get_cell(2).print();
world.get_cell(3).print();
world.get_cell(4).print();
world.create_cell_from(1);
world.get_cell(5).print();
world.create_cell_from(10);
world.get_cell(6).print();
}
struct World {
cells: Vec<Cell>,
}
impl World {
fn new(len: usize) -> Self {
Self {
cells: World::_create_cells(len),
}
}
fn get_cell(&self, index: usize) -> &Cell {
self.cells.get(index - 1).unwrap()
}
fn create_cell_from(&mut self, clone_cell_index: usize) {
let new_index = self.cells.len() as u32 + 1;
let new_or_exiting_param = self._find_or_create_param(clone_cell_index);
let new_cell = Cell {
index: new_index,
param: new_or_exiting_param,
};
self.cells.push(new_cell);
}
fn _create_cells(len: usize) -> Vec<Cell> {
let param_1 = Params(String::from("one"), true, 100);
let param_2 =Params(String::from("two"), false, 200);
let mut cells = vec![];
let len_have = len / 2;
World::_add_cells(&mut cells, 0..len_have, param_1);
World::_add_cells(&mut cells, len_have..len, param_2);
cells
}
fn _add_cells(cells: &mut Vec<Cell>, range: Range<usize>, param: Params) {
let param = Rc::new(param);
for i in range {
let cell = Cell {
index: (i + 1) as u32,
param: Rc::clone(&param),
};
cells.push(cell);
}
}
fn _find_or_create_param(&self, cell_index: usize) -> Rc<Params> {
if cell_index > self.cells.len() {
let new_param = Params(String::from("three"), true, 300);
Rc::new(new_param)
} else {
let existing_param = &self.get_cell(cell_index).param;
Rc::clone(existing_param)
}
}
}
struct Cell {
index: u32,
param: Rc<Params>,
}
impl Cell {
fn print(&self) {
println!("Cell(index: {}, ({}))", self.index, self.param.print())
}
}
struct Params(String, bool, u32);
impl Params {
fn print(&self) -> String {
format!("\"{}\", {}, {}", self.0, self.1, self.2)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment