Disallow bases lower than 2 and higher than 49

Closes #124
This commit is contained in:
PaddiM8 2023-09-15 17:24:38 +02:00
parent 76149a9f41
commit 61a6cd861d
9 changed files with 44 additions and 16 deletions

4
Cargo.lock generated
View File

@ -163,7 +163,7 @@ dependencies = [
[[package]] [[package]]
name = "kalk" name = "kalk"
version = "3.0.3" version = "3.0.4"
dependencies = [ dependencies = [
"gmp-mpfr-sys", "gmp-mpfr-sys",
"lazy_static", "lazy_static",
@ -176,7 +176,7 @@ dependencies = [
[[package]] [[package]]
name = "kalker" name = "kalker"
version = "2.0.3" version = "2.0.4"
dependencies = [ dependencies = [
"ansi_term", "ansi_term",
"atty", "atty",

View File

@ -6,13 +6,19 @@ pub(crate) const DEFAULT_PRECISION: u32 = 63;
pub fn eval(parser: &mut parser::Context, input: &str, precision: u32, base: u8) { pub fn eval(parser: &mut parser::Context, input: &str, precision: u32, base: u8) {
match parser::eval(parser, input, precision) { match parser::eval(parser, input, precision) {
Ok(Some(mut result)) => { Ok(Some(mut result)) => {
result.set_radix(base); if !result.set_radix(base) {
print_err("Invalid base. Change it by typing eg. `base 10`.");
return;
}
if precision == DEFAULT_PRECISION { if precision == DEFAULT_PRECISION {
println!("{}", result.to_string_pretty()) println!("{}", result.to_string_pretty());
} else {
println!("{}", result.to_string_big()) return;
} }
println!("{}", result.to_string_big())
} }
Ok(None) => print!(""), Ok(None) => print!(""),
Err(err) => print_err(&err.to_string()), Err(err) => print_err(&err.to_string()),

View File

@ -92,11 +92,14 @@ fn eval_repl(repl: &mut self::Context, parser: &mut parser::Context, input: &str
if let Some(base_str) = input.strip_prefix("base ") { if let Some(base_str) = input.strip_prefix("base ") {
if !base_str.is_empty() && base_str.chars().next().unwrap().is_ascii_digit() { if !base_str.is_empty() && base_str.chars().next().unwrap().is_ascii_digit() {
if let Ok(base) = base_str.parse::<u8>() { if let Ok(base) = base_str.parse::<u8>() {
repl.base = base; if base > 1 && base < 50 {
} else { repl.base = base;
eprintln!("Invalid number base"); return;
}
} }
eprintln!("Invalid number base");
return; return;
} }
} }

View File

@ -66,8 +66,14 @@ impl CalculationResult {
} }
#[wasm_bindgen(js_name = setRadix)] #[wasm_bindgen(js_name = setRadix)]
pub fn set_radix(&mut self, radix: u8) { pub fn set_radix(&mut self, radix: u8) -> bool {
if radix <= 1 || radix >= 50 {
return false;
}
self.radix = radix; self.radix = radix;
true
} }
#[wasm_bindgen(js_name = toScientificNotation)] #[wasm_bindgen(js_name = toScientificNotation)]

View File

@ -15,6 +15,7 @@ pub enum KalkError {
IncorrectAmountOfIndexes(usize, usize), IncorrectAmountOfIndexes(usize, usize),
ItemOfIndexDoesNotExist(Vec<usize>), ItemOfIndexDoesNotExist(Vec<usize>),
InconsistentColumnWidths, InconsistentColumnWidths,
InvalidBase,
InvalidComprehension(String), InvalidComprehension(String),
InvalidNumberLiteral(String), InvalidNumberLiteral(String),
InvalidOperator, InvalidOperator,
@ -58,6 +59,7 @@ impl ToString for KalkError {
), ),
KalkError::ItemOfIndexDoesNotExist(indices) => format!("Item of index ⟦{}⟧ does not exist.", indices.iter().map(|x| x.to_string()).collect::<Vec<String>>().join(", ")), KalkError::ItemOfIndexDoesNotExist(indices) => format!("Item of index ⟦{}⟧ does not exist.", indices.iter().map(|x| x.to_string()).collect::<Vec<String>>().join(", ")),
KalkError::InconsistentColumnWidths => String::from("Inconsistent column widths. Matrix columns must be the same size."), KalkError::InconsistentColumnWidths => String::from("Inconsistent column widths. Matrix columns must be the same size."),
KalkError::InvalidBase => String::from("Invalid base."),
KalkError::InvalidComprehension(x) => format!("Invalid comprehension: {}", x), KalkError::InvalidComprehension(x) => format!("Invalid comprehension: {}", x),
KalkError::InvalidNumberLiteral(x) => format!("Invalid number literal: '{}'.", x), KalkError::InvalidNumberLiteral(x) => format!("Invalid number literal: '{}'.", x),
KalkError::InvalidOperator => String::from("Invalid operator."), KalkError::InvalidOperator => String::from("Invalid operator."),

View File

@ -122,8 +122,11 @@ pub fn eval(
let result = interpreter.interpret(statements); let result = interpreter.interpret(statements);
if let Ok(Some(mut num)) = result { if let Ok(Some(mut num)) = result {
num.set_radix(context.other_radix.unwrap_or(10)); if !num.set_radix(context.other_radix.unwrap_or(10)) {
Ok(Some(num)) Err(KalkError::InvalidBase)
} else {
Ok(Some(num))
}
} else { } else {
result result
} }

View File

@ -20,7 +20,7 @@ pub fn parse_float_radix(value: &str, radix: u8) -> Option<f64> {
} }
let digit = c.to_digit(radix as u32)? as f64; let digit = c.to_digit(radix as u32)? as f64;
sum += digit * (radix as f64).powi(i as i32); sum += digit * (radix as f64).powi(i);
i -= 1; i -= 1;
} }

View File

@ -17,7 +17,7 @@
], ],
"scripts": { "scripts": {
"build": "cross-env NODE_ENV=production webpack", "build": "cross-env NODE_ENV=production webpack",
"dev": "webpack-dev-server --content-base public --hot", "dev": "NODE_OPTIONS=--openssl-legacy-provider webpack-dev-server --content-base public --hot",
"validate": "svelte-check", "validate": "svelte-check",
"prepublishOnly": "cross-env NODE_ENV=production webpack" "prepublishOnly": "cross-env NODE_ENV=production webpack"
}, },

View File

@ -101,7 +101,10 @@
try { try {
if (!kalkContext) kalkContext = new kalk.Context(); if (!kalkContext) kalkContext = new kalk.Context();
const result = kalkContext.evaluate(input.replaceAll(/\s+/g, " ")); const result = kalkContext.evaluate(input.replaceAll(/\s+/g, " "));
result?.setRadix(currentBase); console.log(result.setRadix(currentBase))
if (result && !result.setRadix(currentBase)) {
return ["Invalid base", false];
}
return [result?.toPrettyString(), true]; return [result?.toPrettyString(), true];
} catch (err) { } catch (err) {
@ -156,7 +159,12 @@
href="https://kalker.xyz/#usage" href="https://kalker.xyz/#usage"
target="blank">Link to usage guide</a>`; target="blank">Link to usage guide</a>`;
} else if (/base\s\d\d?/.test(input.trim())) { } else if (/base\s\d\d?/.test(input.trim())) {
currentBase = +input.trim().slice(5); const baseInput = Number(input.trim().slice(5));
if (baseInput <= 1 || baseInput >= 50) {
output = `<span style="color: ${errorcolor}">Invalid base.</span>`;
} else {
currentBase = baseInput;
}
} else if (input.trim() == "clear") { } else if (input.trim() == "clear") {
outputLines = []; outputLines = [];
setText(""); setText("");