Finally got generators working

This commit is contained in:
Rolf Martin Glomsrud 2023-11-30 19:55:36 +01:00
parent 82e27fa4b2
commit e325cb57e7
8 changed files with 120 additions and 343 deletions

5
.vscode/settings.json vendored Normal file
View file

@ -0,0 +1,5 @@
{
"rust-analyzer.linkedProjects": [
"./Cargo.toml"
]
}

12
Cargo.lock generated
View file

@ -8,6 +8,8 @@ version = "0.1.0"
dependencies = [
"anyhow",
"async-trait",
"futures-core",
"futures-util",
"notan",
"tokio",
"tokio-test",
@ -115,9 +117,9 @@ checksum = "96d30a06541fbafbc7f82ed10c06164cfbd2c401138f6addd8404629c4b16711"
[[package]]
name = "async-stream"
version = "0.3.4"
version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad445822218ce64be7a341abfb0b1ea43b5c23aa83902542a4542e78309d8e5e"
checksum = "cd56dd203fef61ac097dd65721a419ddccb106b2d2b70ba60a6b529f03961a51"
dependencies = [
"async-stream-impl",
"futures-core",
@ -126,13 +128,13 @@ dependencies = [
[[package]]
name = "async-stream-impl"
version = "0.3.4"
version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4655ae1a7b0cdf149156f780c5bf3f1352bc53cbd9e0a361a7ef7b22947e965"
checksum = "16e62a023e7c117e27523144c5d2459f4397fcc3cab0085af8e2224f643a0193"
dependencies = [
"proc-macro2",
"quote",
"syn 1.0.109",
"syn 2.0.39",
]
[[package]]

View file

@ -8,6 +8,8 @@ edition = "2021"
[dependencies]
anyhow = "1.0.75"
async-trait = "0.1.64"
futures-core = "0.3.29"
futures-util = "0.3.29"
notan = "0.11.0"
tokio = {version = "1.34.0", features = ["full"] }
tokio-test = "*"

View file

@ -1,247 +0,0 @@
use crate::BarPlugin::Bar;
use async_trait::async_trait;
#[derive(Clone, Debug)]
pub struct GuiVec {
pub list: Vec<Bar>,
initialSize:usize,
pub lastTime:f64,
pub reads:i32,
pub writes:i32,
pub comps:i32,
isPaused:bool,
delay:f32,
pub done:bool,
renderSkip:i32,
skipped:i32,
lastTouched:Vec<usize>,
lastPlayed:f64,
}
#[async_trait]
pub trait SortingList {
async fn new(length: usize, delay: f32) -> Self;
fn len(&self) -> usize;
async fn swap(&mut self, index1: usize, index2: usize) -> bool;
async fn draw(&mut self);
fn randomize(&mut self);
fn elements(&mut self) -> std::slice::Iter<'_, Bar>;
fn get(&mut self, i: usize) -> &Bar;
fn lessThan(&mut self, a: usize, b: usize) -> bool;
fn lessThanEqual(&mut self, a: usize, b: usize) -> bool;
fn isSorted(&mut self) -> bool;
async fn set(&mut self, i: usize, elem: Bar) -> bool;
async fn show(&mut self);
fn getListClone(&self) -> Vec<Bar>;
}
#[async_trait]
impl SortingList for GuiVec {
async fn new(length: usize, delay: f32) -> Self {
let colorStep = 360. / length as f32;
let mut list: Vec<Bar> = vec![];
let freqStep = 50. + ((2000. - 50.) / length as f32);
for i in 1..length + 1 {
let frequency = i as f32 * freqStep;
list.push(Bar::new(i, (colorStep * i as f32) / 360.));
}
<<<<<<< HEAD
//Generate sounds
GuiVec {
list,
initialSize: length as usize,
lastTime: 0.0,
reads: 0,
writes: 0,
comps: 0,
isPaused: false,
delay,
done: false,
renderSkip: 1,
skipped: 0,
lastTouched: Vec::with_capacity(2),
lastPlayed: 0.,
=======
GuiVec{
list,
initialSize:length as usize,
lastTime: 0.0 ,
reads:0,
writes:0,
comps:0,
isPaused:false,
delay,
done:false,
renderSkip:1,
skipped:0,
lastTouched:Vec::with_capacity(2),
lastPlayed:0.,
>>>>>>> master
}
}
async fn draw(&mut self) {}
fn len(&self) -> usize {
self.list.len()
}
async fn swap(&mut self, index1: usize, index2: usize) -> bool {
self.writes += 2;
self.reads += 2;
self.list.swap(index1, index2);
<<<<<<< HEAD
=======
>>>>>>> master
self.lastTouched.clear();
self.lastTouched.push(index1);
self.lastTouched.push(index2);
self.draw().await;
self.done
}
fn randomize(&mut self) {}
fn elements(&mut self) -> std::slice::Iter<'_, Bar> {
self.list.iter()
}
fn get(&mut self, i: usize) -> &Bar {
self.reads += 1;
self.lastTouched.clear();
self.lastTouched.push(i);
self.list.get(i).unwrap()
}
fn lessThan(&mut self, a: usize, b: usize) -> bool {
self.comps += 1;
return self.get(a).position < self.get(b).position;
}
fn lessThanEqual(&mut self, a: usize, b: usize) -> bool {
self.comps += 1;
return self.get(a).position <= b;
}
fn isSorted(&mut self) -> bool {
self.reads += self.len() as i32;
let mut prev = 0;
for bar in self.list.iter() {
if bar.position < prev {
return false;
} else {
prev = bar.position;
}
}
true
}
async fn set(&mut self, i: usize, elem: Bar) -> bool {
self.writes += 1;
self.reads += 1;
self.list[i] = elem;
self.draw().await;
<<<<<<< HEAD
=======
if time::get_time() + 0.1 >= self.lastPlayed{
self.lastPlayed = time::get_time()+0.1;
}
>>>>>>> master
self.lastTouched.clear();
self.lastTouched.push(i);
self.done
}
async fn show(&mut self) {
loop {
if !self.done {
self.draw().await
} else {
break;
}
}
}
fn getListClone(&self) -> Vec<Bar> {
self.list.clone()
}
}
pub struct NonGuiVec {
pub list: Vec<Bar>,
}
#[async_trait]
impl SortingList for NonGuiVec {
async fn new(length: usize, delay: f32) -> Self {
let mut list = Vec::new();
for i in 0..(length as usize) {
list.push(Bar::new(i, i as f32))
}
NonGuiVec { list: list }
}
fn len(&self) -> usize {
self.list.len()
}
async fn swap(&mut self, index1: usize, index2: usize) -> bool {
self.list.swap(index1, index2);
false
}
async fn draw(&mut self) {
self.swap(0, 0).await;
}
fn randomize(&mut self) {}
fn elements(&mut self) -> std::slice::Iter<'_, Bar> {
self.list.iter()
}
fn get(&mut self, i: usize) -> &Bar {
self.list.get(i).unwrap()
}
fn lessThan(&mut self, a: usize, b: usize) -> bool {
return self.get(a).position < self.get(b).position;
}
fn lessThanEqual(&mut self, a: usize, b: usize) -> bool {
return self.get(a).position <= b;
}
fn isSorted(&mut self) -> bool {
let mut prev = 0;
for bar in self.list.iter() {
if bar.position < prev {
return false;
} else {
prev = bar.position;
}
}
true
}
async fn set(&mut self, i: usize, elem: Bar) -> bool {
self.list[i] = elem;
self.draw().await;
false
}
async fn show(&mut self) {}
fn getListClone(&self) -> Vec<Bar> {
self.list.clone()
}
}

View file

@ -1,64 +0,0 @@
mod radixSort;
mod insertSort;
mod bubbleSort;
mod binaryHeap;
mod coctailShaker;
mod quickSort;
mod bogoSort;
mod radixSortLSD;
use crate::GuiHookVec::GuiVec;
use crate::GuiHookVec::SortingList;
#[derive(Debug, Clone)]
pub struct Algorithm{
algorithms:Vec<String>
}
impl Algorithm{
pub fn new() -> Self{
Algorithm { algorithms: vec![
"insertSort".to_string(),
"bubbleSort".to_string(),
"bogoSort".to_string(),
"cocktailShaker".to_string(),
"binaryHeap".to_string(),
"quickSort".to_string(),
"radixSortMSD".to_string(),
"radixSortLSD".to_string()
] }
}
pub async fn run(length:usize, delay:f32, functionName:String){
let mut list:GuiVec = SortingList::new(length, delay).await;
list.randomize();
match functionName.as_str() {
"insertSort" => insertSort::insertSort(&mut list).await,
"bubbleSort" => bubbleSort::bubbleSort(&mut list).await,
"bogoSort" => bogoSort::bogoSort(&mut list).await,
"cocktailShaker" => coctailShaker::cocktailShaker(&mut list).await,
"binaryHeap" => binaryHeap::binaryHeap(&mut list).await,
"quickSort" => quickSort::quickSort(&mut list).await,
"radixSortMSD" => radixSort::radixSort(&mut list).await,
"radixSortLSD" => radixSortLSD::radixSort(&mut list).await,
_ => panic!("No algorithm with that name implemented!")
}
if !list.done{
list.show().await
}
}
pub fn getAlgorithms(&self) -> &Vec<String>{
&self.algorithms
}
}

Binary file not shown.

View file

@ -0,0 +1,37 @@
use std::cell::RefCell;
use std::rc::Rc;
use futures_core::stream::Stream;
use futures_util::pin_mut;
use futures_util::stream::StreamExt;
pub fn insert_sort(
mut list: Vec<u32>,
) -> impl std::ops::Generator<Yield = Rc<RefCell<Vec<u32>>>, Return = ()> {
let list2 = Rc::new(RefCell::new(list));
let len = list2.borrow().len() - 1;
move || {
for index in 0..len {
let mut j = index;
while j > 0 && list2.borrow()[j] < list2.borrow()[j+1] {
{
list2.borrow_mut().swap(j, j-1);
}
yield list2.clone();
j -= 1;
}
}
}
}
pub fn test(
mut list: Vec<u32>,
) -> impl std::ops::Generator<Yield = Rc<RefCell<Vec<u32>>>, Return = ()> {
let list2 = Rc::new(RefCell::new(list));
let len = list2.borrow().len();
move || {
for index in 0..len {
yield list2.clone();
}
}
}

View file

@ -1,40 +1,82 @@
#![feature(generators, generator_trait)]
mod BarPlugin;
mod GuiHookVec;
mod algorithm;
mod dropdown;
use std::f32::consts::PI;
use std::fs::File;
use std::path::Path;
use dropdown::ButtonDropDown;
use std::cell::RefCell;
use std::ops::{Generator, GeneratorState};
use std::pin::Pin;
use std::rc::Rc;
use anyhow::Result;
use insertSortGenerator::{insert_sort, test};
use notan::draw::*;
use notan::draw::{CreateDraw, CreateFont, DrawConfig, Font};
use notan::prelude::*;
use tokio::runtime::Runtime;
use tokio::time::{sleep, Duration};
mod insertSortGenerator;
#[derive(AppState)]
struct State {
gen: Box<dyn Unpin + Generator<Yield = Rc<RefCell<Vec<u32>>>, Return = ()>>,
delay: f32,
lastStepTime: f32,
font: Font,
next: Option<String>,
finished: bool,
}
fn setup(gfx: &mut Graphics) -> State {
let mut arr = (1..=100).collect::<Vec<u32>>();
let gen = insert_sort(arr);
State {
gen: Box::new(gen),
delay: 1.,
lastStepTime: 1.,
font: gfx
.create_font(include_bytes!("./assets/LDF-ComicSans/LDFComicSans.ttf"))
.unwrap(),
next: None,
finished: false,
}
}
#[notan_main]
fn main() -> Result<(), String> {
notan::init().draw(draw).add_config(DrawConfig).build()
notan::init_with(setup)
.update(update)
.draw(draw)
.add_config(DrawConfig)
.build()
}
fn update(state: &mut State) {
if !state.finished {
match Pin::new(&mut state.gen).resume(()) {
GeneratorState::Yielded(a) => {
state.next = Some(format!("{:?}", a));
println!("We set something")
}
GeneratorState::Complete(_) => {
state.finished = true;
println!("Generator finished");
}
}
};
}
fn draw(gfx: &mut Graphics) {
let _ = run(gfx);
}
fn draw(gfx: &mut Graphics, state: &mut State) {
let mut draw = gfx.create_draw();
fn run(gfx: &mut Graphics) -> Result<()> {
let mut rt = Runtime::new()?;
rt.block_on(async {
let mut draw = gfx.create_draw();
draw.clear(Color::BLACK);
draw.triangle((400.0, 100.0), (100.0, 500.0), (700.0, 500.0));
gfx.render(&draw);
println!("Before sleep");
sleep(Duration::from_millis(10000)).await;
println!("After sleep");
draw.clear(Color::BLACK);
draw.rect((400., 100.), (100., 100.));
gfx.render(&draw);
});
Ok(())
draw.clear(Color::BLACK);
let text = if state.next.is_some() {
state.next.clone().unwrap()
} else {
String::new()
};
draw.text(&state.font, &text)
.position(100., 100.)
.size(60.)
.color(Color::WHITE)
.h_align_center()
.v_align_middle();
gfx.render(&draw);
}