Compare commits

..

No commits in common. "e005675bb8fa5684b200285373e94de9d3e9c9ee" and "8902c986f8d8014c35974e32b6777c362b8be127" have entirely different histories.

32 changed files with 3617 additions and 4603 deletions

4
.rustfmt.toml Normal file
View File

@ -0,0 +1,4 @@
edition = "2021"
fn_params_layout = "Compressed"
fn_single_line = true
hard_tabs = true

3148
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,8 +1,7 @@
[package] [package]
name = "ytbn_graphing_software" name = "ytbn_graphing_software"
version = "0.1.0" version = "0.1.0"
edition = "2024" edition = "2021"
rust-version = "1.88"
license = "AGPL-3.0" license = "AGPL-3.0"
repository = "https://github.com/Titaniumtown/YTBN-Graphing-Software" repository = "https://github.com/Titaniumtown/YTBN-Graphing-Software"
description = "Crossplatform (and web-compatible) graphing calculator" description = "Crossplatform (and web-compatible) graphing calculator"
@ -34,72 +33,62 @@ strip = false
[dependencies] [dependencies]
parsing = { path = "./parsing" } parsing = { path = "./parsing" }
eframe = { path = "../simon-egui/crates/eframe", default-features = false, features = [ eframe = { git = "https://github.com/titaniumtown/egui.git", default-features = false, features = [
"glow", "glow",
"x11",
] } ] }
egui = { path = "../simon-egui/crates/egui", default-features = false, features = [ egui = { git = "https://github.com/titaniumtown/egui.git", default-features = false, features = [
"serde", "serde",
] } ] }
epaint = { path = "../simon-egui/crates/epaint", default-features = false, features = [ epaint = { git = "https://github.com/titaniumtown/egui.git", default-features = false , features = [
"bytemuck", "bytemuck",
] } ] }
emath = { path = "../simon-egui/crates/emath", default-features = false } emath = { git = "https://github.com/titaniumtown/egui.git", default-features = false }
egui_plot = { git = "https://github.com/emilk/egui_plot.git", default-features = false } egui_plot = { git = "https://github.com/titaniumtown/egui.git", default-features = false }
shadow-rs = { version = "0.38", default-features = false }
shadow-rs = { version = "0.12", default-features = false }
const_format = { version = "0.2", default-features = false, features = ["fmt"] } const_format = { version = "0.2", default-features = false, features = ["fmt"] }
cfg-if = "1" cfg-if = "1"
ruzstd = "0.8" ruzstd = "0.5"
tracing = "0.1" tracing = "0.1"
itertools = "0.14" itertools = "0.10"
static_assertions = "1.1" static_assertions = "1.1"
bincode = "1.3" bincode = "1.3"
serde = "1" serde = "1"
log = "0.4"
# Note: benchmarks are in a separate crate - run with: [dev-dependencies]
# cd benchmarks && cargo bench benchmarks = { path = "./benchmarks" }
[build-dependencies] [build-dependencies]
shadow-rs = "0.38" shadow-rs = "0.12"
epaint = { path = "../simon-egui/crates/epaint", default-features = false, features = [ epaint = { git = "https://github.com/titaniumtown/egui.git", default-features = false, features = [
"bytemuck", "bytemuck",
] } ] }
egui = { path = "../simon-egui/crates/egui", default-features = false, features = [ egui = { git = "https://github.com/titaniumtown/egui.git", default-features = false, features = [
"serde", "serde",
] } ] }
bincode = "1.3" bincode = "1.3"
serde = "1" serde = "1"
serde_json = "1" serde_json = "1"
zstd = { version = "0.13", default-features = false } zstd = { version = "0.11", default-features = false, features = ["pkg-config"] }
run_script = "0.10" run_script = "0.9"
json5 = "0.4" json5 = "0.4"
itertools = "0.14" itertools = "0.10"
[target.'cfg(not(target_arch = "wasm32"))'.dependencies] [target.'cfg(not(target_arch = "wasm32"))'.dependencies]
web-time = "1.1" instant = "0.1"
tracing-subscriber = "0.3" tracing-subscriber = "0.3"
getrandom = { version = "0.3" } getrandom = { version = "0.2" }
[target.'cfg(target_arch = "wasm32")'.dependencies] [target.'cfg(target_arch = "wasm32")'.dependencies]
web-time = "1.1" instant = { version = "0.1", features = ["wasm-bindgen"] }
lol_alloc = "0.4" lol_alloc = "0.4.0"
wasm-bindgen = { version = "0.2", default-features = false, features = ["std"] } wasm-bindgen = { version = "0.2", default-features = false, features = ["std"] }
web-sys = "0.3" web-sys = "0.3"
tracing-wasm = "0.2" tracing-wasm = "0.2"
getrandom = { version = "0.3", features = ["wasm_js"] } getrandom = { version = "0.2", features = ["js"] }
wasm-bindgen-futures = "0.4" wasm-bindgen-futures = "0.4.34"
[package.metadata.cargo-all-features] [package.metadata.cargo-all-features]
skip_optional_dependencies = true #don't test optional dependencies, only features skip_optional_dependencies = true #don't test optional dependencies, only features
[patch.crates-io]
egui = { path = "../simon-egui/crates/egui" }
epaint = { path = "../simon-egui/crates/epaint" }
emath = { path = "../simon-egui/crates/emath" }
ecolor = { path = "../simon-egui/crates/ecolor" }
eframe = { path = "../simon-egui/crates/eframe" }
egui-winit = { path = "../simon-egui/crates/egui-winit" }
egui_glow = { path = "../simon-egui/crates/egui_glow" }
egui-wgpu = { path = "../simon-egui/crates/egui-wgpu" }

View File

@ -1,8 +1,14 @@
## TODO: ## TODO:
1. Function management 1. Function management
- Integrals between functions (too hard to implement, maybe will shelve) - Integrals between functions (too hard to implement, maybe will shelve)
- Display intersection between functions (would have to rewrite a lot of the function plotting handling)
- [Drag and drop support](https://github.com/emilk/egui/discussions/1530) in the UI to re-order functions
- Hide/disable functions
- Prevent user from making too many function entries - Prevent user from making too many function entries
- Display function errors as tooltips or a warning box (not preventing the display of the graph)
- Clone functions
2. Smart display of graph 2. Smart display of graph
- Display of intersections between functions
3. Allow constants in min/max integral input (like pi or euler's number) 3. Allow constants in min/max integral input (like pi or euler's number)
4. Sliding values for functions (like a user-interactable slider that adjusts a variable in the function, like desmos) 4. Sliding values for functions (like a user-interactable slider that adjusts a variable in the function, like desmos)
5. Fix integral display 5. Fix integral display

View File

@ -1,18 +1,13 @@
[package] [package]
name = "benchmarks" name = "benchmarks"
version = "0.1.0" version = "0.1.0"
edition = "2024" edition = "2021"
rust-version = "1.88"
license = "AGPL-3.0" license = "AGPL-3.0"
[lib] [lib]
bench = false
[[bench]]
name = "split_function"
harness = false
[dependencies] [dependencies]
pprof = { version = "0.14", features = ["flamegraph"] } pprof = { version = "0.9", features = ["flamegraph"] }
criterion = { version = "0.5", features = ["html_reports"] } criterion = "0.3"
criterion-macro = "0.3"
parsing = { path = "../parsing" } parsing = { path = "../parsing" }

View File

@ -1,46 +0,0 @@
use criterion::{criterion_group, criterion_main, Criterion};
use parsing::split_function_chars;
use std::time::Duration;
fn custom_criterion() -> Criterion {
Criterion::default()
.warm_up_time(Duration::from_millis(250))
.sample_size(1000)
}
fn mutli_split_function(c: &mut Criterion) {
let data_chars = vec![
"sin(x)cos(x)",
"x^2",
"2x",
"log10(x)",
"E^x",
"xxxxx",
"xsin(x)",
"(2x+1)(3x+1)",
"x**2",
"pipipipipipix",
"pi(2x+1)",
"(2x+1)pi",
]
.iter()
.map(|a| a.chars().collect::<Vec<char>>())
.collect::<Vec<Vec<char>>>();
let mut group = c.benchmark_group("split_function");
for entry in data_chars {
group.bench_function(entry.iter().collect::<String>(), |b| {
b.iter(|| {
split_function_chars(&entry, parsing::SplitType::Multiplication);
})
});
}
group.finish();
}
criterion_group! {
name = benches;
config = custom_criterion();
targets = mutli_split_function
}
criterion_main!(benches);

View File

@ -1,18 +1,26 @@
//! Benchmarks library - profiler utilities for flamegraphs #![feature(custom_test_frameworks)]
#![test_runner(criterion::runner)]
#[allow(unused_imports)]
use parsing::split_function_chars;
#[allow(unused_imports)]
use std::time::Duration;
use std::{fs::File, os::raw::c_int, path::Path}; use std::{fs::File, os::raw::c_int, path::Path};
use criterion::profiler::Profiler; use criterion::profiler::Profiler;
#[allow(unused_imports)]
use criterion::{BenchmarkId, Criterion};
use criterion_macro::criterion;
use pprof::ProfilerGuard; use pprof::ProfilerGuard;
/// Flamegraph profiler for criterion benchmarks
pub struct FlamegraphProfiler<'a> { pub struct FlamegraphProfiler<'a> {
frequency: c_int, frequency: c_int,
active_profiler: Option<ProfilerGuard<'a>>, active_profiler: Option<ProfilerGuard<'a>>,
} }
impl<'a> FlamegraphProfiler<'a> { impl<'a> FlamegraphProfiler<'a> {
/// Create a new flamegraph profiler with the given sampling frequency #[allow(dead_code)]
pub fn new(frequency: c_int) -> Self { pub fn new(frequency: c_int) -> Self {
FlamegraphProfiler { FlamegraphProfiler {
frequency, frequency,
@ -21,7 +29,7 @@ impl<'a> FlamegraphProfiler<'a> {
} }
} }
impl Profiler for FlamegraphProfiler<'_> { impl<'a> Profiler for FlamegraphProfiler<'a> {
fn start_profiling(&mut self, _benchmark_id: &str, _benchmark_dir: &Path) { fn start_profiling(&mut self, _benchmark_id: &str, _benchmark_dir: &Path) {
self.active_profiler = Some(ProfilerGuard::new(self.frequency).unwrap()); self.active_profiler = Some(ProfilerGuard::new(self.frequency).unwrap());
} }
@ -41,3 +49,57 @@ impl Profiler for FlamegraphProfiler<'_> {
} }
} }
} }
#[allow(dead_code)] // this infact IS used by benchmarks
fn custom_criterion() -> Criterion {
Criterion::default()
.warm_up_time(Duration::from_millis(250))
.sample_size(1000)
}
#[allow(dead_code)] // this infact IS used by benchmarks
fn custom_criterion_flamegraph() -> Criterion {
custom_criterion().with_profiler(FlamegraphProfiler::new(100))
}
#[criterion(custom_criterion())]
fn mutli_split_function(c: &mut Criterion) {
let data_chars = vec![
"sin(x)cos(x)",
"x^2",
"2x",
"log10(x)",
"E^x",
"xxxxx",
"xsin(x)",
"(2x+1)(3x+1)",
"x**2",
"pipipipipipix",
"pi(2x+1)",
"(2x+1)pi",
]
.iter()
.map(|a| a.chars().collect::<Vec<char>>())
.collect::<Vec<Vec<char>>>();
let mut group = c.benchmark_group("split_function");
for entry in data_chars {
group.bench_function(entry.iter().collect::<String>(), |b| {
b.iter(|| {
split_function_chars(&entry, parsing::suggestions::SplitType::Multiplication);
})
});
}
group.finish();
}
// #[criterion(custom_criterion_flamegraph())]
// fn single_split_function(c: &mut Criterion) {
// let data_chars = "(2x+1)(3x+1)".chars().collect::<Vec<char>>();
// c.bench_function("split_function", |b| {
// b.iter(|| {
// split_function_chars(&data_chars);
// });
// });
// }

279
build.rs
View File

@ -1,180 +1,171 @@
use std::{ use std::{
collections::BTreeMap, collections::BTreeMap,
env, env,
fs::File, fs::File,
io::{BufWriter, Write}, io::{BufWriter, Write},
path::Path, path::Path,
sync::Arc,
}; };
use epaint::{ use epaint::{
FontFamily, text::{FontData, FontDefinitions, FontTweak},
text::{FontData, FontDefinitions, FontTweak}, FontFamily,
}; };
use run_script::ScriptOptions; use run_script::ScriptOptions;
include!(concat!( include!(concat!(
env!("CARGO_MANIFEST_DIR"), env!("CARGO_MANIFEST_DIR"),
"/src/unicode_helper.rs" "/src/unicode_helper.rs"
)); ));
fn font_stripper(from: &str, out: &str, unicodes: Vec<char>) -> Result<Vec<u8>, String> { fn font_stripper(from: &str, out: &str, unicodes: Vec<char>) -> Result<Vec<u8>, String> {
let unicodes: Vec<String> = unicodes.iter().map(|c| to_unicode_hash(*c)).collect(); let unicodes: Vec<String> = unicodes.iter().map(|c| to_unicode_hash(*c)).collect();
let new_path = [&env::var("OUT_DIR").unwrap(), out].concat(); let new_path = [&env::var("OUT_DIR").unwrap(), out].concat();
let unicodes_formatted = unicodes let unicodes_formatted = unicodes
.iter() .iter()
.map(|u| format!("U+{}", u)) .map(|u| format!("U+{}", u))
.collect::<Vec<String>>() .collect::<Vec<String>>()
.join(","); .join(",");
// Test to see if pyftsubset is found // Test to see if pyftsubset is found
let pyftsubset_detect = run_script::run("whereis pyftsubset", &(vec![]), &ScriptOptions::new()); let pyftsubset_detect = run_script::run("whereis pyftsubset", &(vec![]), &ScriptOptions::new());
match pyftsubset_detect { match pyftsubset_detect {
Ok((_i, s1, _s2)) => { Ok((_i, s1, _s2)) => {
if s1 == "pyftsubset: " { if s1 == "pyftsubset: " {
return Err(String::from("pyftsubset not found")); return Err(String::from("pyftsubset not found"));
} }
} }
// It was not, return an error and abort // It was not, return an error and abort
Err(x) => return Err(x.to_string()), Err(x) => return Err(x.to_string()),
} }
let script_result = run_script::run( let script_result = run_script::run(
&format!( &format!(
"pyftsubset {}/assets/{} --unicodes={} "pyftsubset {}/assets/{} --unicodes={}
mv {}/assets/{} {}", mv {}/assets/{} {}",
env!("CARGO_MANIFEST_DIR"), env!("CARGO_MANIFEST_DIR"),
from, from,
unicodes_formatted, unicodes_formatted,
env!("CARGO_MANIFEST_DIR"), env!("CARGO_MANIFEST_DIR"),
from.replace(".ttf", ".subset.ttf"), from.replace(".ttf", ".subset.ttf"),
new_path new_path
), ),
&(vec![]), &(vec![]),
&ScriptOptions::new(), &ScriptOptions::new(),
); );
if let Ok((_, _, error)) = script_result { if let Ok((_, _, error)) = script_result {
if error.is_empty() { if error.is_empty() {
return Ok(std::fs::read(new_path).unwrap()); return Ok(std::fs::read(new_path).unwrap());
} else { } else {
return Err(error); return Err(error);
} }
} else if let Err(error) = script_result { } else if let Err(error) = script_result {
return Err(error.to_string()); return Err(error.to_string());
} }
unreachable!() unreachable!()
} }
fn main() { fn main() {
// rebuild if new commit or contents of `assets` folder changed // rebuild if new commit or contents of `assets` folder changed
println!("cargo:rerun-if-changed=.git/logs/HEAD"); println!("cargo:rerun-if-changed=.git/logs/HEAD");
println!("cargo:rerun-if-changed=assets/*"); println!("cargo:rerun-if-changed=assets/*");
shadow_rs::ShadowBuilder::builder() shadow_rs::new().expect("Could not initialize shadow_rs");
.build()
.expect("Could not initialize shadow_rs");
let mut main_chars: Vec<char> = let mut main_chars: Vec<char> =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzsu0123456789?.,!(){}[]-_=+-/<>'\\ :^*`@#$%&|~;" b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzsu0123456789?.,!(){}[]-_=+-/<>'\\ :^*`@#$%&|~;"
.iter() .iter()
.map(|c| *c as char) .map(|c| *c as char)
.collect(); .collect();
main_chars.append(&mut vec!['π', '"']); main_chars.append(&mut vec!['π', '"']);
{ {
let filtered_chars: Vec<char> = main_chars let filtered_chars: Vec<char> = main_chars
.iter() .iter()
.filter(|c| !c.is_alphanumeric()) .filter(|c| !c.is_alphanumeric())
.cloned() .cloned()
.collect(); .collect();
let chars_array = format!( let chars_array = format!(
"const VALID_EXTRA_CHARS: [char; {}] = {};", "const VALID_EXTRA_CHARS: [char; {}] = {};",
filtered_chars.len(), filtered_chars.len(),
to_chars_array(filtered_chars), to_chars_array(filtered_chars),
); );
let path = Path::new(&env::var("OUT_DIR").unwrap()).join("valid_chars.rs"); let path = Path::new(&env::var("OUT_DIR").unwrap()).join("valid_chars.rs");
let mut file = BufWriter::new(File::create(path).expect("Could not save compressed_data")); let mut file = BufWriter::new(File::create(path).expect("Could not save compressed_data"));
write!(&mut file, "{}", chars_array).expect("unable to write chars_array"); write!(&mut file, "{}", chars_array).expect("unable to write chars_array");
} }
let fonts = FontDefinitions { let fonts = FontDefinitions {
font_data: BTreeMap::from([ font_data: BTreeMap::from([
( (
"Ubuntu-Light".to_owned(), "Ubuntu-Light".to_owned(),
Arc::new(FontData::from_owned( FontData::from_owned(
font_stripper( font_stripper(
"Ubuntu-Light.ttf", "Ubuntu-Light.ttf",
"ubuntu-light.ttf", "ubuntu-light.ttf",
[main_chars, vec!['∫']].concat(), [main_chars, vec!['∫']].concat(),
) )
.unwrap(), .unwrap(),
)), ),
), ),
( (
"NotoEmoji-Regular".to_owned(), "NotoEmoji-Regular".to_owned(),
Arc::new(FontData::from_owned( FontData::from_owned(
font_stripper( font_stripper(
"NotoEmoji-Regular.ttf", "NotoEmoji-Regular.ttf",
"noto-emoji.ttf", "noto-emoji.ttf",
vec!['🌞', '🌙', '✖'], vec!['🌞', '🌙', '✖'],
) )
.unwrap(), .unwrap(),
)), ),
), ),
( (
"emoji-icon-font".to_owned(), "emoji-icon-font".to_owned(),
Arc::new( FontData::from_owned(
FontData::from_owned( font_stripper("emoji-icon-font.ttf", "emoji-icon.ttf", vec!['⚙']).unwrap(),
font_stripper( )
"emoji-icon-font.ttf", .tweak(FontTweak {
"emoji-icon.ttf", scale: 0.8,
vec!['⚙', '⎘', '👁', '○', '⬆', '⬇', '⚠'], y_offset_factor: 0.07,
) y_offset: 0.0,
.unwrap(), baseline_offset_factor: -0.0333,
) }),
.tweak(FontTweak { ),
scale: 0.8, ]),
y_offset_factor: 0.07, families: BTreeMap::from([
y_offset: 0.0, (
}), FontFamily::Monospace,
), vec![
), "Ubuntu-Light".to_owned(),
]), "NotoEmoji-Regular".to_owned(),
families: BTreeMap::from([ "emoji-icon-font".to_owned(),
( ],
FontFamily::Monospace, ),
vec![ (
"Ubuntu-Light".to_owned(), FontFamily::Proportional,
"NotoEmoji-Regular".to_owned(), vec![
"emoji-icon-font".to_owned(), "Ubuntu-Light".to_owned(),
], "NotoEmoji-Regular".to_owned(),
), "emoji-icon-font".to_owned(),
( ],
FontFamily::Proportional, ),
vec![ ]),
"Ubuntu-Light".to_owned(), };
"NotoEmoji-Regular".to_owned(),
"emoji-icon-font".to_owned(),
],
),
]),
};
let data = bincode::serialize(&fonts).unwrap(); let data = bincode::serialize(&fonts).unwrap();
let zstd_levels = zstd::compression_level_range(); let zstd_levels = zstd::compression_level_range();
let data_compressed = let data_compressed =
zstd::encode_all(data.as_slice(), *zstd_levels.end()).expect("Could not compress data"); zstd::encode_all(data.as_slice(), *zstd_levels.end()).expect("Could not compress data");
let path = Path::new(&env::var("OUT_DIR").unwrap()).join("compressed_data"); let path = Path::new(&env::var("OUT_DIR").unwrap()).join("compressed_data");
let mut file = BufWriter::new(File::create(path).expect("Could not save compressed_data")); let mut file = BufWriter::new(File::create(path).expect("Could not save compressed_data"));
file.write_all(data_compressed.as_slice()) file.write_all(data_compressed.as_slice())
.expect("Failed to save compressed data"); .expect("Failed to save compressed data");
} }

76
build.sh Executable file
View File

@ -0,0 +1,76 @@
#!/bin/bash
set -e
rm -fr tmp | true
rm -fr pkg | true
# cargo test
export RUSTFLAGS="--cfg=web_sys_unstable_apis"
if test "$1" == "" || test "$1" == "release"; then
time cargo build --release --target wasm32-unknown-unknown -Z build-std=core,compiler_builtins,alloc,std,panic_abort,panic_unwind,proc_macro,unwind -Z build-std-features=panic_immediate_abort --lib --timings
llvm-strip -s target/wasm32-unknown-unknown/release/ytbn_graphing_software.wasm
export TYPE="release"
elif test "$1" == "debug"; then
time cargo build --target wasm32-unknown-unknown -Z build-std=core,compiler_builtins,alloc,std,panic_abort,panic_unwind,proc_macro,unwind -Z build-std-features=panic-unwind --lib
export TYPE="debug"
else
echo "ERROR: build.sh, argument invalid"
exit 1
fi
pre_size=$(du -sb target/wasm32-unknown-unknown/${TYPE}/ytbn_graphing_software.wasm | awk '{ print $1 }')
echo "compiled size: $pre_size"
wasm-bindgen target/wasm32-unknown-unknown/${TYPE}/ytbn_graphing_software.wasm --out-dir pkg --target web --no-typescript
if test "$TYPE" == "release"; then
echo "running wasm-opt..."
time wasm-opt --converge -Oz --code-folding --const-hoisting --coalesce-locals-learning --vacuum --merge-locals --merge-blocks --fast-math --precompute --rse --low-memory-unused --once-reduction --optimize-instructions --licm --intrinsic-lowering \
--dce --dae-optimizing --inlining-optimizing --strip-debug \
-o pkg/ytbn_graphing_software_bg_2.wasm pkg/ytbn_graphing_software_bg.wasm
mv pkg/ytbn_graphing_software_bg_2.wasm pkg/ytbn_graphing_software_bg.wasm
fi
mkdir tmp
cp -r pkg/ytbn_graphing_software_bg.wasm tmp/
sed -i 's/fatal: true/fatal: false/g' pkg/ytbn_graphing_software.js
sed -i "s/TextEncoder('utf-8')/TextEncoder('utf-8', { ignoreBOM: true, fatal: false })/g" pkg/ytbn_graphing_software.js
#minify pkg/ytbn_graphing_software.js > tmp/ytbn_graphing_software.js
cp www/* tmp/
cp assets/logo.svg tmp/
#minify www/index.html > tmp/index.html
#minify www/sw.js > tmp/sw.js
cp www/index.html www/sw.js pkg/ytbn_graphing_software.js tmp/
wasm_sum=($(md5sum tmp/ytbn_graphing_software_bg.wasm))
js_sum=($(md5sum tmp/ytbn_graphing_software.js))
sum=($(echo "$wasm_sum $js_sum" | md5sum))
echo "sum: $sum"
new_wasm_name="${sum}.wasm"
new_js_name="${sum}.js"
mv tmp/ytbn_graphing_software_bg.wasm "tmp/${new_wasm_name}"
mv tmp/ytbn_graphing_software.js "tmp/${new_js_name}"
sed -i "s/ytbn_graphing_software_bg.wasm/${new_wasm_name}/g" tmp/*.*
sed -i "s/ytbn_graphing_software.js/${new_js_name}/g" tmp/*.*
new_size=$(du -b tmp/${new_wasm_name} | awk '{ print $1 }')
diff=$(echo "scale=5 ; $new_size / $pre_size" | bc)
percent=$(echo "scale=5 ; (1-$diff)*100" | bc)
echo "Total size: $(du -sb tmp)"
echo "Binary size: $new_size reduced: $percent%"

100
flake.lock generated
View File

@ -1,100 +0,0 @@
{
"nodes": {
"flake-utils": {
"inputs": {
"systems": "systems"
},
"locked": {
"lastModified": 1731533236,
"narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "11707dc2f618dd54ca8739b309ec4fc024de578b",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1764517877,
"narHash": "sha256-pp3uT4hHijIC8JUK5MEqeAWmParJrgBVzHLNfJDZxg4=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "2d293cbfa5a793b4c50d17c05ef9e385b90edf6c",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"flake-utils": "flake-utils",
"nixpkgs": "nixpkgs",
"rust-overlay": "rust-overlay",
"simon-egui": "simon-egui"
}
},
"rust-overlay": {
"inputs": {
"nixpkgs": [
"nixpkgs"
]
},
"locked": {
"lastModified": 1764729618,
"narHash": "sha256-z4RA80HCWv2los1KD346c+PwNPzMl79qgl7bCVgz8X0=",
"owner": "oxalica",
"repo": "rust-overlay",
"rev": "52764074a85145d5001bf0aa30cb71936e9ad5b8",
"type": "github"
},
"original": {
"owner": "oxalica",
"repo": "rust-overlay",
"type": "github"
}
},
"simon-egui": {
"flake": false,
"locked": {
"lastModified": 1764730109,
"narHash": "sha256-vNETC0oq6tKJKF8KOGQKKIWRom38m0RwGgi3MPBrRx8=",
"owner": "Titaniumtown",
"repo": "egui",
"rev": "b63c21d70150f1b414370f0f9a8af56e886662f4",
"type": "github"
},
"original": {
"owner": "Titaniumtown",
"repo": "egui",
"rev": "b63c21d70150f1b414370f0f9a8af56e886662f4",
"type": "github"
}
},
"systems": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
}
},
"root": "root",
"version": 7
}

225
flake.nix
View File

@ -1,225 +0,0 @@
{
description = "YTBN Graphing Software - Web-compatible graphing calculator";
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
flake-utils.url = "github:numtide/flake-utils";
rust-overlay = {
url = "github:oxalica/rust-overlay";
inputs.nixpkgs.follows = "nixpkgs";
};
simon-egui = {
url = "github:Titaniumtown/egui/b63c21d70150f1b414370f0f9a8af56e886662f4";
flake = false;
};
};
outputs = { self, nixpkgs, flake-utils, rust-overlay, simon-egui }:
flake-utils.lib.eachDefaultSystem (system:
let
overlays = [ (import rust-overlay) ];
pkgs = import nixpkgs {
inherit system overlays;
};
# Use nightly rust with wasm32 target
rustToolchain = pkgs.rust-bin.nightly."2025-05-01".default.override {
targets = [ "wasm32-unknown-unknown" ];
};
rustPlatform = pkgs.makeRustPlatform {
cargo = rustToolchain;
rustc = rustToolchain;
};
# Build wasm-bindgen-cli matching the version in Cargo.lock (0.2.106)
wasm-bindgen-cli = rustPlatform.buildRustPackage rec {
pname = "wasm-bindgen-cli";
version = "0.2.106";
src = pkgs.fetchCrate {
inherit pname version;
hash = "sha256-M6WuGl7EruNopHZbqBpucu4RWz44/MSdv6f0zkYw+44=";
};
cargoHash = "sha256-ElDatyOwdKwHg3bNH/1pcxKI7LXkhsotlDPQjiLHBwA=";
nativeBuildInputs = [ pkgs.pkg-config ];
buildInputs = [ pkgs.openssl ] ++ pkgs.lib.optionals pkgs.stdenv.isDarwin [
pkgs.curl
pkgs.darwin.apple_sdk.frameworks.Security
];
# Tests require network access
doCheck = false;
};
# Create a combined source with the main project and dependencies
combinedSrc = pkgs.stdenv.mkDerivation {
name = "ytbn-combined-src";
phases = [ "installPhase" ];
installPhase = ''
mkdir -p $out/integral_site_rust
mkdir -p $out/simon-egui
cp -r ${./.}/* $out/integral_site_rust/
cp -r ${simon-egui}/* $out/simon-egui/
chmod -R u+w $out
'';
};
# Build the wasm library using rustPlatform
wasmLib = rustPlatform.buildRustPackage {
pname = "ytbn-graphing-software-wasm";
version = "0.1.0";
src = combinedSrc;
sourceRoot = "${combinedSrc.name}/integral_site_rust";
cargoLock = {
lockFile = ./Cargo.lock;
outputHashes = {
"egui_plot-0.34.0" = "sha256-lk0yeljsvkHzF0eLD5llQ+05DycPqG2jGzhBvQ0X6Qw=";
};
};
nativeBuildInputs = with pkgs; [
python3Packages.fonttools
pkg-config
clang
];
buildInputs = with pkgs; [
openssl
zstd
];
buildPhase = ''
runHook preBuild
export HOME=$TMPDIR
cargo build \
--release \
--lib \
--target wasm32-unknown-unknown
runHook postBuild
'';
installPhase = ''
runHook preInstall
mkdir -p $out/lib
cp target/wasm32-unknown-unknown/release/*.wasm $out/lib/
runHook postInstall
'';
doCheck = false;
};
# Final web package with wasm-bindgen processing
ytbn-graphing-software-web = pkgs.stdenv.mkDerivation {
pname = "ytbn-graphing-software-web";
version = "0.1.0";
src = ./.;
nativeBuildInputs = [
wasm-bindgen-cli
pkgs.binaryen
];
buildPhase = ''
runHook preBuild
# Generate JS bindings
wasm-bindgen ${wasmLib}/lib/ytbn_graphing_software.wasm \
--out-dir out \
--out-name ytbn_graphing_software \
--target web \
--no-typescript
# Optimize wasm (enable features used by modern rust wasm targets)
wasm-opt out/ytbn_graphing_software_bg.wasm \
-O2 --fast-math \
--enable-bulk-memory \
--enable-nontrapping-float-to-int \
--enable-sign-ext \
--enable-mutable-globals \
-o out/ytbn_graphing_software_bg.wasm
runHook postBuild
'';
installPhase = ''
runHook preInstall
mkdir -p $out
# Copy wasm and js files
cp out/ytbn_graphing_software_bg.wasm $out/
cp out/ytbn_graphing_software.js $out/
# Copy static web assets
cp www/index.html $out/
cp www/manifest.json $out/
cp www/sw.js $out/
# Copy logo
cp assets/logo.svg $out/
runHook postInstall
'';
meta = with pkgs.lib; {
description = "Web-compatible graphing calculator similar to Desmos";
homepage = "https://github.com/Titaniumtown/YTBN-Graphing-Software";
license = licenses.agpl3Only;
platforms = platforms.all;
};
};
in
{
packages = {
default = ytbn-graphing-software-web;
web = ytbn-graphing-software-web;
wasm = wasmLib;
};
devShells.default = pkgs.mkShell {
nativeBuildInputs = with pkgs; [
rustToolchain
wasm-bindgen-cli
binaryen
python3Packages.fonttools
rust-analyzer
pkg-config
clang
# Runtime deps for native builds
libxkbcommon
libGL
wayland
xorg.libX11
xorg.libXcursor
xorg.libXi
];
buildInputs = with pkgs; [
openssl
zstd
];
LD_LIBRARY_PATH = pkgs.lib.makeLibraryPath (with pkgs; [
libxkbcommon
libGL
wayland
xorg.libX11
xorg.libXcursor
xorg.libXi
]);
};
}
);
}

View File

@ -1,4 +1,4 @@
use std::hint::unreachable_unchecked; use std::{hint::unreachable_unchecked, intrinsics::assume};
use crate::{generate_hint, Hint, HINT_EMPTY}; use crate::{generate_hint, Hint, HINT_EMPTY};
@ -18,7 +18,7 @@ impl Movement {
pub const fn is_complete(&self) -> bool { matches!(&self, &Self::Complete) } pub const fn is_complete(&self) -> bool { matches!(&self, &Self::Complete) }
} }
impl Default for Movement { impl const Default for Movement {
fn default() -> Self { Self::None } fn default() -> Self { Self::None }
} }
@ -29,7 +29,7 @@ pub struct AutoComplete<'a> {
pub string: String, pub string: String,
} }
impl<'a> Default for AutoComplete<'a> { impl<'a> const Default for AutoComplete<'a> {
fn default() -> AutoComplete<'a> { AutoComplete::EMPTY } fn default() -> AutoComplete<'a> { AutoComplete::EMPTY }
} }
@ -70,6 +70,12 @@ impl<'a> AutoComplete<'a> {
// Impossible for plural hints to be singular or non-existant // Impossible for plural hints to be singular or non-existant
debug_assert!(hints.len() > 1); // check on debug debug_assert!(hints.len() > 1); // check on debug
// Hint to the compiler
unsafe {
assume(hints.len() > 1);
assume(!hints.is_empty());
}
match movement { match movement {
Movement::Up => { Movement::Up => {
// Wrap self.i to maximum `i` value if needed // Wrap self.i to maximum `i` value if needed

View File

@ -1,3 +1,7 @@
#![feature(const_trait_impl)]
#![feature(core_intrinsics)]
#![feature(const_mut_refs)]
#![feature(const_for)]
mod autocomplete; mod autocomplete;
mod autocomplete_hashmap; mod autocomplete_hashmap;
mod parsing; mod parsing;

View File

@ -58,7 +58,7 @@ impl FlatExWrapper {
.as_ref() .as_ref()
.map(|f| { .map(|f| {
f.clone() f.clone()
.partial_iter((0..n).map(|_| 0)) .partial_iter((0..=n).map(|_| 0))
.map(Self::new) .map(Self::new)
.unwrap_or(Self::EMPTY) .unwrap_or(Self::EMPTY)
}) })
@ -66,7 +66,7 @@ impl FlatExWrapper {
} }
} }
impl Default for FlatExWrapper { impl const Default for FlatExWrapper {
fn default() -> FlatExWrapper { FlatExWrapper::EMPTY } fn default() -> FlatExWrapper { FlatExWrapper::EMPTY }
} }
/// Function that includes f(x), f'(x), f'(x)'s string representation, and f''(x) /// Function that includes f(x), f'(x), f'(x)'s string representation, and f''(x)

View File

@ -127,7 +127,6 @@ pub fn split_function_chars(chars: &[char], split: SplitType) -> Vec<String> {
// Append split // Append split
if curr_c.splitable(c, &prev_char, &split) { if curr_c.splitable(c, &prev_char, &split) {
// create new buffer
data.push(String::new()); data.push(String::new());
last = unsafe { data.last_mut().unwrap_unchecked() }; last = unsafe { data.last_mut().unwrap_unchecked() };
} }

View File

@ -1,4 +1,5 @@
use crate::{split_function_chars, SplitType}; use crate::{split_function_chars, SplitType};
use std::intrinsics::assume;
pub const HINT_EMPTY: Hint = Hint::Single("x^2"); pub const HINT_EMPTY: Hint = Hint::Single("x^2");
const HINT_CLOSED_PARENS: Hint = Hint::Single(")"); const HINT_CLOSED_PARENS: Hint = Hint::Single(")");
@ -19,6 +20,10 @@ pub fn generate_hint<'a>(input: &str) -> &'a Hint<'a> {
} else { } else {
let chars: Vec<char> = input.chars().collect::<Vec<char>>(); let chars: Vec<char> = input.chars().collect::<Vec<char>>();
unsafe {
assume(!chars.is_empty());
}
let key = get_last_term(&chars); let key = get_last_term(&chars);
match key { match key {
Some(key) => { Some(key) => {

15
push.sh Executable file
View File

@ -0,0 +1,15 @@
#!/bin/bash
set -e #kill script if error occurs
cargo test
bash build.sh release
echo "rsyncing"
# rsync -av --delete --info=progress2 tmp/ rpi-public:/mnt/hdd/http_share/ytbn/
rsync -av --delete --info=progress2 --exclude=".git" tmp/ ../titaniumtown.github.io/
rm -fr tmp
cd ../titaniumtown.github.io
git add .
git commit -m "update" | true
git push

View File

@ -1,30 +0,0 @@
{
pkgs ? import <nixpkgs> { },
}:
pkgs.mkShell rec {
libs = with pkgs; [
# wayland
libxkbcommon
libGL
wayland
libx11
libxcursor
libxi
clang
];
nativeBuildInputs =
with pkgs;
[
rustc
cargo
rust-analyzer
python3Packages.fonttools
]
++ libs;
# add libs to path
LD_LIBRARY_PATH = "${pkgs.lib.makeLibraryPath libs}";
}

View File

@ -5,13 +5,13 @@ shadow!(build);
/// Constant string that has a string containing information about the build. /// Constant string that has a string containing information about the build.
pub const BUILD_INFO: &str = formatc!( pub const BUILD_INFO: &str = formatc!(
"Commit: {} ({})\nBuild Date: {}\nPackage Version: {}\nRust Channel: {}\nRust Version: {}", "Commit: {} ({})\nBuild Date: {}\nPackage Version: {}\nRust Channel: {}\nRust Version: {}",
&build::SHORT_COMMIT, &build::SHORT_COMMIT,
&build::BRANCH, &build::BRANCH,
&build::BUILD_TIME, &build::BUILD_TIME,
&build::PKG_VERSION, &build::PKG_VERSION,
&build::RUST_CHANNEL, &build::RUST_CHANNEL,
&build::RUST_VERSION, &build::RUST_VERSION,
); );
pub const FONT_SIZE: f32 = 14.0; pub const FONT_SIZE: f32 = 14.0;
@ -31,24 +31,24 @@ pub const DEFAULT_INTEGRAL_NUM: usize = 100;
/// Colors used for plotting /// Colors used for plotting
// Colors commented out are used elsewhere and are not included here for better user experience // Colors commented out are used elsewhere and are not included here for better user experience
pub const COLORS: [Color32; 13] = [ pub const COLORS: [Color32; 13] = [
Color32::RED, Color32::RED,
// Color32::GREEN, // Color32::GREEN,
// Color32::YELLOW, // Color32::YELLOW,
// Color32::BLUE, // Color32::BLUE,
Color32::BROWN, Color32::BROWN,
Color32::GOLD, Color32::GOLD,
Color32::GRAY, Color32::GRAY,
Color32::WHITE, Color32::WHITE,
Color32::LIGHT_YELLOW, Color32::LIGHT_YELLOW,
Color32::LIGHT_GREEN, Color32::LIGHT_GREEN,
// Color32::LIGHT_BLUE, // Color32::LIGHT_BLUE,
Color32::LIGHT_GRAY, Color32::LIGHT_GRAY,
Color32::LIGHT_RED, Color32::LIGHT_RED,
Color32::DARK_GRAY, Color32::DARK_GRAY,
// Color32::DARK_RED, // Color32::DARK_RED,
Color32::KHAKI, Color32::KHAKI,
Color32::DARK_GREEN, Color32::DARK_GREEN,
Color32::DARK_BLUE, Color32::DARK_BLUE,
]; ];
const_assert!(!COLORS.is_empty()); const_assert!(!COLORS.is_empty());

View File

@ -1,523 +1,482 @@
use crate::math_app::AppSettings; use crate::math_app::AppSettings;
use crate::misc::{EguiHelper, newtons_method_helper, step_helper}; use crate::misc::{newtons_method_helper, step_helper, EguiHelper};
use egui::{Checkbox, Context}; use egui::{Checkbox, Context};
use egui_plot::{Bar, BarChart, PlotPoint, PlotUi}; use egui_plot::{Bar, BarChart, PlotPoint, PlotUi};
use epaint::Color32; use epaint::Color32;
use parsing::{AutoComplete, generate_hint}; use parsing::{generate_hint, AutoComplete};
use parsing::{BackingFunction, process_func_str}; use parsing::{process_func_str, BackingFunction};
use serde::{Deserialize, Deserializer, Serialize, Serializer, ser::SerializeStruct}; use serde::{ser::SerializeStruct, Deserialize, Deserializer, Serialize, Serializer};
use std::{ use std::{
fmt::{self, Debug}, fmt::{self, Debug},
hash::{Hash, Hasher}, hash::{Hash, Hasher},
intrinsics::assume,
}; };
/// Represents the possible variations of Riemann Sums /// Represents the possible variations of Riemann Sums
#[derive(PartialEq, Eq, Debug, Copy, Clone, Default)] #[derive(PartialEq, Eq, Debug, Copy, Clone, Default)]
pub enum Riemann { pub enum Riemann {
#[default] #[default]
Left, Left,
Middle, Middle,
Right, Right,
} }
impl fmt::Display for Riemann { impl fmt::Display for Riemann {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self) }
write!(f, "{:?}", self)
}
} }
/// `FunctionEntry` is a function that can calculate values, integrals, derivatives, etc etc /// `FunctionEntry` is a function that can calculate values, integrals, derivatives, etc etc
#[derive(Clone)] #[derive(Clone)]
pub struct FunctionEntry { pub struct FunctionEntry {
/// The `BackingFunction` instance that is used to generate `f(x)`, `f'(x)`, and `f''(x)` /// The `BackingFunction` instance that is used to generate `f(x)`, `f'(x)`, and `f''(x)`
function: BackingFunction, function: BackingFunction,
/// Stores a function string (that hasn't been processed via `process_func_str`) to display to the user /// Stores a function string (that hasn't been processed via `process_func_str`) to display to the user
pub raw_func_str: String, pub raw_func_str: String,
/// If calculating/displayingintegrals are enabled /// If calculating/displayingintegrals are enabled
pub integral: bool, pub integral: bool,
/// If displaying derivatives are enabled (note, they are still calculated for other purposes) /// If displaying derivatives are enabled (note, they are still calculated for other purposes)
pub derivative: bool, pub derivative: bool,
pub nth_derviative: bool, pub nth_derviative: bool,
/// If the function is visible on the graph pub back_data: Vec<PlotPoint>,
pub visible: bool, pub integral_data: Option<(Vec<Bar>, f64)>,
pub derivative_data: Vec<PlotPoint>,
pub extrema_data: Vec<PlotPoint>,
pub root_data: Vec<PlotPoint>,
nth_derivative_data: Option<Vec<PlotPoint>>,
pub back_data: Vec<PlotPoint>, pub autocomplete: AutoComplete<'static>,
pub integral_data: Option<(Vec<Bar>, f64)>,
pub derivative_data: Vec<PlotPoint>,
pub extrema_data: Vec<PlotPoint>,
pub root_data: Vec<PlotPoint>,
nth_derivative_data: Option<Vec<PlotPoint>>,
pub autocomplete: AutoComplete<'static>, test_result: Option<String>,
curr_nth: usize,
test_result: Option<String>, pub settings_opened: bool,
curr_nth: usize,
pub settings_opened: bool,
} }
impl Hash for FunctionEntry { impl Hash for FunctionEntry {
fn hash<H: Hasher>(&self, state: &mut H) { fn hash<H: Hasher>(&self, state: &mut H) {
self.raw_func_str.hash(state); self.raw_func_str.hash(state);
self.integral.hash(state); self.integral.hash(state);
self.nth_derviative.hash(state); self.nth_derviative.hash(state);
self.curr_nth.hash(state); self.curr_nth.hash(state);
self.settings_opened.hash(state); self.settings_opened.hash(state);
self.visible.hash(state); }
}
} }
impl Serialize for FunctionEntry { impl Serialize for FunctionEntry {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where where
S: Serializer, S: Serializer,
{ {
let mut s = serializer.serialize_struct("FunctionEntry", 5)?; let mut s = serializer.serialize_struct("FunctionEntry", 4)?;
s.serialize_field("raw_func_str", &self.raw_func_str)?; s.serialize_field("raw_func_str", &self.raw_func_str)?;
s.serialize_field("integral", &self.integral)?; s.serialize_field("integral", &self.integral)?;
s.serialize_field("derivative", &self.derivative)?; s.serialize_field("derivative", &self.derivative)?;
s.serialize_field("curr_nth", &self.curr_nth)?; s.serialize_field("curr_nth", &self.curr_nth)?;
s.serialize_field("visible", &self.visible)?;
s.end() s.end()
} }
} }
impl<'de> Deserialize<'de> for FunctionEntry { impl<'de> Deserialize<'de> for FunctionEntry {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where where
D: Deserializer<'de>, D: Deserializer<'de>,
{ {
#[derive(Deserialize)] #[derive(Deserialize)]
struct Helper { struct Helper {
raw_func_str: String, raw_func_str: String,
integral: bool, integral: bool,
derivative: bool, derivative: bool,
curr_nth: usize, curr_nth: usize,
#[serde(default = "default_visible")] }
visible: bool,
}
fn default_visible() -> bool { let helper = Helper::deserialize(deserializer)?;
true let mut new_func_entry = FunctionEntry::default();
} let gen_func = BackingFunction::new(&helper.raw_func_str);
match gen_func {
Ok(func) => new_func_entry.function = func,
Err(x) => new_func_entry.test_result = Some(x),
}
let helper = Helper::deserialize(deserializer)?; new_func_entry.autocomplete = AutoComplete {
let mut new_func_entry = FunctionEntry::default(); i: 0,
let gen_func = BackingFunction::new(&helper.raw_func_str); hint: generate_hint(&helper.raw_func_str),
match gen_func { string: helper.raw_func_str,
Ok(func) => new_func_entry.function = func, };
Err(x) => new_func_entry.test_result = Some(x),
}
new_func_entry.autocomplete = AutoComplete { new_func_entry.integral = helper.integral;
i: 0, new_func_entry.derivative = helper.derivative;
hint: generate_hint(&helper.raw_func_str), new_func_entry.curr_nth = helper.curr_nth;
string: helper.raw_func_str,
};
new_func_entry.integral = helper.integral; Ok(new_func_entry)
new_func_entry.derivative = helper.derivative; }
new_func_entry.curr_nth = helper.curr_nth;
new_func_entry.visible = helper.visible;
Ok(new_func_entry)
}
} }
impl Default for FunctionEntry { impl const Default for FunctionEntry {
/// Creates default FunctionEntry instance (which is empty) /// Creates default FunctionEntry instance (which is empty)
fn default() -> FunctionEntry { fn default() -> FunctionEntry {
FunctionEntry { FunctionEntry {
function: BackingFunction::default(), function: BackingFunction::default(),
raw_func_str: String::new(), raw_func_str: String::new(),
integral: false, integral: false,
derivative: false, derivative: false,
nth_derviative: false, nth_derviative: false,
visible: true, back_data: Vec::new(),
back_data: Vec::new(), integral_data: None,
integral_data: None, derivative_data: Vec::new(),
derivative_data: Vec::new(), extrema_data: Vec::new(),
extrema_data: Vec::new(), root_data: Vec::new(),
root_data: Vec::new(), nth_derivative_data: None,
nth_derivative_data: None, autocomplete: AutoComplete::EMPTY,
autocomplete: AutoComplete::EMPTY, test_result: None,
test_result: None, curr_nth: 3,
curr_nth: 3, settings_opened: false,
settings_opened: false, }
} }
}
} }
impl FunctionEntry { impl FunctionEntry {
pub const fn is_some(&self) -> bool { pub const fn is_some(&self) -> bool { !self.function.is_none() }
!self.function.is_none()
}
pub fn settings_window(&mut self, ctx: &Context) { pub fn settings_window(&mut self, ctx: &Context) {
let mut invalidate_nth = false; let mut invalidate_nth = false;
egui::Window::new(format!("Settings: {}", self.raw_func_str)) egui::Window::new(format!("Settings: {}", self.raw_func_str))
.open(&mut self.settings_opened) .open(&mut self.settings_opened)
.default_pos([200.0, 200.0]) .default_pos([200.0, 200.0])
.resizable(false) .resizable(false)
.collapsible(false) .collapsible(false)
.show(ctx, |ui| { .show(ctx, |ui| {
ui.add(Checkbox::new( ui.add(Checkbox::new(
&mut self.nth_derviative, &mut self.nth_derviative,
"Display Nth Derivative", "Display Nth Derivative",
)); ));
if ui if ui
.add(egui::Slider::new(&mut self.curr_nth, 3..=5).text("Nth Derivative")) .add(egui::Slider::new(&mut self.curr_nth, 3..=5).text("Nth Derivative"))
.changed() .changed()
{ {
invalidate_nth = true; invalidate_nth = true;
} }
}); });
if invalidate_nth { if invalidate_nth {
self.function.generate_derivative(self.curr_nth); self.function.generate_derivative(self.curr_nth);
self.clear_nth(); self.clear_nth();
} }
} }
/// Get function's cached test result /// Get function's cached test result
pub fn get_test_result(&self) -> &Option<String> { pub fn get_test_result(&self) -> &Option<String> { &self.test_result }
&self.test_result
}
/// Update function string and test it /// Update function string and test it
pub fn update_string(&mut self, raw_func_str: &str) { pub fn update_string(&mut self, raw_func_str: &str) {
if raw_func_str == self.raw_func_str { if raw_func_str == self.raw_func_str {
return; return;
} }
self.raw_func_str = raw_func_str.to_owned(); self.raw_func_str = raw_func_str.to_owned();
let processed_func = process_func_str(raw_func_str); let processed_func = process_func_str(raw_func_str);
let new_func_result = BackingFunction::new(&processed_func); let new_func_result = BackingFunction::new(&processed_func);
match new_func_result { match new_func_result {
Ok(new_function) => { Ok(new_function) => {
self.test_result = None; self.test_result = None;
self.function = new_function; self.function = new_function;
self.invalidate_whole(); self.invalidate_whole();
} }
Err(error) => { Err(error) => {
self.test_result = Some(error); self.test_result = Some(error);
} }
} }
} }
/// Creates and does the math for creating all the rectangles under the graph /// Creates and does the math for creating all the rectangles under the graph
fn integral_rectangles( fn integral_rectangles(
&mut self, &mut self, integral_min_x: f64, integral_max_x: f64, sum: Riemann, integral_num: usize,
integral_min_x: f64, ) -> (Vec<(f64, f64)>, f64) {
integral_max_x: f64, let step = (integral_max_x - integral_min_x) / (integral_num as f64);
sum: Riemann,
integral_num: usize,
) -> (Vec<(f64, f64)>, f64) {
let step = (integral_max_x - integral_min_x) / (integral_num as f64);
// let sum_func = self.get_sum_func(sum); // let sum_func = self.get_sum_func(sum);
let data2: Vec<(f64, f64)> = step_helper(integral_num, integral_min_x, step) let data2: Vec<(f64, f64)> = step_helper(integral_num, integral_min_x, step)
.into_iter() .into_iter()
.map(|x| { .map(|x| {
let step_offset = step.copysign(x); // store the offset here so it doesn't have to be calculated multiple times let step_offset = step.copysign(x); // store the offset here so it doesn't have to be calculated multiple times
let x2: f64 = x + step_offset; let x2: f64 = x + step_offset;
let (left_x, right_x) = match x.is_sign_positive() { let (left_x, right_x) = match x.is_sign_positive() {
true => (x, x2), true => (x, x2),
false => (x2, x), false => (x2, x),
}; };
let y = match sum { let y = match sum {
Riemann::Left => self.function.get(0, left_x), Riemann::Left => self.function.get(0, left_x),
Riemann::Right => self.function.get(0, right_x), Riemann::Right => self.function.get(0, right_x),
Riemann::Middle => { Riemann::Middle => {
(self.function.get(0, left_x) + self.function.get(0, right_x)) / 2.0 (self.function.get(0, left_x) + self.function.get(0, right_x)) / 2.0
} }
}; };
(x + (step_offset / 2.0), y) (x + (step_offset / 2.0), y)
}) })
.filter(|(_, y)| y.is_finite()) .filter(|(_, y)| y.is_finite())
.collect(); .collect();
let area = data2.iter().map(move |(_, y)| y * step).sum(); let area = data2.iter().map(move |(_, y)| y * step).sum();
(data2, area) (data2, area)
} }
/// Helps with processing newton's method depending on level of derivative /// Helps with processing newton's method depending on level of derivative
fn newtons_method_helper( fn newtons_method_helper(
&mut self, &mut self, threshold: f64, derivative_level: usize, range: &std::ops::Range<f64>,
threshold: f64, ) -> Vec<PlotPoint> {
derivative_level: usize, self.function.generate_derivative(derivative_level);
range: &std::ops::Range<f64>, self.function.generate_derivative(derivative_level + 1);
) -> Vec<PlotPoint> { let newtons_method_output: Vec<f64> = match derivative_level {
self.function.generate_derivative(derivative_level); 0 => newtons_method_helper(
self.function.generate_derivative(derivative_level + 1); threshold,
let newtons_method_output: Vec<f64> = match derivative_level { range,
0 => newtons_method_helper( self.back_data.as_slice(),
threshold, &self.function.get_function_derivative(0),
range, &self.function.get_function_derivative(1),
self.back_data.as_slice(), ),
self.function.get_function_derivative(0), 1 => newtons_method_helper(
self.function.get_function_derivative(1), threshold,
), range,
1 => newtons_method_helper( self.derivative_data.as_slice(),
threshold, &self.function.get_function_derivative(1),
range, &self.function.get_function_derivative(2),
self.derivative_data.as_slice(), ),
self.function.get_function_derivative(1), _ => unreachable!(),
self.function.get_function_derivative(2), };
),
_ => unreachable!(),
};
newtons_method_output newtons_method_output
.into_iter() .into_iter()
.map(|x| PlotPoint::new(x, self.function.get(0, x))) .map(|x| PlotPoint::new(x, self.function.get(0, x)))
.collect() .collect()
} }
/// Does the calculations and stores results in `self` /// Does the calculations and stores results in `self`
pub fn calculate( pub fn calculate(
&mut self, &mut self, width_changed: bool, min_max_changed: bool, did_zoom: bool,
width_changed: bool, settings: AppSettings,
min_max_changed: bool, ) {
did_zoom: bool, if self.test_result.is_some() | self.function.is_none() {
settings: AppSettings, return;
) { }
if self.test_result.is_some() | self.function.is_none() {
return;
}
let resolution = (settings.max_x - settings.min_x) / (settings.plot_width as f64); let resolution = (settings.max_x - settings.min_x) / (settings.plot_width as f64);
debug_assert!(resolution > 0.0); debug_assert!(resolution > 0.0);
let resolution_iter = step_helper(settings.plot_width + 1, settings.min_x, resolution); let resolution_iter = step_helper(settings.plot_width + 1, settings.min_x, resolution);
// Makes sure proper arguments are passed when integral is enabled unsafe { assume(!resolution_iter.is_empty()) }
if self.integral && settings.integral_changed {
self.clear_integral();
}
if width_changed | min_max_changed | did_zoom { // Makes sure proper arguments are passed when integral is enabled
self.clear_back(); if self.integral && settings.integral_changed {
self.clear_derivative(); self.clear_integral();
self.clear_nth(); }
}
if self.back_data.is_empty() { if width_changed | min_max_changed | did_zoom {
let data: Vec<PlotPoint> = resolution_iter self.clear_back();
.clone() self.clear_derivative();
.into_iter() self.clear_nth();
.map(|x| PlotPoint::new(x, self.function.get(0, x))) }
.collect();
debug_assert_eq!(data.len(), settings.plot_width + 1);
self.back_data = data; if self.back_data.is_empty() {
} let data: Vec<PlotPoint> = resolution_iter
.clone()
.into_iter()
.map(|x| PlotPoint::new(x, self.function.get(0, x)))
.collect();
debug_assert_eq!(data.len(), settings.plot_width + 1);
if self.derivative_data.is_empty() { self.back_data = data;
self.function.generate_derivative(1); }
let data: Vec<PlotPoint> = resolution_iter
.clone()
.into_iter()
.map(|x| PlotPoint::new(x, self.function.get(1, x)))
.collect();
debug_assert_eq!(data.len(), settings.plot_width + 1);
self.derivative_data = data;
}
if self.nth_derviative && self.nth_derivative_data.is_none() { if self.derivative_data.is_empty() {
let data: Vec<PlotPoint> = resolution_iter self.function.generate_derivative(1);
.into_iter() let data: Vec<PlotPoint> = resolution_iter
.map(|x| PlotPoint::new(x, self.function.get(self.curr_nth, x))) .clone()
.collect(); .into_iter()
debug_assert_eq!(data.len(), settings.plot_width + 1); .map(|x| PlotPoint::new(x, self.function.get(1, x)))
self.nth_derivative_data = Some(data); .collect();
} debug_assert_eq!(data.len(), settings.plot_width + 1);
self.derivative_data = data;
}
if self.integral { if self.nth_derviative && self.nth_derivative_data.is_none() {
if self.integral_data.is_none() { let data: Vec<PlotPoint> = resolution_iter
let (data, area) = self.integral_rectangles( .into_iter()
settings.integral_min_x, .map(|x| PlotPoint::new(x, self.function.get(self.curr_nth, x)))
settings.integral_max_x, .collect();
settings.riemann_sum, debug_assert_eq!(data.len(), settings.plot_width + 1);
settings.integral_num, self.nth_derivative_data = Some(data);
); }
self.integral_data = Some(( if self.integral {
data.into_iter().map(|(x, y)| Bar::new(x, y)).collect(), if self.integral_data.is_none() {
area, let (data, area) = self.integral_rectangles(
)); settings.integral_min_x,
} settings.integral_max_x,
} else { settings.riemann_sum,
self.clear_integral(); settings.integral_num,
} );
let threshold: f64 = resolution / 2.0; self.integral_data = Some((
let x_range = settings.min_x..settings.max_x; data.into_iter().map(|(x, y)| Bar::new(x, y)).collect(),
area,
));
}
} else {
self.clear_integral();
}
// Calculates extrema let threshold: f64 = resolution / 2.0;
if settings.do_extrema && (min_max_changed | self.extrema_data.is_empty()) { let x_range = settings.min_x..settings.max_x;
self.extrema_data = self.newtons_method_helper(threshold, 1, &x_range);
}
// Calculates roots // Calculates extrema
if settings.do_roots && (min_max_changed | self.root_data.is_empty()) { if settings.do_extrema && (min_max_changed | self.extrema_data.is_empty()) {
self.root_data = self.newtons_method_helper(threshold, 0, &x_range); self.extrema_data = self.newtons_method_helper(threshold, 1, &x_range);
} }
}
/// Displays the function's output on PlotUI `plot_ui` with settings `settings`. // Calculates roots
/// Returns an `Option<f64>` of the calculated integral. if settings.do_roots && (min_max_changed | self.root_data.is_empty()) {
pub fn display( self.root_data = self.newtons_method_helper(threshold, 0, &x_range);
&self, }
plot_ui: &mut PlotUi, }
settings: &AppSettings,
main_plot_color: Color32,
) -> Option<f64> {
if self.test_result.is_some() | self.function.is_none() | !self.visible {
return None;
}
let integral_step = /// Displays the function's output on PlotUI `plot_ui` with settings `settings`.
(settings.integral_max_x - settings.integral_min_x) / (settings.integral_num as f64); /// Returns an `Option<f64>` of the calculated integral.
debug_assert!(integral_step > 0.0); pub fn display(
&self, plot_ui: &mut PlotUi, settings: &AppSettings, main_plot_color: Color32,
) -> Option<f64> {
if self.test_result.is_some() | self.function.is_none() {
return None;
}
let step = (settings.max_x - settings.min_x) / (settings.plot_width as f64); let integral_step =
debug_assert!(step > 0.0); (settings.integral_max_x - settings.integral_min_x) / (settings.integral_num as f64);
debug_assert!(integral_step > 0.0);
// Plot back data let step = (settings.max_x - settings.min_x) / (settings.plot_width as f64);
if !self.back_data.is_empty() { debug_assert!(step > 0.0);
if self.integral && (step >= integral_step) {
plot_ui.line(
self.back_data
.iter()
.filter(|value| {
(value.x > settings.integral_min_x)
&& (settings.integral_max_x > value.x)
})
.cloned()
.collect::<Vec<PlotPoint>>()
.to_line()
.stroke((0.0, Color32::TRANSPARENT))
.color(Color32::from_rgb(4, 4, 255))
.fill(0.0),
);
}
plot_ui.line(
self.back_data
.clone()
.to_line()
.stroke((4.0, main_plot_color)),
);
}
// Plot derivative data // Plot back data
if self.derivative && !self.derivative_data.is_empty() { if !self.back_data.is_empty() {
plot_ui.line(self.derivative_data.clone().to_line().color(Color32::GREEN)); if self.integral && (step >= integral_step) {
} plot_ui.line(
self.back_data
.iter()
.filter(|value| {
(value.x > settings.integral_min_x)
&& (settings.integral_max_x > value.x)
})
.cloned()
.collect::<Vec<PlotPoint>>()
.to_line()
.stroke(epaint::Stroke::NONE)
.color(Color32::from_rgb(4, 4, 255))
.fill(0.0),
);
}
plot_ui.line(
self.back_data
.clone()
.to_line()
.stroke(egui::Stroke::new(4.0, main_plot_color)),
);
}
// Plot extrema points // Plot derivative data
if settings.do_extrema && !self.extrema_data.is_empty() { if self.derivative && !self.derivative_data.is_empty() {
plot_ui.points( plot_ui.line(self.derivative_data.clone().to_line().color(Color32::GREEN));
self.extrema_data }
.clone()
.to_points()
.color(Color32::YELLOW)
.radius(5.0), // Radius of points of Extrema
);
}
// Plot roots points // Plot extrema points
if settings.do_roots && !self.root_data.is_empty() { if settings.do_extrema && !self.extrema_data.is_empty() {
plot_ui.points( plot_ui.points(
self.root_data self.extrema_data
.clone() .clone()
.to_points() .to_points()
.color(Color32::LIGHT_BLUE) .color(Color32::YELLOW)
.radius(5.0), // Radius of points of Roots .radius(5.0), // Radius of points of Extrema
); );
} }
if self.nth_derviative // Plot roots points
&& let Some(ref nth_derviative) = self.nth_derivative_data if settings.do_roots && !self.root_data.is_empty() {
{ plot_ui.points(
plot_ui.line(nth_derviative.clone().to_line().color(Color32::DARK_RED)); self.root_data
} .clone()
.to_points()
.color(Color32::LIGHT_BLUE)
.radius(5.0), // Radius of points of Roots
);
}
// Plot integral data if self.nth_derviative
match &self.integral_data { && let Some(ref nth_derviative) = self.nth_derivative_data
Some(integral_data) => { {
if integral_step > step { plot_ui.line(nth_derviative.clone().to_line().color(Color32::DARK_RED));
plot_ui.bar_chart( }
BarChart::new("integral", integral_data.0.clone())
.color(Color32::BLUE)
.width(integral_step),
);
}
// return value rounded to 8 decimal places // Plot integral data
Some(emath::round_to_decimals(integral_data.1, 8)) match &self.integral_data {
} Some(integral_data) => {
None => None, if integral_step > step {
} plot_ui.bar_chart(
} BarChart::new(integral_data.0.clone())
.color(Color32::BLUE)
.width(integral_step),
);
}
/// Invalidate entire cache // return value rounded to 8 decimal places
fn invalidate_whole(&mut self) { Some(emath::round_to_decimals(integral_data.1, 8))
self.clear_back(); }
self.clear_integral(); None => None,
self.clear_derivative(); }
self.clear_nth(); }
self.clear_extrema();
self.clear_roots();
}
/// Invalidate `back` data /// Invalidate entire cache
#[inline] fn invalidate_whole(&mut self) {
fn clear_back(&mut self) { self.clear_back();
self.back_data.clear(); self.clear_integral();
} self.clear_derivative();
self.clear_nth();
self.clear_extrema();
self.clear_roots();
}
/// Invalidate Integral data /// Invalidate `back` data
#[inline] #[inline]
fn clear_integral(&mut self) { fn clear_back(&mut self) { self.back_data.clear(); }
self.integral_data = None;
}
/// Invalidate Derivative data /// Invalidate Integral data
#[inline] #[inline]
fn clear_derivative(&mut self) { fn clear_integral(&mut self) { self.integral_data = None; }
self.derivative_data.clear();
}
/// Invalidates `n`th derivative data /// Invalidate Derivative data
#[inline] #[inline]
fn clear_nth(&mut self) { fn clear_derivative(&mut self) { self.derivative_data.clear(); }
self.nth_derivative_data = None
}
/// Invalidate extrema data /// Invalidates `n`th derivative data
#[inline] #[inline]
fn clear_extrema(&mut self) { fn clear_nth(&mut self) { self.nth_derivative_data = None }
self.extrema_data.clear()
}
/// Invalidate root data /// Invalidate extrema data
#[inline] #[inline]
fn clear_roots(&mut self) { fn clear_extrema(&mut self) { self.extrema_data.clear() }
self.root_data.clear()
} /// Invalidate root data
#[inline]
fn clear_roots(&mut self) { self.root_data.clear() }
} }

View File

@ -1,10 +1,10 @@
use crate::{ use crate::{
consts::COLORS, consts::COLORS,
function_entry::FunctionEntry, function_entry::FunctionEntry,
misc::{create_id, get_u64_id, random_u64}, misc::{create_id, get_u64_id, random_u64},
widgets::widgets_ontop, widgets::widgets_ontop,
}; };
use egui::{Button, Id, Key, Modifiers, Popup, TextEdit, WidgetText}; use egui::{Button, Id, Key, Modifiers, TextEdit, WidgetText};
use emath::vec2; use emath::vec2;
use parsing::Movement; use parsing::Movement;
use serde::ser::SerializeStruct; use serde::ser::SerializeStruct;
@ -15,350 +15,267 @@ use std::ops::BitXorAssign;
type Functions = Vec<(Id, FunctionEntry)>; type Functions = Vec<(Id, FunctionEntry)>;
pub struct FunctionManager { pub struct FunctionManager {
functions: Functions, functions: Functions,
} }
impl Default for FunctionManager { impl Default for FunctionManager {
fn default() -> Self { fn default() -> Self {
let mut vec: Functions = Vec::with_capacity(COLORS.len()); let mut vec: Functions = Vec::with_capacity(COLORS.len());
vec.push(( vec.push((
create_id(11414819524356497634), // Random number here to avoid call to crate::misc::random_u64() create_id(11414819524356497634), // Random number here to avoid call to crate::misc::random_u64()
FunctionEntry::default(), FunctionEntry::default(),
)); ));
Self { functions: vec } Self { functions: vec }
} }
} }
impl Serialize for FunctionManager { impl Serialize for FunctionManager {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where where
S: Serializer, S: Serializer,
{ {
let mut s = serializer.serialize_struct("FunctionManager", 1)?; let mut s = serializer.serialize_struct("FunctionManager", 1)?;
s.serialize_field( s.serialize_field(
"data", "data",
&self &self
.functions .functions
.iter() .iter()
.map(|(id, func)| (get_u64_id(*id), func.clone())) .map(|(id, func)| (get_u64_id(*id), func.clone()))
.collect::<Vec<(u64, FunctionEntry)>>(), .collect::<Vec<(u64, FunctionEntry)>>(),
)?; )?;
s.end() s.end()
} }
} }
impl<'de> Deserialize<'de> for FunctionManager { impl<'de> Deserialize<'de> for FunctionManager {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where where
D: Deserializer<'de>, D: Deserializer<'de>,
{ {
#[derive(Deserialize)] #[derive(Deserialize)]
struct Helper(Vec<(u64, FunctionEntry)>); struct Helper(Vec<(u64, FunctionEntry)>);
let helper = Helper::deserialize(deserializer)?; let helper = Helper::deserialize(deserializer)?;
Ok(FunctionManager { Ok(FunctionManager {
functions: helper functions: helper
.0 .0
.iter() .iter()
.cloned() .cloned()
.map(|(id, func)| (create_id(id), func)) .map(|(id, func)| (create_id(id), func))
.collect::<Vec<(Id, FunctionEntry)>>(), .collect::<Vec<(Id, FunctionEntry)>>(),
}) })
} }
} }
/// Function that creates button that's used with the `button_area` /// Function that creates button that's used with the `button_area`
fn button_area_button<'a>(text: impl Into<WidgetText>) -> Button<'a> { fn button_area_button<'a>(text: impl Into<WidgetText>) -> Button<'a> {
Button::new(text).frame(false) Button::new(text).frame(false)
} }
impl FunctionManager { impl FunctionManager {
#[inline] #[inline]
fn get_hash(&self) -> u64 { fn get_hash(&self) -> u64 {
let mut hasher = DefaultHasher::new(); let mut hasher = DefaultHasher::new();
self.functions.hash(&mut hasher); self.functions.hash(&mut hasher);
hasher.finish() hasher.finish()
} }
/// Displays function entries alongside returning whether or not functions have been modified /// Displays function entries alongside returning whether or not functions have been modified
pub fn display_entries(&mut self, ui: &mut egui::Ui) -> bool { pub fn display_entries(&mut self, ui: &mut egui::Ui) -> bool {
let initial_hash = self.get_hash(); let initial_hash = self.get_hash();
let can_remove = self.functions.len() > 1; let can_remove = self.functions.len() > 1;
let can_add = self.functions.len() < COLORS.len();
let num_functions = self.functions.len();
let available_width = ui.available_width(); let available_width = ui.available_width();
let mut remove_i: Option<usize> = None; let mut remove_i: Option<usize> = None;
let mut clone_i: Option<usize> = None; let target_size = vec2(available_width, crate::consts::FONT_SIZE);
let mut move_up_i: Option<usize> = None; for (i, (te_id, function)) in self.functions.iter_mut().map(|(a, b)| (*a, b)).enumerate() {
let mut move_down_i: Option<usize> = None; let mut new_string = function.autocomplete.string.clone();
let target_size = vec2(available_width, crate::consts::FONT_SIZE); function.update_string(&new_string);
for (i, (te_id, function)) in self.functions.iter_mut().map(|(a, b)| (*a, b)).enumerate() {
let mut new_string = function.autocomplete.string.clone();
function.update_string(&new_string);
let mut movement: Movement = Movement::default(); let mut movement: Movement = Movement::default();
let size_multiplier = vec2(1.0, { let size_multiplier = vec2(1.0, {
let had_focus = ui.memory(|x| x.has_focus(te_id)); let had_focus = ui.memory(|x| x.has_focus(te_id));
(ui.ctx().animate_bool(te_id, had_focus) * 1.5) + 1.0 (ui.ctx().animate_bool(te_id, had_focus) * 1.5) + 1.0
}); });
let re = ui.add_sized( let re = ui.add_sized(
target_size * size_multiplier, target_size * size_multiplier,
egui::TextEdit::singleline(&mut new_string) egui::TextEdit::singleline(&mut new_string)
.hint_forward(true) // Make the hint appear after the last text in the textbox .hint_forward(true) // Make the hint appear after the last text in the textbox
.lock_focus(true) .lock_focus(true)
.id(te_id) // Set widget's id to `te_id` .id(te_id) // Set widget's id to `te_id`
.hint_text( .hint_text(
// If there's a single hint, go ahead and apply the hint here, if not, set the hint to an empty string // If there's a single hint, go ahead and apply the hint here, if not, set the hint to an empty string
function.autocomplete.hint.single().unwrap_or(""), function.autocomplete.hint.single().unwrap_or(""),
), ),
); );
// Only keep valid chars // Only keep valid chars
new_string.retain(crate::misc::is_valid_char); new_string.retain(crate::misc::is_valid_char);
// Display error indicator with tooltip if there's a parsing error // If not fully open, return here as buttons cannot yet be displayed, therefore the user is inable to mark it for deletion
if let Some(error) = function.get_test_result() { let animate_bool = ui.ctx().animate_bool(te_id, re.has_focus());
ui.horizontal(|ui| { if animate_bool == 1.0 {
ui.label(egui::RichText::new("").color(egui::Color32::YELLOW)) function.autocomplete.update_string(&new_string);
.on_hover_text(error);
ui.label(
egui::RichText::new(error)
.color(egui::Color32::LIGHT_RED)
.small(),
);
});
}
// If not fully open, return here as buttons cannot yet be displayed, therefore the user is inable to mark it for deletion if function.autocomplete.hint.is_some() {
let animate_bool = ui.ctx().animate_bool(te_id, re.has_focus()); // only register up and down arrow movements if hint is type `Hint::Many`
if animate_bool == 1.0 { if !function.autocomplete.hint.is_single() {
function.autocomplete.update_string(&new_string); let (arrow_down, arrow_up) = ui.input(|x| {
(x.key_pressed(Key::ArrowDown), x.key_pressed(Key::ArrowUp))
});
if arrow_down {
movement = Movement::Down;
} else if arrow_up {
movement = Movement::Up;
}
}
if function.autocomplete.hint.is_some() { // Put here so these key presses don't interact with other elements
// only register up and down arrow movements if hint is type `Hint::Many` let movement_complete_action = ui.input_mut(|x| {
if !function.autocomplete.hint.is_single() { x.consume_key(Modifiers::NONE, Key::Enter)
let (arrow_down, arrow_up) = ui.input(|x| { | x.consume_key(Modifiers::NONE, Key::Tab)
(x.key_pressed(Key::ArrowDown), x.key_pressed(Key::ArrowUp)) | x.key_pressed(Key::ArrowRight)
}); });
if arrow_down {
movement = Movement::Down;
} else if arrow_up {
movement = Movement::Up;
}
}
// Put here so these key presses don't interact with other elements if movement_complete_action {
let movement_complete_action = ui.input_mut(|x| { movement = Movement::Complete;
x.consume_key(Modifiers::NONE, Key::Enter) }
| x.consume_key(Modifiers::NONE, Key::Tab)
| x.key_pressed(Key::ArrowRight)
});
if movement_complete_action { // Register movement and apply proper changes
movement = Movement::Complete; function.autocomplete.register_movement(&movement);
}
// Register movement and apply proper changes if movement != Movement::Complete
function.autocomplete.register_movement(&movement); && let Some(hints) = function.autocomplete.hint.many()
{
// Doesn't need to have a number in id as there should only be 1 autocomplete popup in the entire gui
if movement != Movement::Complete // hashed "autocomplete_popup"
&& let Some(hints) = function.autocomplete.hint.many() const POPUP_ID: Id = create_id(7574801616484505465);
{
let mut clicked = false;
let selected_i = function.autocomplete.i;
if let Some(popup_response) = Popup::menu(&re).show(|ui| { let mut clicked = false;
hints.iter().enumerate().for_each(|(i, candidate)| {
if ui.selectable_label(i == selected_i, *candidate).clicked() {
clicked = true;
function.autocomplete.i = i;
}
});
}) && clicked
{
function
.autocomplete
.apply_hint(hints[function.autocomplete.i]);
movement = Movement::Complete;
}
}
// Push cursor to end if needed egui::popup_below_widget(ui, POPUP_ID, &re, |ui| {
if movement == Movement::Complete hints.iter().enumerate().for_each(|(i, candidate)| {
&& let Some(mut state) = TextEdit::load_state(ui.ctx(), te_id) if ui
{ .selectable_label(i == function.autocomplete.i, *candidate)
let ccursor = egui::text::CCursor::new(function.autocomplete.string.len()); .clicked()
state {
.cursor clicked = true;
.set_char_range(Some(egui::text::CCursorRange::one(ccursor))); function.autocomplete.i = i;
TextEdit::store_state(ui.ctx(), te_id, state); }
} });
} });
/// The y offset multiplier of the `buttons_area` area if clicked {
const BUTTONS_Y_OFFSET: f32 = 1.32; function
const Y_OFFSET: f32 = crate::consts::FONT_SIZE * BUTTONS_Y_OFFSET; .autocomplete
.apply_hint(hints[function.autocomplete.i]);
widgets_ontop(ui, create_id(i as u64), &re, Y_OFFSET, |ui| { // Don't need this here as it simply won't be display next frame
ui.horizontal(|ui| { // ui.memory_mut().close_popup();
// There's more than 1 function! Functions can now be deleted
if ui
.add_enabled(can_remove, button_area_button(""))
.on_hover_text("Delete Function")
.clicked()
{
remove_i = Some(i);
}
// Toggle visibility movement = Movement::Complete;
function.visible.bitxor_assign( } else {
ui.add(button_area_button(if function.visible { ui.memory_mut(|x| x.open_popup(POPUP_ID));
"👁" }
} else { }
""
}))
.on_hover_text(match function.visible {
true => "Hide Function",
false => "Show Function",
})
.clicked(),
);
// Clone function // Push cursor to end if needed
if ui if movement == Movement::Complete {
.add_enabled(can_add, button_area_button("")) let mut state =
.on_hover_text("Clone Function") unsafe { TextEdit::load_state(ui.ctx(), te_id).unwrap_unchecked() };
.clicked() let ccursor = egui::text::CCursor::new(function.autocomplete.string.len());
{ state.set_ccursor_range(Some(egui::text::CCursorRange::one(ccursor)));
clone_i = Some(i); TextEdit::store_state(ui.ctx(), te_id, state);
} }
}
// Move up (only if not first) /// The y offset multiplier of the `buttons_area` area
if ui const BUTTONS_Y_OFFSET: f32 = 1.32;
.add_enabled(i > 0, button_area_button("")) const Y_OFFSET: f32 = crate::consts::FONT_SIZE * BUTTONS_Y_OFFSET;
.on_hover_text("Move Up")
.clicked()
{
move_up_i = Some(i);
}
// Move down (only if not last) widgets_ontop(ui, create_id(i as u64), &re, Y_OFFSET, |ui| {
if ui ui.horizontal(|ui| {
.add_enabled(i < num_functions - 1, button_area_button("")) // There's more than 1 function! Functions can now be deleted
.on_hover_text("Move Down") if ui
.clicked() .add_enabled(can_remove, button_area_button(""))
{ .on_hover_text("Delete Function")
move_down_i = Some(i); .clicked()
} {
remove_i = Some(i);
}
ui.add_enabled_ui(function.is_some(), |ui| { ui.add_enabled_ui(function.is_some(), |ui| {
// Toggle integral being enabled or not // Toggle integral being enabled or not
function.integral.bitxor_assign( function.integral.bitxor_assign(
ui.add(button_area_button("")) ui.add(button_area_button(""))
.on_hover_text(match function.integral { .on_hover_text(match function.integral {
true => "Don't integrate", true => "Don't integrate",
false => "Integrate", false => "Integrate",
}) })
.clicked(), .clicked(),
); );
// Toggle showing the derivative (even though it's already calculated this option just toggles if it's displayed or not) // Toggle showing the derivative (even though it's already calculated this option just toggles if it's displayed or not)
function.derivative.bitxor_assign( function.derivative.bitxor_assign(
ui.add(button_area_button("d/dx")) ui.add(button_area_button("d/dx"))
.on_hover_text(match function.derivative { .on_hover_text(match function.derivative {
true => "Don't Differentiate", true => "Don't Differentiate",
false => "Differentiate", false => "Differentiate",
}) })
.clicked(), .clicked(),
); );
// Toggle showing the settings window // Toggle showing the settings window
function.settings_opened.bitxor_assign( function.settings_opened.bitxor_assign(
ui.add(button_area_button("")) ui.add(button_area_button(""))
.on_hover_text(match function.settings_opened { .on_hover_text(match function.settings_opened {
true => "Close Settings", true => "Close Settings",
false => "Open Settings", false => "Open Settings",
}) })
.clicked(), .clicked(),
); );
}); });
}); });
}); });
} }
function.settings_window(ui.ctx()); function.settings_window(ui.ctx());
} }
// Remove function if the user requests it // Remove function if the user requests it
if let Some(remove_i_unwrap) = remove_i { if let Some(remove_i_unwrap) = remove_i {
self.functions.remove(remove_i_unwrap); self.functions.remove(remove_i_unwrap);
} }
// Clone function if the user requests it let final_hash = self.get_hash();
if let Some(clone_i_unwrap) = clone_i {
let cloned = self.functions[clone_i_unwrap].1.clone();
self.push_cloned(cloned);
}
// Move function up if the user requests it initial_hash != final_hash
if let Some(i) = move_up_i }
&& i > 0
{
self.functions.swap(i, i - 1);
}
// Move function down if the user requests it /// Create and push new empty function entry
if let Some(i) = move_down_i pub fn push_empty(&mut self) {
&& i < self.functions.len() - 1 self.functions.push((
{ create_id(random_u64().expect("unable to generate random id")),
self.functions.swap(i, i + 1); FunctionEntry::default(),
} ));
}
let final_hash = self.get_hash(); /// Detect if any functions are using integrals
pub fn any_using_integral(&self) -> bool {
self.functions.iter().any(|(_, func)| func.integral)
}
initial_hash != final_hash #[inline]
} pub fn len(&self) -> usize { self.functions.len() }
/// Create and push new empty function entry #[inline]
pub fn push_empty(&mut self) { pub fn get_entries_mut(&mut self) -> &mut Functions { &mut self.functions }
self.functions.push((
create_id(random_u64().expect("unable to generate random id")),
FunctionEntry::default(),
));
}
/// Push a cloned function entry #[inline]
pub fn push_cloned(&mut self, mut entry: FunctionEntry) { pub fn get_entries(&self) -> &Functions { &self.functions }
// Reset settings_opened so the cloned function doesn't have settings open
entry.settings_opened = false;
self.functions.push((
create_id(random_u64().expect("unable to generate random id")),
entry,
));
}
/// Detect if any functions are using integrals
pub fn any_using_integral(&self) -> bool {
self.functions.iter().any(|(_, func)| func.integral)
}
#[inline]
pub fn len(&self) -> usize {
self.functions.len()
}
#[inline]
pub fn get_entries_mut(&mut self) -> &mut Functions {
&mut self.functions
}
#[inline]
pub fn get_entries(&self) -> &Functions {
&self.functions
}
} }

View File

@ -1,3 +1,15 @@
#![feature(const_mut_refs)]
#![feature(let_chains)]
#![feature(const_trait_impl)]
#![feature(core_intrinsics)]
#![feature(const_fn_floating_point_arithmetic)]
#![feature(const_assume)]
#![feature(const_option_ext)]
#![feature(const_slice_index)]
#![feature(slice_split_at_unchecked)]
#![feature(inline_const)]
#![feature(const_for)]
#[macro_use] #[macro_use]
extern crate static_assertions; extern crate static_assertions;
@ -10,72 +22,65 @@ mod unicode_helper;
mod widgets; mod widgets;
pub use crate::{ pub use crate::{
function_entry::{FunctionEntry, Riemann}, function_entry::{FunctionEntry, Riemann},
math_app::AppSettings, math_app::AppSettings,
misc::{ misc::{
EguiHelper, HashBytes, hashed_storage_create, hashed_storage_read, newtons_method, hashed_storage_create, hashed_storage_read, newtons_method, option_vec_printer,
option_vec_printer, step_helper, step_helper, EguiHelper, HashBytes,
}, },
unicode_helper::{to_chars_array, to_unicode_hash}, unicode_helper::{to_chars_array, to_unicode_hash},
}; };
cfg_if::cfg_if! { cfg_if::cfg_if! {
if #[cfg(target_arch = "wasm32")] { if #[cfg(target_arch = "wasm32")] {
use wasm_bindgen::prelude::*; use wasm_bindgen::prelude::*;
use lol_alloc::{FreeListAllocator, LockedAllocator}; use lol_alloc::{FreeListAllocator, LockedAllocator};
#[global_allocator] #[global_allocator]
static ALLOCATOR: LockedAllocator<FreeListAllocator> = LockedAllocator::new(FreeListAllocator::new()); static ALLOCATOR: LockedAllocator<FreeListAllocator> = LockedAllocator::new(FreeListAllocator::new());
use eframe::WebRunner; use eframe::WebRunner;
// use tracing::metadata::LevelFilter; // use tracing::metadata::LevelFilter;
#[derive(Clone)] #[derive(Clone)]
#[wasm_bindgen] #[wasm_bindgen]
pub struct WebHandle { pub struct WebHandle {
runner: WebRunner, runner: WebRunner,
} }
#[wasm_bindgen] #[wasm_bindgen]
impl WebHandle { impl WebHandle {
/// Installs a panic hook, then returns. /// Installs a panic hook, then returns.
#[allow(clippy::new_without_default)] #[allow(clippy::new_without_default)]
#[wasm_bindgen(constructor)] #[wasm_bindgen(constructor)]
pub fn new() -> Self { pub fn new() -> Self {
// eframe::WebLogger::init(LevelFilter::Debug).ok(); // eframe::WebLogger::init(LevelFilter::Debug).ok();
tracing_wasm::set_as_global_default(); tracing_wasm::set_as_global_default();
Self { Self {
runner: WebRunner::new(), runner: WebRunner::new(),
} }
} }
/// Call this once from JavaScript to start your app. /// Call this once from JavaScript to start your app.
#[wasm_bindgen] #[wasm_bindgen]
pub async fn start(&self, canvas: web_sys::HtmlCanvasElement) -> Result<(), wasm_bindgen::JsValue> { pub async fn start(&self, canvas_id: &str) -> Result<(), wasm_bindgen::JsValue> {
self.runner self.runner
.start( .start(
canvas, canvas_id,
eframe::WebOptions::default(), eframe::WebOptions::default(),
Box::new(|cc| Ok(Box::new(math_app::MathApp::new(cc)))), Box::new(|cc| Box::new(math_app::MathApp::new(cc))),
) )
.await .await
} }
} }
#[wasm_bindgen(start)] #[wasm_bindgen(start)]
pub async fn start() { pub async fn start() {
tracing::info!("Starting..."); tracing::info!("Starting...");
let window = web_sys::window().expect("no global window exists");
let document = window.document().expect("should have a document on window");
let canvas = document
.get_element_by_id("canvas")
.expect("should have a canvas element with id 'canvas'")
.dyn_into::<web_sys::HtmlCanvasElement>()
.expect("canvas element should be an HtmlCanvasElement");
let web_handle = WebHandle::new(); let web_handle = WebHandle::new();
web_handle.start(canvas).await.unwrap() web_handle.start("canvas").await.unwrap()
} }
} }
} }

View File

@ -1,3 +1,15 @@
#![feature(const_mut_refs)]
#![feature(let_chains)]
#![feature(const_trait_impl)]
#![feature(core_intrinsics)]
#![feature(const_fn_floating_point_arithmetic)]
#![feature(const_assume)]
#![feature(const_option_ext)]
#![feature(const_slice_index)]
#![feature(slice_split_at_unchecked)]
#![feature(inline_const)]
#![feature(const_for)]
#[macro_use] #[macro_use]
extern crate static_assertions; extern crate static_assertions;
@ -11,16 +23,16 @@ mod widgets;
// For running the program natively! (Because why not?) // For running the program natively! (Because why not?)
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
fn main() -> eframe::Result { fn main() -> eframe::Result<()> {
let subscriber = tracing_subscriber::FmtSubscriber::builder() let subscriber = tracing_subscriber::FmtSubscriber::builder()
.with_max_level(tracing::Level::INFO) .with_max_level(tracing::Level::INFO)
.finish(); .finish();
tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed"); tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");
eframe::run_native( eframe::run_native(
"(Yet-to-be-named) Graphing Software", "(Yet-to-be-named) Graphing Software",
eframe::NativeOptions::default(), eframe::NativeOptions::default(),
Box::new(|cc| Ok(Box::new(math_app::MathApp::new(cc)))), Box::new(|cc| Box::new(math_app::MathApp::new(cc))),
) )
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,82 +1,75 @@
use egui::Id; use egui::Id;
use egui_plot::{Line, PlotPoint, PlotPoints, Points}; use egui_plot::{Line, PlotPoint, PlotPoints, Points};
use emath::Pos2; use emath::Pos2;
use getrandom::getrandom;
use itertools::Itertools; use itertools::Itertools;
use parsing::FlatExWrapper; use parsing::FlatExWrapper;
/// Implements traits that are useful when dealing with Vectors of egui's `Value` /// Implements traits that are useful when dealing with Vectors of egui's `Value`
pub trait EguiHelper { pub trait EguiHelper {
/// Converts to `egui::plot::Values` /// Converts to `egui::plot::Values`
fn to_values(self) -> PlotPoints<'static>; fn to_values(self) -> PlotPoints;
/// Converts to `egui::plot::Line` /// Converts to `egui::plot::Line`
fn to_line(self) -> Line<'static>; fn to_line(self) -> Line;
/// Converts to `egui::plot::Points` /// Converts to `egui::plot::Points`
fn to_points(self) -> Points<'static>; fn to_points(self) -> Points;
/// Converts Vector of Values into vector of tuples /// Converts Vector of Values into vector of tuples
fn to_tuple(self) -> Vec<(f64, f64)>; fn to_tuple(self) -> Vec<(f64, f64)>;
} }
impl EguiHelper for Vec<PlotPoint> { impl EguiHelper for Vec<PlotPoint> {
#[inline(always)] #[inline(always)]
fn to_values(self) -> PlotPoints<'static> { fn to_values(self) -> PlotPoints {
PlotPoints::from(unsafe { std::mem::transmute::<Vec<PlotPoint>, Vec<[f64; 2]>>(self) }) PlotPoints::from(unsafe { std::mem::transmute::<Vec<PlotPoint>, Vec<[f64; 2]>>(self) })
} }
#[inline(always)] #[inline(always)]
fn to_line(self) -> Line<'static> { fn to_line(self) -> Line { Line::new(self.to_values()) }
Line::new("", self.to_values())
}
#[inline(always)] #[inline(always)]
fn to_points(self) -> Points<'static> { fn to_points(self) -> Points { Points::new(self.to_values()) }
Points::new("", self.to_values())
}
#[inline(always)] #[inline(always)]
fn to_tuple(self) -> Vec<(f64, f64)> { fn to_tuple(self) -> Vec<(f64, f64)> {
unsafe { std::mem::transmute::<Vec<PlotPoint>, Vec<(f64, f64)>>(self) } unsafe { std::mem::transmute::<Vec<PlotPoint>, Vec<(f64, f64)>>(self) }
} }
} }
pub trait Offset { pub trait Offset {
fn offset_y(self, y_offset: f32) -> Pos2; fn offset_y(self, y_offset: f32) -> Pos2;
fn offset_x(self, x_offset: f32) -> Pos2; fn offset_x(self, x_offset: f32) -> Pos2;
} }
impl Offset for Pos2 { impl const Offset for Pos2 {
fn offset_y(self, y_offset: f32) -> Pos2 { fn offset_y(self, y_offset: f32) -> Pos2 {
Pos2 { Pos2 {
x: self.x, x: self.x,
y: self.y + y_offset, y: self.y + y_offset,
} }
} }
fn offset_x(self, x_offset: f32) -> Pos2 { fn offset_x(self, x_offset: f32) -> Pos2 {
Pos2 { Pos2 {
x: self.x + x_offset, x: self.x + x_offset,
y: self.y, y: self.y,
} }
} }
} }
pub const fn create_id(x: u64) -> Id { pub const fn create_id(x: u64) -> Id { unsafe { std::mem::transmute::<u64, Id>(x) } }
unsafe { std::mem::transmute::<u64, Id>(x) }
}
pub const fn get_u64_id(id: Id) -> u64 { pub const fn get_u64_id(id: Id) -> u64 { unsafe { std::mem::transmute::<Id, u64>(id) } }
unsafe { std::mem::transmute::<Id, u64>(id) }
}
/* /*
/// Rounds f64 to `n` decimal places /// Rounds f64 to `n` decimal places
pub fn decimal_round(x: f64, n: usize) -> f64 { pub fn decimal_round(x: f64, n: usize) -> f64 {
let large_number: f64 = 10.0_f64.powf(n as f64); // 10^n let large_number: f64 = 10.0_f64.powf(n as f64); // 10^n
// round and devide in order to cutoff after the `n`th decimal place // round and devide in order to cutoff after the `n`th decimal place
(x * large_number).round() / large_number (x * large_number).round() / large_number
} }
*/ */
@ -87,21 +80,18 @@ pub fn decimal_round(x: f64, n: usize) -> f64 {
/// `f_1` is f'(x) aka the derivative of f(x) /// `f_1` is f'(x) aka the derivative of f(x)
/// The function returns a Vector of `x` values where roots occur /// The function returns a Vector of `x` values where roots occur
pub fn newtons_method_helper( pub fn newtons_method_helper(
threshold: f64, threshold: f64, range: &std::ops::Range<f64>, data: &[PlotPoint], f: &FlatExWrapper,
range: &std::ops::Range<f64>, f_1: &FlatExWrapper,
data: &[PlotPoint],
f: &FlatExWrapper,
f_1: &FlatExWrapper,
) -> Vec<f64> { ) -> Vec<f64> {
data.iter() data.iter()
.tuple_windows() .tuple_windows()
.filter(|(prev, curr)| prev.y.is_finite() && curr.y.is_finite()) .filter(|(prev, curr)| prev.y.is_finite() && curr.y.is_finite())
.filter(|(prev, curr)| prev.y.signum() != curr.y.signum()) .filter(|(prev, curr)| prev.y.signum() != curr.y.signum())
.map(|(start, _)| start.x) .map(|(start, _)| start.x)
.map(|x| newtons_method(f, f_1, x, range, threshold)) .map(|x| newtons_method(f, f_1, x, range, threshold))
.filter(|x| x.is_some()) .filter(|x| x.is_some())
.map(|x| unsafe { x.unwrap_unchecked() }) .map(|x| unsafe { x.unwrap_unchecked() })
.collect() .collect()
} }
/// `range` is the range of valid x values (used to stop calculation when /// `range` is the range of valid x values (used to stop calculation when
@ -109,67 +99,64 @@ pub fn newtons_method_helper(
/// `f_1` is f'(x) aka the derivative of f(x) /// `f_1` is f'(x) aka the derivative of f(x)
/// The function returns an `Option<f64>` of the x value at which a root occurs /// The function returns an `Option<f64>` of the x value at which a root occurs
pub fn newtons_method( pub fn newtons_method(
f: &FlatExWrapper, f: &FlatExWrapper, f_1: &FlatExWrapper, start_x: f64, range: &std::ops::Range<f64>,
f_1: &FlatExWrapper, threshold: f64,
start_x: f64,
range: &std::ops::Range<f64>,
threshold: f64,
) -> Option<f64> { ) -> Option<f64> {
let mut x1: f64 = start_x; let mut x1: f64 = start_x;
let mut x2: f64; let mut x2: f64;
let mut derivative: f64; let mut derivative: f64;
loop { loop {
derivative = f_1.eval(&[x1]); derivative = f_1.eval(&[x1]);
if !derivative.is_finite() { if !derivative.is_finite() {
return None; return None;
} }
x2 = x1 - (f.eval(&[x1]) / derivative); x2 = x1 - (f.eval(&[x1]) / derivative);
if !x2.is_finite() | !range.contains(&x2) { if !x2.is_finite() | !range.contains(&x2) {
return None; return None;
} }
// If below threshold, break // If below threshold, break
if (x2 - x1).abs() < threshold { if (x2 - x1).abs() < threshold {
return Some(x2); return Some(x2);
} }
x1 = x2; x1 = x2;
} }
} }
/// Inputs `Vec<Option<T>>` and outputs a `String` containing a pretty representation of the Vector /// Inputs `Vec<Option<T>>` and outputs a `String` containing a pretty representation of the Vector
pub fn option_vec_printer<T: ToString>(data: &[Option<T>]) -> String { pub fn option_vec_printer<T: ToString>(data: &[Option<T>]) -> String {
let formatted: String = data let formatted: String = data
.iter() .iter()
.map(|item| match item { .map(|item| match item {
Some(x) => x.to_string(), Some(x) => x.to_string(),
None => "None".to_owned(), None => "None".to_owned(),
}) })
.join(", "); .join(", ");
format!("[{}]", formatted) format!("[{}]", formatted)
} }
/// Returns a vector of length `max_i` starting at value `min_x` with step of `step` /// Returns a vector of length `max_i` starting at value `min_x` with step of `step`
pub fn step_helper(max_i: usize, min_x: f64, step: f64) -> Vec<f64> { pub fn step_helper(max_i: usize, min_x: f64, step: f64) -> Vec<f64> {
(0..max_i) (0..max_i)
.map(move |x: usize| (x as f64 * step) + min_x) .map(move |x: usize| (x as f64 * step) + min_x)
.collect() .collect()
} }
// TODO: use in hovering over points // TODO: use in hovering over points
/// Attempts to see what variable `x` is almost /// Attempts to see what variable `x` is almost
#[allow(dead_code)] #[allow(dead_code)]
pub fn almost_variable(x: f64) -> Option<char> { pub fn almost_variable(x: f64) -> Option<char> {
const EPSILON: f32 = f32::EPSILON * 2.0; const EPSILON: f32 = f32::EPSILON * 2.0;
if emath::almost_equal(x as f32, std::f32::consts::E, EPSILON) { if emath::almost_equal(x as f32, std::f32::consts::E, EPSILON) {
Some('e') Some('e')
} else if emath::almost_equal(x as f32, std::f32::consts::PI, EPSILON) { } else if emath::almost_equal(x as f32, std::f32::consts::PI, EPSILON) {
Some('π') Some('π')
} else { } else {
None None
} }
} }
pub const HASH_LENGTH: usize = 8; pub const HASH_LENGTH: usize = 8;
@ -179,82 +166,36 @@ pub type HashBytes = [u8; HASH_LENGTH];
#[allow(dead_code)] #[allow(dead_code)]
pub fn hashed_storage_create(hashbytes: HashBytes, data: &[u8]) -> String { pub fn hashed_storage_create(hashbytes: HashBytes, data: &[u8]) -> String {
unsafe { std::mem::transmute::<Vec<u8>, String>([hashbytes.to_vec(), data.to_vec()].concat()) } unsafe { std::mem::transmute::<Vec<u8>, String>([hashbytes.to_vec(), data.to_vec()].concat()) }
} }
#[allow(dead_code)] #[allow(dead_code)]
pub fn hashed_storage_read(data: &str) -> Option<(HashBytes, &[u8])> { pub fn hashed_storage_read(data: &str) -> Option<(HashBytes, &[u8])> {
// Make sure data is long enough to decode // Make sure data is long enough to decode
if HASH_LENGTH >= data.len() { if HASH_LENGTH >= data.len() {
return None; return None;
} }
// Transmute data into slice // Transmute data into slice
let decoded_1: &[u8] = unsafe { std::mem::transmute::<&str, &[u8]>(data) }; let decoded_1: &[u8] = unsafe { std::mem::transmute::<&str, &[u8]>(data) };
// Return hash and decoded data // Return hash and decoded data
Some(( Some((
unsafe { *(decoded_1[..HASH_LENGTH].as_ptr() as *const HashBytes) }, unsafe { *(decoded_1[..HASH_LENGTH].as_ptr() as *const HashBytes) },
&decoded_1[HASH_LENGTH..], &decoded_1[HASH_LENGTH..],
)) ))
} }
/// Creates and returns random u64 /// Creates and returns random u64
pub fn random_u64() -> Result<u64, getrandom::Error> { pub fn random_u64() -> Result<u64, getrandom::Error> {
// Buffer of 8 `u8`s that are later merged into one u64 // Buffer of 8 `u8`s that are later merged into one u64
let mut buf = [0u8; 8]; let mut buf = [0u8; 8];
// Populate buffer with random values // Populate buffer with random values
getrandom::fill(&mut buf)?; getrandom(&mut buf)?;
// Merge buffer into u64 // Merge buffer into u64
Ok(u64::from_be_bytes(buf)) Ok(u64::from_be_bytes(buf))
} }
include!(concat!(env!("OUT_DIR"), "/valid_chars.rs")); include!(concat!(env!("OUT_DIR"), "/valid_chars.rs"));
pub fn is_valid_char(c: char) -> bool { pub fn is_valid_char(c: char) -> bool { c.is_alphanumeric() | VALID_EXTRA_CHARS.contains(&c) }
c.is_alphanumeric() | VALID_EXTRA_CHARS.contains(&c)
}
/// Find intersection points between two functions given their plotted data
/// Returns a vector of PlotPoints where the functions intersect
pub fn find_intersections(data1: &[PlotPoint], data2: &[PlotPoint]) -> Vec<PlotPoint> {
if data1.is_empty() || data2.is_empty() || data1.len() != data2.len() {
return Vec::new();
}
// Calculate difference between functions at each x point
let differences: Vec<(f64, f64)> = data1
.iter()
.zip(data2.iter())
.filter(|(p1, p2)| p1.y.is_finite() && p2.y.is_finite())
.map(|(p1, p2)| (p1.x, p1.y - p2.y))
.collect();
// Find where sign changes (intersection points)
differences
.iter()
.tuple_windows()
.filter(|((_, diff1), (_, diff2))| diff1.signum() != diff2.signum())
.map(|((x1, diff1), (x2, diff2))| {
// Linear interpolation to find approximate x of intersection
let t = diff1.abs() / (diff1.abs() + diff2.abs());
let x = x1 + t * (x2 - x1);
// Find corresponding y values and average them for the intersection point
// We need to interpolate y values from both functions
let y1_at_x1 = data1
.iter()
.find(|p| (p.x - x1).abs() < f64::EPSILON)
.map(|p| p.y)
.unwrap_or(0.0);
let y1_at_x2 = data1
.iter()
.find(|p| (p.x - x2).abs() < f64::EPSILON)
.map(|p| p.y)
.unwrap_or(0.0);
let y = y1_at_x1 + t * (y1_at_x2 - y1_at_x1);
PlotPoint::new(x, y)
})
.collect()
}

View File

@ -2,19 +2,19 @@ use itertools::Itertools;
#[allow(dead_code)] #[allow(dead_code)]
pub fn to_unicode_hash(c: char) -> String { pub fn to_unicode_hash(c: char) -> String {
c.escape_unicode() c.escape_unicode()
.to_string() .to_string()
.replace(r"\\u{", "") .replace(r"\\u{", "")
.replace(['{', '}'], "") .replace(['{', '}'], "")
.to_uppercase() .to_uppercase()
} }
#[allow(dead_code)] #[allow(dead_code)]
pub fn to_chars_array(chars: Vec<char>) -> String { pub fn to_chars_array(chars: Vec<char>) -> String {
"[".to_string() "[".to_string()
+ &chars + &chars
.iter() .iter()
.map(|c| format!("'{}'", c.escape_unicode())) .map(|c| format!("'{}'", c.escape_unicode()))
.join(", ") .join(", ")
+ "]" + "]"
} }

View File

@ -3,15 +3,12 @@ use egui::{Id, InnerResponse};
/// Creates an area ontop of a widget with an y offset /// Creates an area ontop of a widget with an y offset
pub fn widgets_ontop<R>( pub fn widgets_ontop<R>(
ui: &egui::Ui, ui: &egui::Ui, id: Id, re: &egui::Response, y_offset: f32,
id: Id, add_contents: impl FnOnce(&mut egui::Ui) -> R,
re: &egui::Response,
y_offset: f32,
add_contents: impl FnOnce(&mut egui::Ui) -> R,
) -> InnerResponse<R> { ) -> InnerResponse<R> {
let area = egui::Area::new(id) let area = egui::Area::new(id)
.fixed_pos(re.rect.min.offset_y(y_offset)) .fixed_pos(re.rect.min.offset_y(y_offset))
.order(egui::Order::Foreground); .order(egui::Order::Foreground);
area.show(ui.ctx(), |ui| add_contents(ui)) area.show(ui.ctx(), |ui| add_contents(ui))
} }

6
start-server.sh Executable file
View File

@ -0,0 +1,6 @@
#!/bin/bash
set -e
bash build.sh "$1"
basic-http-server tmp/

View File

@ -1,159 +1,159 @@
use parsing::{AutoComplete, Hint, Movement}; use parsing::{AutoComplete, Hint, Movement};
enum Action<'a> { enum Action<'a> {
AssertIndex(usize), AssertIndex(usize),
AssertString(&'a str), AssertString(&'a str),
AssertHint(&'a str), AssertHint(&'a str),
SetString(&'a str), SetString(&'a str),
Move(Movement), Move(Movement),
} }
use Action::*; use Action::*;
fn ac_tester(actions: &[Action]) { fn ac_tester(actions: &[Action]) {
let mut ac = AutoComplete::default(); let mut ac = AutoComplete::default();
for action in actions.iter() { for action in actions.iter() {
match action { match action {
AssertIndex(target_i) => { AssertIndex(target_i) => {
if &ac.i != target_i { if &ac.i != target_i {
panic!( panic!(
"AssertIndex failed: Current: '{}' Expected: '{}'", "AssertIndex failed: Current: '{}' Expected: '{}'",
ac.i, target_i ac.i, target_i
) )
} }
} }
AssertString(target_string) => { AssertString(target_string) => {
if &ac.string != target_string { if &ac.string != target_string {
panic!( panic!(
"AssertString failed: Current: '{}' Expected: '{}'", "AssertString failed: Current: '{}' Expected: '{}'",
ac.string, target_string ac.string, target_string
) )
} }
} }
AssertHint(target_hint) => match ac.hint { AssertHint(target_hint) => match ac.hint {
Hint::None => { Hint::None => {
if !target_hint.is_empty() { if !target_hint.is_empty() {
panic!( panic!(
"AssertHint failed on `Hint::None`: Expected: {}", "AssertHint failed on `Hint::None`: Expected: {}",
target_hint target_hint
); );
} }
} }
Hint::Many(hints) => { Hint::Many(hints) => {
let hint = hints[ac.i]; let hint = hints[ac.i];
if &hint != target_hint { if &hint != target_hint {
panic!( panic!(
"AssertHint failed on `Hint::Many`: Current: '{}' (index: {}) Expected: '{}'", "AssertHint failed on `Hint::Many`: Current: '{}' (index: {}) Expected: '{}'",
hint, ac.i, target_hint hint, ac.i, target_hint
) )
} }
} }
Hint::Single(hint) => { Hint::Single(hint) => {
if hint != target_hint { if hint != target_hint {
panic!( panic!(
"AssertHint failed on `Hint::Single`: Current: '{}' Expected: '{}'", "AssertHint failed on `Hint::Single`: Current: '{}' Expected: '{}'",
hint, target_hint hint, target_hint
) )
} }
} }
}, },
SetString(target_string) => { SetString(target_string) => {
ac.update_string(target_string); ac.update_string(target_string);
} }
Move(target_movement) => { Move(target_movement) => {
ac.register_movement(target_movement); ac.register_movement(target_movement);
} }
} }
} }
} }
#[test] #[test]
fn single() { fn single() {
ac_tester(&[ ac_tester(&[
SetString(""), SetString(""),
AssertHint("x^2"), AssertHint("x^2"),
Move(Movement::Up), Move(Movement::Up),
AssertIndex(0), AssertIndex(0),
AssertString(""), AssertString(""),
AssertHint("x^2"), AssertHint("x^2"),
Move(Movement::Down), Move(Movement::Down),
AssertIndex(0), AssertIndex(0),
AssertString(""), AssertString(""),
AssertHint("x^2"), AssertHint("x^2"),
Move(Movement::Complete), Move(Movement::Complete),
AssertString("x^2"), AssertString("x^2"),
AssertHint(""), AssertHint(""),
AssertIndex(0), AssertIndex(0),
]); ]);
} }
#[test] #[test]
fn multi() { fn multi() {
ac_tester(&[ ac_tester(&[
SetString("s"), SetString("s"),
AssertHint("in("), AssertHint("in("),
Move(Movement::Up), Move(Movement::Up),
AssertIndex(3), AssertIndex(3),
AssertString("s"), AssertString("s"),
AssertHint("ignum("), AssertHint("ignum("),
Move(Movement::Down), Move(Movement::Down),
AssertIndex(0), AssertIndex(0),
AssertString("s"), AssertString("s"),
AssertHint("in("), AssertHint("in("),
Move(Movement::Down), Move(Movement::Down),
AssertIndex(1), AssertIndex(1),
AssertString("s"), AssertString("s"),
AssertHint("qrt("), AssertHint("qrt("),
Move(Movement::Up), Move(Movement::Up),
AssertIndex(0), AssertIndex(0),
AssertString("s"), AssertString("s"),
AssertHint("in("), AssertHint("in("),
Move(Movement::Complete), Move(Movement::Complete),
AssertString("sin("), AssertString("sin("),
AssertHint(")"), AssertHint(")"),
AssertIndex(0), AssertIndex(0),
]); ]);
} }
#[test] #[test]
fn none() { fn none() {
// string that should give no hints // string that should give no hints
let random = "qwert987gybhj"; let random = "qwert987gybhj";
assert_eq!(parsing::generate_hint(random), &Hint::None); assert_eq!(parsing::generate_hint(random), &Hint::None);
ac_tester(&[ ac_tester(&[
SetString(random), SetString(random),
AssertHint(""), AssertHint(""),
Move(Movement::Up), Move(Movement::Up),
AssertIndex(0), AssertIndex(0),
AssertString(random), AssertString(random),
AssertHint(""), AssertHint(""),
Move(Movement::Down), Move(Movement::Down),
AssertIndex(0), AssertIndex(0),
AssertString(random), AssertString(random),
AssertHint(""), AssertHint(""),
Move(Movement::Complete), Move(Movement::Complete),
AssertString(random), AssertString(random),
AssertHint(""), AssertHint(""),
AssertIndex(0), AssertIndex(0),
]); ]);
} }
#[test] #[test]
fn parens() { fn parens() {
ac_tester(&[ ac_tester(&[
SetString("sin(x"), SetString("sin(x"),
AssertHint(")"), AssertHint(")"),
Move(Movement::Up), Move(Movement::Up),
AssertIndex(0), AssertIndex(0),
AssertString("sin(x"), AssertString("sin(x"),
AssertHint(")"), AssertHint(")"),
Move(Movement::Down), Move(Movement::Down),
AssertIndex(0), AssertIndex(0),
AssertString("sin(x"), AssertString("sin(x"),
AssertHint(")"), AssertHint(")"),
Move(Movement::Complete), Move(Movement::Complete),
AssertString("sin(x)"), AssertString("sin(x)"),
AssertHint(""), AssertHint(""),
AssertIndex(0), AssertIndex(0),
]); ]);
} }

View File

@ -1,274 +1,262 @@
use ytbn_graphing_software::{AppSettings, EguiHelper, FunctionEntry, Riemann}; use ytbn_graphing_software::{AppSettings, EguiHelper, FunctionEntry, Riemann};
fn app_settings_constructor( fn app_settings_constructor(
sum: Riemann, sum: Riemann, integral_min_x: f64, integral_max_x: f64, pixel_width: usize,
integral_min_x: f64, integral_num: usize, min_x: f64, max_x: f64,
integral_max_x: f64,
pixel_width: usize,
integral_num: usize,
min_x: f64,
max_x: f64,
) -> AppSettings { ) -> AppSettings {
AppSettings { AppSettings {
riemann_sum: sum, riemann_sum: sum,
integral_min_x, integral_min_x,
integral_max_x, integral_max_x,
min_x, min_x,
max_x, max_x,
integral_changed: true, integral_changed: true,
integral_num, integral_num,
do_extrema: false, do_extrema: false,
do_roots: false, do_roots: false,
do_intersections: false, plot_width: pixel_width,
plot_width: pixel_width, }
}
} }
static BACK_TARGET: [(f64, f64); 11] = [ static BACK_TARGET: [(f64, f64); 11] = [
(-1.0, 1.0), (-1.0, 1.0),
(-0.8, 0.6400000000000001), (-0.8, 0.6400000000000001),
(-0.6, 0.36), (-0.6, 0.36),
(-0.4, 0.16000000000000003), (-0.4, 0.16000000000000003),
(-0.19999999999999996, 0.03999999999999998), (-0.19999999999999996, 0.03999999999999998),
(0.0, 0.0), (0.0, 0.0),
(0.19999999999999996, 0.03999999999999998), (0.19999999999999996, 0.03999999999999998),
(0.3999999999999999, 0.15999999999999992), (0.3999999999999999, 0.15999999999999992),
(0.6000000000000001, 0.3600000000000001), (0.6000000000000001, 0.3600000000000001),
(0.8, 0.6400000000000001), (0.8, 0.6400000000000001),
(1.0, 1.0), (1.0, 1.0),
]; ];
static DERIVATIVE_TARGET: [(f64, f64); 11] = [ static DERIVATIVE_TARGET: [(f64, f64); 11] = [
(-1.0, -2.0), (-1.0, -2.0),
(-0.8, -1.6), (-0.8, -1.6),
(-0.6, -1.2), (-0.6, -1.2),
(-0.4, -0.8), (-0.4, -0.8),
(-0.19999999999999996, -0.3999999999999999), (-0.19999999999999996, -0.3999999999999999),
(0.0, 0.0), (0.0, 0.0),
(0.19999999999999996, 0.3999999999999999), (0.19999999999999996, 0.3999999999999999),
(0.3999999999999999, 0.7999999999999998), (0.3999999999999999, 0.7999999999999998),
(0.6000000000000001, 1.2000000000000002), (0.6000000000000001, 1.2000000000000002),
(0.8, 1.6), (0.8, 1.6),
(1.0, 2.0), (1.0, 2.0),
]; ];
#[cfg(test)] #[cfg(test)]
fn do_test(sum: Riemann, area_target: f64) { fn do_test(sum: Riemann, area_target: f64) {
let settings = app_settings_constructor(sum, -1.0, 1.0, 10, 10, -1.0, 1.0); let settings = app_settings_constructor(sum, -1.0, 1.0, 10, 10, -1.0, 1.0);
let mut function = FunctionEntry::default(); let mut function = FunctionEntry::default();
function.update_string("x^2"); function.update_string("x^2");
function.integral = true; function.integral = true;
function.derivative = true; function.derivative = true;
let mut settings = settings; let mut settings = settings;
{ {
function.calculate(true, true, false, settings); function.calculate(true, true, false, settings);
assert!(!function.back_data.is_empty()); assert!(!function.back_data.is_empty());
assert_eq!(function.back_data.len(), settings.plot_width + 1); assert_eq!(function.back_data.len(), settings.plot_width + 1);
assert!(function.integral); assert!(function.integral);
assert!(function.derivative); assert!(function.derivative);
assert_eq!(!function.root_data.is_empty(), settings.do_roots); assert_eq!(!function.root_data.is_empty(), settings.do_roots);
assert_eq!(!function.extrema_data.is_empty(), settings.do_extrema); assert_eq!(!function.extrema_data.is_empty(), settings.do_extrema);
assert!(!function.derivative_data.is_empty()); assert!(!function.derivative_data.is_empty());
assert!(function.integral_data.is_some()); assert!(function.integral_data.is_some());
assert_eq!(function.integral_data.clone().unwrap().1, area_target); assert_eq!(function.integral_data.clone().unwrap().1, area_target);
let a = function.derivative_data.clone().to_tuple(); let a = function.derivative_data.clone().to_tuple();
assert_eq!(a.len(), DERIVATIVE_TARGET.len()); assert_eq!(a.len(), DERIVATIVE_TARGET.len());
for i in 0..a.len() { for i in 0..a.len() {
if !emath::almost_equal(a[i].0 as f32, DERIVATIVE_TARGET[i].0 as f32, f32::EPSILON) if !emath::almost_equal(a[i].0 as f32, DERIVATIVE_TARGET[i].0 as f32, f32::EPSILON)
| !emath::almost_equal(a[i].1 as f32, DERIVATIVE_TARGET[i].1 as f32, f32::EPSILON) | !emath::almost_equal(a[i].1 as f32, DERIVATIVE_TARGET[i].1 as f32, f32::EPSILON)
{ {
panic!("Expected: {:?}\nGot: {:?}", a, DERIVATIVE_TARGET); panic!("Expected: {:?}\nGot: {:?}", a, DERIVATIVE_TARGET);
} }
} }
let a_1 = function.back_data.clone().to_tuple(); let a_1 = function.back_data.clone().to_tuple();
assert_eq!(a_1.len(), BACK_TARGET.len()); assert_eq!(a_1.len(), BACK_TARGET.len());
assert_eq!(a.len(), BACK_TARGET.len()); assert_eq!(a.len(), BACK_TARGET.len());
for i in 0..a.len() { for i in 0..a.len() {
if !emath::almost_equal(a_1[i].0 as f32, BACK_TARGET[i].0 as f32, f32::EPSILON) if !emath::almost_equal(a_1[i].0 as f32, BACK_TARGET[i].0 as f32, f32::EPSILON)
| !emath::almost_equal(a_1[i].1 as f32, BACK_TARGET[i].1 as f32, f32::EPSILON) | !emath::almost_equal(a_1[i].1 as f32, BACK_TARGET[i].1 as f32, f32::EPSILON)
{ {
panic!("Expected: {:?}\nGot: {:?}", a_1, BACK_TARGET); panic!("Expected: {:?}\nGot: {:?}", a_1, BACK_TARGET);
} }
} }
} }
{ {
settings.min_x += 1.0; settings.min_x += 1.0;
settings.max_x += 1.0; settings.max_x += 1.0;
function.calculate(true, true, false, settings); function.calculate(true, true, false, settings);
let a = function let a = function
.derivative_data .derivative_data
.clone() .clone()
.to_tuple() .to_tuple()
.iter() .iter()
.take(6) .take(6)
.cloned() .cloned()
.collect::<Vec<(f64, f64)>>(); .collect::<Vec<(f64, f64)>>();
let b = DERIVATIVE_TARGET let b = DERIVATIVE_TARGET
.iter() .iter()
.rev() .rev()
.take(6) .take(6)
.rev() .rev()
.cloned() .cloned()
.collect::<Vec<(f64, f64)>>(); .collect::<Vec<(f64, f64)>>();
assert_eq!(a.len(), b.len()); assert_eq!(a.len(), b.len());
for i in 0..a.len() { for i in 0..a.len() {
if !emath::almost_equal(a[i].0 as f32, b[i].0 as f32, f32::EPSILON) if !emath::almost_equal(a[i].0 as f32, b[i].0 as f32, f32::EPSILON)
| !emath::almost_equal(a[i].1 as f32, b[i].1 as f32, f32::EPSILON) | !emath::almost_equal(a[i].1 as f32, b[i].1 as f32, f32::EPSILON)
{ {
panic!("Expected: {:?}\nGot: {:?}", a, b); panic!("Expected: {:?}\nGot: {:?}", a, b);
} }
} }
let a_1 = function let a_1 = function
.back_data .back_data
.clone() .clone()
.to_tuple() .to_tuple()
.iter() .iter()
.take(6) .take(6)
.cloned() .cloned()
.collect::<Vec<(f64, f64)>>(); .collect::<Vec<(f64, f64)>>();
let b_1 = BACK_TARGET let b_1 = BACK_TARGET
.iter() .iter()
.rev() .rev()
.take(6) .take(6)
.rev() .rev()
.cloned() .cloned()
.collect::<Vec<(f64, f64)>>(); .collect::<Vec<(f64, f64)>>();
assert_eq!(a_1.len(), b_1.len()); assert_eq!(a_1.len(), b_1.len());
assert_eq!(a.len(), b_1.len()); assert_eq!(a.len(), b_1.len());
for i in 0..a.len() { for i in 0..a.len() {
if !emath::almost_equal(a_1[i].0 as f32, b_1[i].0 as f32, f32::EPSILON) if !emath::almost_equal(a_1[i].0 as f32, b_1[i].0 as f32, f32::EPSILON)
| !emath::almost_equal(a_1[i].1 as f32, b_1[i].1 as f32, f32::EPSILON) | !emath::almost_equal(a_1[i].1 as f32, b_1[i].1 as f32, f32::EPSILON)
{ {
panic!("Expected: {:?}\nGot: {:?}", a_1, b_1); panic!("Expected: {:?}\nGot: {:?}", a_1, b_1);
} }
} }
} }
{ {
settings.min_x -= 2.0; settings.min_x -= 2.0;
settings.max_x -= 2.0; settings.max_x -= 2.0;
function.calculate(true, true, false, settings); function.calculate(true, true, false, settings);
let a = function let a = function
.derivative_data .derivative_data
.clone() .clone()
.to_tuple() .to_tuple()
.iter() .iter()
.rev() .rev()
.take(6) .take(6)
.rev() .rev()
.cloned() .cloned()
.collect::<Vec<(f64, f64)>>(); .collect::<Vec<(f64, f64)>>();
let b = DERIVATIVE_TARGET let b = DERIVATIVE_TARGET
.iter() .iter()
.take(6) .take(6)
.cloned() .cloned()
.collect::<Vec<(f64, f64)>>(); .collect::<Vec<(f64, f64)>>();
assert_eq!(a.len(), b.len()); assert_eq!(a.len(), b.len());
for i in 0..a.len() { for i in 0..a.len() {
if !emath::almost_equal(a[i].0 as f32, b[i].0 as f32, f32::EPSILON) if !emath::almost_equal(a[i].0 as f32, b[i].0 as f32, f32::EPSILON)
| !emath::almost_equal(a[i].1 as f32, b[i].1 as f32, f32::EPSILON) | !emath::almost_equal(a[i].1 as f32, b[i].1 as f32, f32::EPSILON)
{ {
panic!("Expected: {:?}\nGot: {:?}", a, b); panic!("Expected: {:?}\nGot: {:?}", a, b);
} }
} }
let a_1 = function let a_1 = function
.back_data .back_data
.clone() .clone()
.to_tuple() .to_tuple()
.iter() .iter()
.rev() .rev()
.take(6) .take(6)
.rev() .rev()
.cloned() .cloned()
.collect::<Vec<(f64, f64)>>(); .collect::<Vec<(f64, f64)>>();
let b_1 = BACK_TARGET let b_1 = BACK_TARGET
.iter() .iter()
.take(6) .take(6)
.cloned() .cloned()
.collect::<Vec<(f64, f64)>>(); .collect::<Vec<(f64, f64)>>();
assert_eq!(a_1.len(), b_1.len()); assert_eq!(a_1.len(), b_1.len());
assert_eq!(a.len(), b_1.len()); assert_eq!(a.len(), b_1.len());
for i in 0..a.len() { for i in 0..a.len() {
if !emath::almost_equal(a_1[i].0 as f32, b_1[i].0 as f32, f32::EPSILON) if !emath::almost_equal(a_1[i].0 as f32, b_1[i].0 as f32, f32::EPSILON)
| !emath::almost_equal(a_1[i].1 as f32, b_1[i].1 as f32, f32::EPSILON) | !emath::almost_equal(a_1[i].1 as f32, b_1[i].1 as f32, f32::EPSILON)
{ {
panic!("Expected: {:?}\nGot: {:?}", a_1, b_1); panic!("Expected: {:?}\nGot: {:?}", a_1, b_1);
} }
} }
} }
{ {
function.update_string("sin(x)"); function.update_string("sin(x)");
assert!(function.get_test_result().is_none()); assert!(function.get_test_result().is_none());
assert_eq!(&function.raw_func_str, "sin(x)"); assert_eq!(&function.raw_func_str, "sin(x)");
function.integral = false; function.integral = false;
function.derivative = false; function.derivative = false;
assert!(!function.integral); assert!(!function.integral);
assert!(!function.derivative); assert!(!function.derivative);
assert!(function.back_data.is_empty()); assert!(function.back_data.is_empty());
assert!(function.integral_data.is_none()); assert!(function.integral_data.is_none());
assert!(function.root_data.is_empty()); assert!(function.root_data.is_empty());
assert!(function.extrema_data.is_empty()); assert!(function.extrema_data.is_empty());
assert!(function.derivative_data.is_empty()); assert!(function.derivative_data.is_empty());
settings.min_x -= 1.0; settings.min_x -= 1.0;
settings.max_x -= 1.0; settings.max_x -= 1.0;
function.calculate(true, true, false, settings); function.calculate(true, true, false, settings);
assert!(!function.back_data.is_empty()); assert!(!function.back_data.is_empty());
assert!(function.integral_data.is_none()); assert!(function.integral_data.is_none());
assert!(function.root_data.is_empty()); assert!(function.root_data.is_empty());
assert!(function.extrema_data.is_empty()); assert!(function.extrema_data.is_empty());
assert!(!function.derivative_data.is_empty()); assert!(!function.derivative_data.is_empty());
} }
} }
#[test] #[test]
fn left_function() { fn left_function() { do_test(Riemann::Left, 0.9600000000000001); }
do_test(Riemann::Left, 0.9600000000000001);
}
#[test] #[test]
fn middle_function() { fn middle_function() { do_test(Riemann::Middle, 0.92); }
do_test(Riemann::Middle, 0.92);
}
#[test] #[test]
fn right_function() { fn right_function() { do_test(Riemann::Right, 0.8800000000000001); }
do_test(Riemann::Right, 0.8800000000000001);
}

View File

@ -2,90 +2,90 @@
/// Ensures [`decimal_round`] returns correct values /// Ensures [`decimal_round`] returns correct values
#[test] #[test]
fn decimal_round() { fn decimal_round() {
use ytbn_graphing_software::decimal_round; use ytbn_graphing_software::decimal_round;
assert_eq!(decimal_round(0.00001, 1), 0.0); assert_eq!(decimal_round(0.00001, 1), 0.0);
assert_eq!(decimal_round(0.00001, 2), 0.0); assert_eq!(decimal_round(0.00001, 2), 0.0);
assert_eq!(decimal_round(0.00001, 3), 0.0); assert_eq!(decimal_round(0.00001, 3), 0.0);
assert_eq!(decimal_round(0.00001, 4), 0.0); assert_eq!(decimal_round(0.00001, 4), 0.0);
assert_eq!(decimal_round(0.00001, 5), 0.00001); assert_eq!(decimal_round(0.00001, 5), 0.00001);
assert_eq!(decimal_round(0.12345, 1), 0.1); assert_eq!(decimal_round(0.12345, 1), 0.1);
assert_eq!(decimal_round(0.12345, 2), 0.12); assert_eq!(decimal_round(0.12345, 2), 0.12);
assert_eq!(decimal_round(0.12345, 3), 0.123); assert_eq!(decimal_round(0.12345, 3), 0.123);
assert_eq!(decimal_round(0.12345, 4), 0.1235); // rounds up assert_eq!(decimal_round(0.12345, 4), 0.1235); // rounds up
assert_eq!(decimal_round(0.12345, 5), 0.12345); assert_eq!(decimal_round(0.12345, 5), 0.12345);
assert_eq!(decimal_round(1.9, 0), 2.0); assert_eq!(decimal_round(1.9, 0), 2.0);
assert_eq!(decimal_round(1.9, 1), 1.9); assert_eq!(decimal_round(1.9, 1), 1.9);
} }
*/ */
#[test] #[test]
fn step_helper() { fn step_helper() {
use ytbn_graphing_software::step_helper; use ytbn_graphing_software::step_helper;
assert_eq!( assert_eq!(
step_helper(10, 2.0, 3.0), step_helper(10, 2.0, 3.0),
vec![2.0, 5.0, 8.0, 11.0, 14.0, 17.0, 20.0, 23.0, 26.0, 29.0] vec![2.0, 5.0, 8.0, 11.0, 14.0, 17.0, 20.0, 23.0, 26.0, 29.0]
); );
} }
/// Tests [`option_vec_printer`] /// Tests [`option_vec_printer`]
#[test] #[test]
fn option_vec_printer() { fn option_vec_printer() {
use std::collections::HashMap; use std::collections::HashMap;
use ytbn_graphing_software::option_vec_printer; use ytbn_graphing_software::option_vec_printer;
let values_strings: HashMap<Vec<Option<&str>>, &str> = HashMap::from([ let values_strings: HashMap<Vec<Option<&str>>, &str> = HashMap::from([
(vec![None], "[None]"), (vec![None], "[None]"),
(vec![Some("text"), None], "[text, None]"), (vec![Some("text"), None], "[text, None]"),
(vec![None, None], "[None, None]"), (vec![None, None], "[None, None]"),
(vec![Some("text1"), Some("text2")], "[text1, text2]"), (vec![Some("text1"), Some("text2")], "[text1, text2]"),
]); ]);
for (key, value) in values_strings { for (key, value) in values_strings {
assert_eq!(option_vec_printer(&key), value); assert_eq!(option_vec_printer(&key), value);
} }
let values_nums = HashMap::from([ let values_nums = HashMap::from([
(vec![Some(10)], "[10]"), (vec![Some(10)], "[10]"),
(vec![Some(10), None], "[10, None]"), (vec![Some(10), None], "[10, None]"),
(vec![None, Some(10)], "[None, 10]"), (vec![None, Some(10)], "[None, 10]"),
(vec![Some(10), Some(100)], "[10, 100]"), (vec![Some(10), Some(100)], "[10, 100]"),
]); ]);
for (key, value) in values_nums { for (key, value) in values_nums {
assert_eq!(option_vec_printer(&key), value); assert_eq!(option_vec_printer(&key), value);
} }
} }
#[test] #[test]
fn hashed_storage() { fn hashed_storage() {
use ytbn_graphing_software::{hashed_storage_create, hashed_storage_read}; use ytbn_graphing_software::{hashed_storage_create, hashed_storage_read};
let commit = "abcdefeg".chars().map(|c| c as u8).collect::<Vec<u8>>(); let commit = "abcdefeg".chars().map(|c| c as u8).collect::<Vec<u8>>();
let data = "really cool data" let data = "really cool data"
.chars() .chars()
.map(|c| c as u8) .map(|c| c as u8)
.collect::<Vec<u8>>(); .collect::<Vec<u8>>();
let storage_tmp: [u8; 8] = commit let storage_tmp: [u8; 8] = commit
.as_slice() .as_slice()
.try_into() .try_into()
.expect("cannot turn into [u8; 8]"); .expect("cannot turn into [u8; 8]");
let storage = hashed_storage_create(storage_tmp, data.as_slice()); let storage = hashed_storage_create(storage_tmp, data.as_slice());
let read = hashed_storage_read(&storage); let read = hashed_storage_read(&storage);
assert_eq!( assert_eq!(
read.map(|(a, b)| (a.to_vec(), b.to_vec())), read.map(|(a, b)| (a.to_vec(), b.to_vec())),
Some((commit.to_vec(), data.to_vec())) Some((commit.to_vec(), data.to_vec()))
); );
} }
#[test] #[test]
fn invalid_hashed_storage() { fn invalid_hashed_storage() {
use ytbn_graphing_software::hashed_storage_read; use ytbn_graphing_software::hashed_storage_read;
assert_eq!(hashed_storage_read("aaaa"), None); assert_eq!(hashed_storage_read("aaaa"), None);
} }
// #[test] // #[test]
@ -141,46 +141,45 @@ fn invalid_hashed_storage() {
#[test] #[test]
fn newtons_method() { fn newtons_method() {
use parsing::BackingFunction; use parsing::BackingFunction;
use parsing::FlatExWrapper; use parsing::FlatExWrapper;
use parsing::process_func_str; fn get_flatexwrapper(func: &str) -> FlatExWrapper {
fn get_flatexwrapper(func: &str) -> FlatExWrapper { let mut backing_func = BackingFunction::new(func).unwrap();
let backing_func = BackingFunction::new(&process_func_str(func)).unwrap(); backing_func.get_function_derivative(0).clone()
backing_func.get_function_derivative(0).clone() }
}
use ytbn_graphing_software::newtons_method; use ytbn_graphing_software::newtons_method;
let data = newtons_method( let data = newtons_method(
&get_flatexwrapper("x^2 -1"), &get_flatexwrapper("x^2 -1"),
&get_flatexwrapper("2x"), &get_flatexwrapper("2x"),
3.0, 3.0,
&(0.0..5.0), &(0.0..5.0),
f64::EPSILON, f64::EPSILON,
); );
assert_eq!(data, Some(1.0)); assert_eq!(data, Some(1.0));
let data = newtons_method( let data = newtons_method(
&get_flatexwrapper("sin(x)"), &get_flatexwrapper("sin(x)"),
&get_flatexwrapper("cos(x)"), &get_flatexwrapper("cos(x)"),
3.0, 3.0,
&(2.95..3.18), &(2.95..3.18),
f64::EPSILON, f64::EPSILON,
); );
assert_eq!(data, Some(std::f64::consts::PI)); assert_eq!(data, Some(std::f64::consts::PI));
} }
#[test] #[test]
fn to_unicode_hash() { fn to_unicode_hash() {
use ytbn_graphing_software::to_unicode_hash; use ytbn_graphing_software::to_unicode_hash;
assert_eq!(to_unicode_hash('\u{1f31e}'), "\\U1F31E"); assert_eq!(to_unicode_hash('\u{1f31e}'), "\\U1F31E");
} }
#[test] #[test]
fn to_chars_array() { fn to_chars_array() {
use ytbn_graphing_software::to_chars_array; use ytbn_graphing_software::to_chars_array;
assert_eq!( assert_eq!(
to_chars_array(vec!['\u{1f31e}', '\u{2d12c}']), to_chars_array(vec!['\u{1f31e}', '\u{2d12c}']),
r"['\u{1f31e}', '\u{2d12c}']" r"['\u{1f31e}', '\u{2d12c}']"
); );
} }

View File

@ -3,292 +3,292 @@ use std::collections::HashMap;
#[test] #[test]
fn hashmap_gen_test() { fn hashmap_gen_test() {
let data = ["time", "text", "test"]; let data = ["time", "text", "test"];
let expect = vec![ let expect = vec![
("t", "Hint::Many(&[\"ime(\", \"ext(\", \"est(\"])"), ("t", "Hint::Many(&[\"ime(\", \"ext(\", \"est(\"])"),
("te", "Hint::Many(&[\"xt(\", \"st(\"])"), ("te", "Hint::Many(&[\"xt(\", \"st(\"])"),
("tes", "Hint::Single(\"t(\")"), ("tes", "Hint::Single(\"t(\")"),
("test", "Hint::Single(\"(\")"), ("test", "Hint::Single(\"(\")"),
("tex", "Hint::Single(\"t(\")"), ("tex", "Hint::Single(\"t(\")"),
("text", "Hint::Single(\"(\")"), ("text", "Hint::Single(\"(\")"),
("ti", "Hint::Single(\"me(\")"), ("ti", "Hint::Single(\"me(\")"),
("tim", "Hint::Single(\"e(\")"), ("tim", "Hint::Single(\"e(\")"),
("time", "Hint::Single(\"(\")"), ("time", "Hint::Single(\"(\")"),
]; ];
assert_eq!( assert_eq!(
parsing::compile_hashmap(data.iter().map(|e| e.to_string()).collect()), parsing::compile_hashmap(data.iter().map(|e| e.to_string()).collect()),
expect expect
.iter() .iter()
.map(|(a, b)| (a.to_string(), b.to_string())) .map(|(a, b)| (a.to_string(), b.to_string()))
.collect::<Vec<(String, String)>>() .collect::<Vec<(String, String)>>()
); );
} }
/// Returns if function with string `func_str` is valid after processing through [`process_func_str`] /// Returns if function with string `func_str` is valid after processing through [`process_func_str`]
fn func_is_valid(func_str: &str) -> bool { fn func_is_valid(func_str: &str) -> bool {
parsing::BackingFunction::new(&parsing::process_func_str(func_str)).is_ok() parsing::BackingFunction::new(&parsing::process_func_str(func_str)).is_ok()
} }
/// Used for testing: passes function to [`process_func_str`] before running [`test_func`]. if `expect_valid` == `true`, it expects no errors to be created. /// Used for testing: passes function to [`process_func_str`] before running [`test_func`]. if `expect_valid` == `true`, it expects no errors to be created.
fn test_func_helper(func_str: &str, expect_valid: bool) { fn test_func_helper(func_str: &str, expect_valid: bool) {
let is_valid = func_is_valid(func_str); let is_valid = func_is_valid(func_str);
let string = format!( let string = format!(
"function: {} (expected: {}, got: {})", "function: {} (expected: {}, got: {})",
func_str, expect_valid, is_valid func_str, expect_valid, is_valid
); );
if is_valid == expect_valid { if is_valid == expect_valid {
println!("{}", string); println!("{}", string);
} else { } else {
panic!("{}", string); panic!("{}", string);
} }
} }
/// Tests to make sure functions that are expected to succeed, succeed. /// Tests to make sure functions that are expected to succeed, succeed.
#[test] #[test]
fn test_expected() { fn test_expected() {
let values = HashMap::from([ let values = HashMap::from([
("", true), ("", true),
("x^2", true), ("x^2", true),
("2x", true), ("2x", true),
("E^x", true), ("E^x", true),
("log10(x)", true), ("log10(x)", true),
("xxxxx", true), ("xxxxx", true),
("sin(x)", true), ("sin(x)", true),
("xsin(x)", true), ("xsin(x)", true),
("sin(x)cos(x)", true), ("sin(x)cos(x)", true),
("x/0", true), ("x/0", true),
("(x+1)(x-3)", true), ("(x+1)(x-3)", true),
("cos(xsin(x)x)", true), ("cos(xsin(x)x)", true),
("(2x+1)x", true), ("(2x+1)x", true),
("(2x+1)pi", true), ("(2x+1)pi", true),
("pi(2x+1)", true), ("pi(2x+1)", true),
("pipipipipipix", true), ("pipipipipipix", true),
("e^sin(x)", true), ("e^sin(x)", true),
("E^sin(x)", true), ("E^sin(x)", true),
("e^x", true), ("e^x", true),
("x**2", true), ("x**2", true),
("a", false), ("a", false),
("log222(x)", false), ("log222(x)", false),
("abcdef", false), ("abcdef", false),
("log10(x", false), ("log10(x", false),
("x^a", false), ("x^a", false),
("sin(cos(x)))", false), ("sin(cos(x)))", false),
("0/0", false), ("0/0", false),
]); ]);
for (key, value) in values { for (key, value) in values {
test_func_helper(key, value); test_func_helper(key, value);
} }
} }
/// Helps with tests of [`process_func_str`] /// Helps with tests of [`process_func_str`]
fn test_process_helper(input: &str, expected: &str) { fn test_process_helper(input: &str, expected: &str) {
assert_eq!(&parsing::process_func_str(input), expected); assert_eq!(&parsing::process_func_str(input), expected);
} }
/// Tests to make sure my cursed function works as intended /// Tests to make sure my cursed function works as intended
#[test] #[test]
fn func_process_test() { fn func_process_test() {
let values = HashMap::from([ let values = HashMap::from([
("2x", "2*x"), ("2x", "2*x"),
(")(", ")*("), (")(", ")*("),
("(2", "(2"), ("(2", "(2"),
("log10(x)", "log10(x)"), ("log10(x)", "log10(x)"),
("log2(x)", "log2(x)"), ("log2(x)", "log2(x)"),
("pipipipipipi", "π*π*π*π*π*π"), ("pipipipipipi", "π*π*π*π*π*π"),
("10pi", "10*π"), ("10pi", "10*π"),
("pi10", "π*10"), ("pi10", "π*10"),
("10pi10", "10*π*10"), ("10pi10", "10*π*10"),
("emax(x)", "e*max(x)"), ("emax(x)", "e*max(x)"),
("pisin(x)", "π*sin(x)"), ("pisin(x)", "π*sin(x)"),
("e^sin(x)", "e^sin(x)"), ("e^sin(x)", "e^sin(x)"),
("x**2", "x^2"), ("x**2", "x^2"),
("(x+1)(x-3)", "(x+1)*(x-3)"), ("(x+1)(x-3)", "(x+1)*(x-3)"),
]); ]);
for (key, value) in values { for (key, value) in values {
test_process_helper(key, value); test_process_helper(key, value);
} }
for func in SUPPORTED_FUNCTIONS.iter() { for func in SUPPORTED_FUNCTIONS.iter() {
let func_new = format!("{}(x)", func); let func_new = format!("{}(x)", func);
test_process_helper(&func_new, &func_new); test_process_helper(&func_new, &func_new);
} }
} }
/// Tests to make sure hints are properly outputed based on input /// Tests to make sure hints are properly outputed based on input
#[test] #[test]
fn hints() { fn hints() {
let values = HashMap::from([ let values = HashMap::from([
("", Hint::Single("x^2")), ("", Hint::Single("x^2")),
("si", Hint::Many(&["n(", "nh(", "gnum("])), ("si", Hint::Many(&["n(", "nh(", "gnum("])),
("log", Hint::Many(&["2(", "10("])), ("log", Hint::Many(&["2(", "10("])),
("cos", Hint::Many(&["(", "h("])), ("cos", Hint::Many(&["(", "h("])),
("sin(", Hint::Single(")")), ("sin(", Hint::Single(")")),
("sqrt", Hint::Single("(")), ("sqrt", Hint::Single("(")),
("ln(x)", Hint::None), ("ln(x)", Hint::None),
("ln(x)cos", Hint::Many(&["(", "h("])), ("ln(x)cos", Hint::Many(&["(", "h("])),
("ln(x)*cos", Hint::Many(&["(", "h("])), ("ln(x)*cos", Hint::Many(&["(", "h("])),
("sin(cos", Hint::Many(&["(", "h("])), ("sin(cos", Hint::Many(&["(", "h("])),
]); ]);
for (key, value) in values { for (key, value) in values {
println!("{} + {:?}", key, value); println!("{} + {:?}", key, value);
assert_eq!(parsing::generate_hint(key), &value); assert_eq!(parsing::generate_hint(key), &value);
} }
} }
#[test] #[test]
fn hint_to_string() { fn hint_to_string() {
let values = HashMap::from([ let values = HashMap::from([
("x^2", Hint::Single("x^2")), ("x^2", Hint::Single("x^2")),
( (
r#"["n(", "nh(", "gnum("]"#, r#"["n(", "nh(", "gnum("]"#,
Hint::Many(&["n(", "nh(", "gnum("]), Hint::Many(&["n(", "nh(", "gnum("]),
), ),
(r#"["n("]"#, Hint::Many(&["n("])), (r#"["n("]"#, Hint::Many(&["n("])),
("None", Hint::None), ("None", Hint::None),
]); ]);
for (key, value) in values { for (key, value) in values {
assert_eq!(value.to_string(), key); assert_eq!(value.to_string(), key);
} }
} }
#[test] #[test]
fn invalid_function() { fn invalid_function() {
use parsing::SplitType; use parsing::SplitType;
SUPPORTED_FUNCTIONS SUPPORTED_FUNCTIONS
.iter() .iter()
.flat_map(|func1| { .flat_map(|func1| {
SUPPORTED_FUNCTIONS SUPPORTED_FUNCTIONS
.iter() .iter()
.map(|func2| func1.to_string() + func2) .map(|func2| func1.to_string() + func2)
.collect::<Vec<String>>() .collect::<Vec<String>>()
}) })
.filter(|func| !SUPPORTED_FUNCTIONS.contains(&func.as_str())) .filter(|func| !SUPPORTED_FUNCTIONS.contains(&func.as_str()))
.for_each(|key| { .for_each(|key| {
let split = parsing::split_function(&key, SplitType::Multiplication); let split = parsing::split_function(&key, SplitType::Multiplication);
if split.len() != 1 { if split.len() != 1 {
panic!("failed: {} (len: {}, split: {:?})", key, split.len(), split); panic!("failed: {} (len: {}, split: {:?})", key, split.len(), split);
} }
let generated_hint = parsing::generate_hint(&key); let generated_hint = parsing::generate_hint(&key);
if generated_hint.is_none() { if generated_hint.is_none() {
println!("success: {}", key); println!("success: {}", key);
} else { } else {
panic!("failed: {} (Hint: '{}')", key, generated_hint); panic!("failed: {} (Hint: '{}')", key, generated_hint);
} }
}); });
} }
#[test] #[test]
fn split_function_multiplication() { fn split_function_multiplication() {
use parsing::SplitType; use parsing::SplitType;
let values = HashMap::from([ let values = HashMap::from([
("cos(x)", vec!["cos(x)"]), ("cos(x)", vec!["cos(x)"]),
("cos(", vec!["cos("]), ("cos(", vec!["cos("]),
("cos(x)sin(x)", vec!["cos(x)", "sin(x)"]), ("cos(x)sin(x)", vec!["cos(x)", "sin(x)"]),
("aaaaaaaaaaa", vec!["aaaaaaaaaaa"]), ("aaaaaaaaaaa", vec!["aaaaaaaaaaa"]),
("emax(x)", vec!["e", "max(x)"]), ("emax(x)", vec!["e", "max(x)"]),
("x", vec!["x"]), ("x", vec!["x"]),
("xxx", vec!["x", "x", "x"]), ("xxx", vec!["x", "x", "x"]),
("sin(cos(x)x)", vec!["sin(cos(x)", "x)"]), ("sin(cos(x)x)", vec!["sin(cos(x)", "x)"]),
("sin(x)*cos(x)", vec!["sin(x)", "cos(x)"]), ("sin(x)*cos(x)", vec!["sin(x)", "cos(x)"]),
("x*x", vec!["x", "x"]), ("x*x", vec!["x", "x"]),
("10*10", vec!["10", "10"]), ("10*10", vec!["10", "10"]),
("a1b2c3d4", vec!["a1b2c3d4"]), ("a1b2c3d4", vec!["a1b2c3d4"]),
("cos(sin(x)cos(x))", vec!["cos(sin(x)", "cos(x))"]), ("cos(sin(x)cos(x))", vec!["cos(sin(x)", "cos(x))"]),
("", Vec::new()), ("", Vec::new()),
]); ]);
for (key, value) in values { for (key, value) in values {
assert_eq!( assert_eq!(
parsing::split_function(key, SplitType::Multiplication), parsing::split_function(key, SplitType::Multiplication),
value value
); );
} }
} }
#[test] #[test]
fn split_function_terms() { fn split_function_terms() {
use parsing::SplitType; use parsing::SplitType;
let values = HashMap::from([ let values = HashMap::from([
( (
"cos(sin(x)cos(x))", "cos(sin(x)cos(x))",
vec!["cos(", "sin(", "x)", "cos(", "x))"], vec!["cos(", "sin(", "x)", "cos(", "x))"],
), ),
("", Vec::new()), ("", Vec::new()),
]); ]);
for (key, value) in values { for (key, value) in values {
assert_eq!(parsing::split_function(key, SplitType::Term), value); assert_eq!(parsing::split_function(key, SplitType::Term), value);
} }
} }
#[test] #[test]
fn hint_tests() { fn hint_tests() {
{ {
let hint = Hint::None; let hint = Hint::None;
assert!(hint.is_none()); assert!(hint.is_none());
assert!(!hint.is_some()); assert!(!hint.is_some());
assert!(!hint.is_single()); assert!(!hint.is_single());
} }
{ {
let hint = Hint::Single(""); let hint = Hint::Single("");
assert!(!hint.is_none()); assert!(!hint.is_none());
assert!(hint.is_some()); assert!(hint.is_some());
assert!(hint.is_single()); assert!(hint.is_single());
} }
{ {
let hint = Hint::Many(&[""]); let hint = Hint::Many(&[""]);
assert!(!hint.is_none()); assert!(!hint.is_none());
assert!(hint.is_some()); assert!(hint.is_some());
assert!(!hint.is_single()); assert!(!hint.is_single());
} }
} }
#[test] #[test]
fn get_last_term() { fn get_last_term() {
let values = HashMap::from([ let values = HashMap::from([
("cos(x)", "x)"), ("cos(x)", "x)"),
("cos(", "cos("), ("cos(", "cos("),
("aaaaaaaaaaa", "aaaaaaaaaaa"), ("aaaaaaaaaaa", "aaaaaaaaaaa"),
("x", "x"), ("x", "x"),
("xxx", "x"), ("xxx", "x"),
("x*x", "x"), ("x*x", "x"),
("10*10", "10"), ("10*10", "10"),
("sin(cos", "cos"), ("sin(cos", "cos"),
("exp(cos(exp(sin", "sin"), ("exp(cos(exp(sin", "sin"),
]); ]);
for (key, value) in values { for (key, value) in values {
assert_eq!( assert_eq!(
parsing::get_last_term(key.chars().collect::<Vec<char>>().as_slice()), parsing::get_last_term(key.chars().collect::<Vec<char>>().as_slice()),
Some(value.to_owned()) Some(value.to_owned())
); );
} }
} }
#[test] #[test]
fn hint_accessor() { fn hint_accessor() {
assert_eq!(Hint::Single("hint").many(), None); assert_eq!(Hint::Single("hint").many(), None);
assert_eq!(Hint::Single("hint").single(), Some("hint")); assert_eq!(Hint::Single("hint").single(), Some("hint"));
assert_eq!(Hint::Many(&["hint", "hint2"]).single(), None); assert_eq!(Hint::Many(&["hint", "hint2"]).single(), None);
assert_eq!( assert_eq!(
Hint::Many(&["hint", "hint2"]).many(), Hint::Many(&["hint", "hint2"]).many(),
Some(["hint", "hint2"].as_slice()) Some(["hint", "hint2"].as_slice())
); );
assert_eq!(Hint::None.single(), None); assert_eq!(Hint::None.single(), None);
assert_eq!(Hint::None.many(), None); assert_eq!(Hint::None.many(), None);
} }