From 1a814a0558be6ff41657278fe92ef2fd23c9869a Mon Sep 17 00:00:00 2001 From: Aras14HD Date: Sun, 1 Mar 2026 16:55:44 +0100 Subject: [PATCH 1/3] simplify locale: use single struct hierachy with optional fields --- Cargo.lock | 6 +- factorion-bot-discord/Cargo.toml | 4 +- factorion-bot-discord/src/main.rs | 4 +- factorion-bot-reddit/Cargo.toml | 4 +- factorion-lib/Cargo.toml | 2 +- factorion-lib/Locales.md | 142 ++++----- factorion-lib/README.md | 4 +- factorion-lib/src/calculation_results.rs | 126 ++++---- factorion-lib/src/comment.rs | 72 ++--- factorion-lib/src/de.json | 85 +++--- factorion-lib/src/en.json | 85 +++--- factorion-lib/src/en_fuck.json | 85 +++--- factorion-lib/src/it.json | 86 +++--- factorion-lib/src/locale.rs | 352 +++-------------------- factorion-lib/src/parse.rs | 240 +++++++--------- factorion-lib/src/ru.json | 176 ++++++------ 16 files changed, 585 insertions(+), 888 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 50759bfb..3f6ed617 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -399,7 +399,7 @@ dependencies = [ [[package]] name = "factorion-bot-discord" -version = "2.3.1" +version = "3.0.0" dependencies = [ "anyhow", "dotenvy", @@ -414,7 +414,7 @@ dependencies = [ [[package]] name = "factorion-bot-reddit" -version = "5.4.1" +version = "6.0.0" dependencies = [ "anyhow", "base64 0.22.1", @@ -434,7 +434,7 @@ dependencies = [ [[package]] name = "factorion-lib" -version = "4.3.1" +version = "5.0.0" dependencies = [ "arbtest", "chrono", diff --git a/factorion-bot-discord/Cargo.toml b/factorion-bot-discord/Cargo.toml index be475664..f873a632 100644 --- a/factorion-bot-discord/Cargo.toml +++ b/factorion-bot-discord/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "factorion-bot-discord" -version = "2.3.1" +version = "3.0.0" edition = "2024" description = "factorion-bot (for factorials and related) on Discord" license = "MIT" @@ -10,7 +10,7 @@ keywords = ["factorial", "termial", "bot", "math", "discord"] categories = ["mathematics", "web-programming", "parser-implementations"] [dependencies] -factorion-lib = { path = "../factorion-lib", version = "4.3.1", features = ["serde", "influxdb"] } +factorion-lib = { path = "../factorion-lib", version = "5.0.0", features = ["serde", "influxdb"] } serenity = { version = "0.12", default-features = false, features = ["client", "gateway", "rustls_backend", "model", "cache"] } tokio = { version = "1.48.0", features = ["macros", "rt-multi-thread", "time"] } dotenvy = "^0.15.7" diff --git a/factorion-bot-discord/src/main.rs b/factorion-bot-discord/src/main.rs index dcea3f11..e0d92102 100644 --- a/factorion-bot-discord/src/main.rs +++ b/factorion-bot-discord/src/main.rs @@ -94,7 +94,7 @@ async fn main() -> Result<(), Box> { std::fs::read_to_string(file.path()).unwrap().leak(), ) .unwrap(); - locale.set_bot_disclaimer("".into()); + locale.bot_disclaimer = "".into(); (file.file_name().into_string().unwrap(), locale) }) .collect::>() @@ -106,7 +106,7 @@ async fn main() -> Result<(), Box> { .unwrap_or_else(|_| { factorion_lib::locale::get_all() .map(|(k, mut v)| { - v.set_bot_disclaimer("".into()); + v.bot_disclaimer = "".into(); (k.to_owned(), v) }) .collect() diff --git a/factorion-bot-reddit/Cargo.toml b/factorion-bot-reddit/Cargo.toml index 452f00b0..19747bb5 100644 --- a/factorion-bot-reddit/Cargo.toml +++ b/factorion-bot-reddit/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "factorion-bot-reddit" -version = "5.4.1" +version = "6.0.0" edition = "2024" description = "factorion-bot (for factorials and related) on Reddit" license = "MIT" @@ -10,7 +10,7 @@ keywords = ["factorial", "termial", "bot", "math"] categories = ["mathematics", "web-programming", "parser-implementations"] [dependencies] -factorion-lib = {path = "../factorion-lib", version = "4.3.1", features = ["serde", "influxdb"]} +factorion-lib = {path = "../factorion-lib", version = "5.0.0", features = ["serde", "influxdb"]} reqwest = { version = "0.12.28", features = ["json", "native-tls"], default-features = false } serde = { version = "1.0.219", default-features = false, features = ["derive"] } serde_json = "1.0.140" diff --git a/factorion-lib/Cargo.toml b/factorion-lib/Cargo.toml index 199a3045..d2c12f9f 100644 --- a/factorion-lib/Cargo.toml +++ b/factorion-lib/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "factorion-lib" -version = "4.3.1" +version = "5.0.0" edition = "2024" description = "A library used to create bots to recognize and calculate factorials and related concepts" license = "MIT" diff --git a/factorion-lib/Locales.md b/factorion-lib/Locales.md index 86dfbbf4..6b87c39e 100644 --- a/factorion-lib/Locales.md +++ b/factorion-lib/Locales.md @@ -10,80 +10,80 @@ Locales contain a few different kinds of settings: - Toggles: on is true, off is false - Map, a list of key value pairs for certain settings, used for overrides -## V1 +## Example ```jsonc // Version number -{ "V1": - { - // The little disclaimer at the end of a comment - "bot_disclaimer": "This action was performed by a bot | [Source code](http://f.r0.fyi)", - // The notes at the beginning of a comment - "notes": { - "tower": "That is so large, that I can't even give the number of digits of it, so I have to make a power of ten tower.", - "tower_mult": "Some of these are so large, that I can't even give the number of digits of them, so I have to make a power of ten tower.", - "digits": "That number is so large, that I can't even approximate it well, so I can only give you an approximation on the number of digits.", - "digits_mult": "Some of these are so large, that I can't even approximate them well, so I can only give you an approximation on the number of digits.", - "approx": "That is so large, that I can't calculate it, so I'll have to approximate.", - "approx_mult": "Some of those are so large, that I can't calculate them, so I'll have to approximate.", - "round": "I can't calculate such a large factorial of decimals. So I had to round at some point.", - "round_mult": "I can't calculate that large factorials of decimals. So I had to round at some point.", - "too_big": "If I post the whole number, the comment would get too long. So I had to turn it into scientific notation.", - "too_big_mult": "If I post the whole numbers, the comment would get too long. So I had to turn them into scientific notation.", - "remove": "If I posted all numbers, the comment would get too long. So I had to remove some of them.", - "tetration": "That is so large, I can't even fit it in a comment with a power of 10 tower, so I'll have to use tetration!", - "no_post": "Sorry, but the reply text for all those numbers would be _really_ long, so I'd rather not even try posting lmao", - // How to call out to a user (when mentioning them). "{mention}" is replaced by the user string formatted as a mention - "mention": "Hey {mention}!" +{ + // The little disclaimer at the end of a comment + "bot_disclaimer": "This action was performed by a bot | [Source code](http://f.r0.fyi)", + // The notes at the beginning of a comment + "notes": { + "tower": "That is so large, that I can't even give the number of digits of it, so I have to make a power of ten tower.", + "tower_mult": "Some of these are so large, that I can't even give the number of digits of them, so I have to make a power of ten tower.", + "digits": "That number is so large, that I can't even approximate it well, so I can only give you an approximation on the number of digits.", + "digits_mult": "Some of these are so large, that I can't even approximate them well, so I can only give you an approximation on the number of digits.", + "approx": "That is so large, that I can't calculate it, so I'll have to approximate.", + "approx_mult": "Some of those are so large, that I can't calculate them, so I'll have to approximate.", + "round": "I can't calculate such a large factorial of decimals. So I had to round at some point.", + "round_mult": "I can't calculate that large factorials of decimals. So I had to round at some point.", + "too_big": "If I post the whole number, the comment would get too long. So I had to turn it into scientific notation.", + "too_big_mult": "If I post the whole numbers, the comment would get too long. So I had to turn them into scientific notation.", + "remove": "If I posted all numbers, the comment would get too long. So I had to remove some of them.", + "tetration": "That is so large, I can't even fit it in a comment with a power of 10 tower, so I'll have to use tetration!", + "no_post": "Sorry, but the reply text for all those numbers would be _really_ long, so I'd rather not even try posting lmao", + "limit_hit": "I have repeated myself enough, I won't do that calculation again.", + "write_out_unsupported": "I can only write out numbers in english, so I will do that.", + // How to call out to a user (when mentioning them). "{mention}" is replaced by the user string formatted as a mention + "mention": "Hey {mention}!" + }, + // Formatting calculations + "format": { + // Formatting numbers + "number_format": { + // The number decimal separator (also used when parsing). Must be a single character + "decimal": "." }, - // Formatting calculations - "format": { - // Formatting numbers - "number_format": { - // The number decimal separator (also used when parsing). Must be a single character - "decimal": "." - }, - // Whether to capitalize the start of the calculation word (sub, uple, termial or factorial) (ASCII only) - "capitalize_calc": false, - "termial": "termial", - "factorial": "factorial", - // What to call tuples. "{factorial}" is replaced by termial or factorial - "uple": "uple-{factorial}", - // What to call a subfactorial. "{factorial}" is replaced by termial (not currently) or factorial - "sub": "sub{factorial}", - // How to call a negative calculation. "{factorial}" is replaced by sub, uple, termial or factorial - "negative": "negative {factorial}", - // Overrides for individual tuples. "{factorial}" is replaced by termial or factorial - "num_overrides": { - "2": "double-{factorial}", - "3": "triple-{factorial}" - }, - // Turn off automatic tuple names (use overrides and numbers) - "force_num": false, - // How to write nested factorials. "{factorial}" is replaced by the outer calculation, "{next}" by the inner (both being negative, sub, uple, termial or factorial) - "nest": "{factorial} of {next}", - // How to write a calculation with an exact result. "{factorial}" is replaced by nest, negative, sub, uple, termial or factorial, - // "{number}" by the input to the calculation or rough_number and "{result}" by the result - "exact": "{factorial} of {number} is {result}", - // How to write a calculation with a shortened result. "{factorial}" is replaced by nest, negative, sub, uple, termial or factorial, - // "{number}" by the input to the calculation or rough_number and "{result}" by the result - "rough": "{factorial} of {number} is roughly {result}", - // How to write a calculation with an approximate result. "{factorial}" is replaced by nest, negative, sub, uple, termial or factorial, - // "{number}" by the input to the calculation or rough_number and "{result}" by the result - "approx": "{factorial} of {number} is approximately {result}", - // How to write a calculation with a result given in approximate number of digits. "{factorial}" is replaced by nest, negative, sub, uple, termial or factorial, - // "{number}" by the input to the calculation or rough_number and "{result}" by the result - "digits": "{factorial} of {number} has approximately {result} digits", - // How to write a calculation with a result given in a power-of-ten tower number of digits. - // "{factorial}" is replaced by nest, negative, sub, uple, termial or factorial, - // "{number}" by the input to the calculation or rough_number and "{result}" by the result - "order": "{factorial} of {number} has on the order of {result} digits", - // How to write a calculation with a result given in tetration of ten number of digits, and no calculation steps. - // "{factorial}" is replaced by nest, negative, sub, uple, termial or factorial, - // "{number}" by the input to the calculation or rough_number and "{result}" by the result - "all_that": "All that of {number} has on the order of {result} digits", - // How to write a shortened number. "{number}" is replaced by the input to the calculation - "rough_number": "roughly {number}" - } + // Whether to capitalize the start of the calculation word (sub, uple, termial or factorial) (ASCII only) + "capitalize_calc": false, + "termial": "termial", + "factorial": "factorial", + // What to call tuples. "{factorial}" is replaced by termial or factorial + "uple": "uple-{factorial}", + // What to call a subfactorial. "{factorial}" is replaced by termial (not currently) or factorial + "sub": "sub{factorial}", + // How to call a negative calculation. "{factorial}" is replaced by sub, uple, termial or factorial + "negative": "negative {factorial}", + // Overrides for individual tuples. "{factorial}" is replaced by termial or factorial + "num_overrides": { + "2": "double-{factorial}", + "3": "triple-{factorial}" + }, + // Turn off automatic tuple names (use overrides and numbers) + "force_num": false, + // How to write nested factorials. "{factorial}" is replaced by the outer calculation, "{next}" by the inner (both being negative, sub, uple, termial or factorial) + "nest": "{factorial} of {next}", + // How to write a calculation with an exact result. "{factorial}" is replaced by nest, negative, sub, uple, termial or factorial, + // "{number}" by the input to the calculation or rough_number and "{result}" by the result + "exact": "{factorial} of {number} is {result}", + // How to write a calculation with a shortened result. "{factorial}" is replaced by nest, negative, sub, uple, termial or factorial, + // "{number}" by the input to the calculation or rough_number and "{result}" by the result + "rough": "{factorial} of {number} is roughly {result}", + // How to write a calculation with an approximate result. "{factorial}" is replaced by nest, negative, sub, uple, termial or factorial, + // "{number}" by the input to the calculation or rough_number and "{result}" by the result + "approx": "{factorial} of {number} is approximately {result}", + // How to write a calculation with a result given in approximate number of digits. "{factorial}" is replaced by nest, negative, sub, uple, termial or factorial, + // "{number}" by the input to the calculation or rough_number and "{result}" by the result + "digits": "{factorial} of {number} has approximately {result} digits", + // How to write a calculation with a result given in a power-of-ten tower number of digits. + // "{factorial}" is replaced by nest, negative, sub, uple, termial or factorial, + // "{number}" by the input to the calculation or rough_number and "{result}" by the result + "order": "{factorial} of {number} has on the order of {result} digits", + // How to write a calculation with a result given in tetration of ten number of digits, and no calculation steps. + // "{factorial}" is replaced by nest, negative, sub, uple, termial or factorial, + // "{number}" by the input to the calculation or rough_number and "{result}" by the result + "all_that": "All that of {number} has on the order of {result} digits", + // How to write a shortened number. "{number}" is replaced by the input to the calculation + "rough_number": "roughly {number}" } } ``` diff --git a/factorion-lib/README.md b/factorion-lib/README.md index a4c18d09..4a9000ce 100644 --- a/factorion-lib/README.md +++ b/factorion-lib/README.md @@ -35,7 +35,7 @@ use factorion_lib::{parse::parse, calculation_tasks::{CalculationJob, Calculatio let consts = Consts::default(); let locale = consts.locales.get("en").unwrap(); // Parse the text for calculations -let calculations: Vec = parse("Some text with factorial 4!", true, &consts, &locale.format().number_format()); +let calculations: Vec = parse("Some text with factorial 4!", true, &consts, &locale.format.number_format); // These are given in an intemediate format for delayed calculation assert_eq!(calculations, [CalculationJob { // The base may be a number or another job @@ -61,6 +61,6 @@ assert_eq!(results, [ let result = results.remove(0); let mut formatted = String::new(); // Write the formatted result to a string (for efficiency). We don't want to shorten anything below that huge number -result.format(&mut formatted, false, false, &10000000000000000000u128.into(), &consts, &locale.format()).unwrap(); +result.format(&mut formatted, false, false, &10000000000000000000u128.into(), &consts, &locale.format).unwrap(); assert_eq!(formatted, "Factorial of 4 is 24 \n\n"); ``` diff --git a/factorion-lib/src/calculation_results.rs b/factorion-lib/src/calculation_results.rs index ea4400fb..d9652006 100644 --- a/factorion-lib/src/calculation_results.rs +++ b/factorion-lib/src/calculation_results.rs @@ -210,8 +210,8 @@ impl CalculationResult { acc.write_str("∞\u{0303}")?; } } - if *locale.decimal() != '.' { - let decimal = locale.decimal().to_string(); + if locale.decimal != '.' { + let decimal = locale.decimal.to_string(); while start < acc.len() { start = replace(acc, start, ".", &decimal); } @@ -300,17 +300,17 @@ impl Calculation { agressive_shorten && self.steps.len() > 1, ) { // All that - (_, _, true) => locale.all_that(), + (_, _, true) => &locale.all_that, // on the order - (_, CalculationResult::ApproximateDigitsTower(_, _, _, _), _) => locale.order(), + (_, CalculationResult::ApproximateDigitsTower(_, _, _, _), _) => &locale.order, // digits - (_, CalculationResult::ApproximateDigits(_, _), _) => locale.digits(), + (_, CalculationResult::ApproximateDigits(_, _), _) => &locale.digits, // approximately (Number::Float(_), _, _) | (_, CalculationResult::Approximate(_, _), _) => { - locale.approx() + &locale.approx } // is - _ => locale.exact(), + _ => &locale.exact, }, )?; acc.write_str(" \n\n")?; @@ -324,10 +324,10 @@ impl Calculation { agressive_shorten, true, consts, - &locale.number_format(), + &locale.number_format, )?; if rough { - replace(acc, frame_start, "{number}", locale.rough_number()); + replace(acc, frame_start, "{number}", &locale.rough_number); } replace(acc, frame_start, "{number}", &number); replace(acc, frame_start, "{result}", "{number}"); @@ -340,10 +340,10 @@ impl Calculation { agressive_shorten, false, consts, - &locale.number_format(), + &locale.number_format, )?; if rough { - replace(acc, frame_start, "{number}", locale.rough_number()); + replace(acc, frame_start, "{number}", &locale.rough_number); } replace(acc, frame_start, "{number}", &number); @@ -351,7 +351,7 @@ impl Calculation { let mut start = frame_start; for (i, (level, neg)) in self.steps.iter().copied().rev().enumerate() { if i != len - 1 { - replace(acc, start, "{factorial}", locale.nest()); + replace(acc, start, "{factorial}", &locale.nest); } if neg { @@ -370,12 +370,12 @@ impl Calculation { start, "{factorial}", if level < 0 { - locale.termial() + &locale.termial } else { - locale.factorial() + &locale.factorial }, ); - if *locale.capitalize_calc() { + if locale.capitalize_calc { let mut ind = acc[calc_start..].char_indices(); if let Some((start, _)) = ind.next() && let Some((end, _)) = ind.next() @@ -449,13 +449,13 @@ impl Calculation { false, false, false, false, false, false, false, false, false, false, ], ]; - if let Some(s) = locale.num_overrides().get(&level) { + if let Some(s) = locale.num_overrides.get(&level) { return s.as_ref().into(); } match level { - 0 => locale.sub().as_ref().into(), + 0 => locale.sub.as_ref().into(), 1 => "{factorial}".into(), - ..=9999 if !locale.force_num() => { + ..=9999 if !locale.force_num => { let singles = if level < 10 { SINGLES_LAST } else { SINGLES }; let mut acc = String::new(); let mut n = level; @@ -481,7 +481,7 @@ impl Calculation { if BINDING_T[last_written.0][last_written.1 as usize] { acc.write_str("t").unwrap(); } - acc.write_str(locale.uple()).unwrap(); + acc.write_str(&locale.uple).unwrap(); acc.into() } @@ -684,64 +684,64 @@ mod tests { fn test_factorial_level_string() { let en = locale::get_en(); assert_eq!( - Calculation::get_factorial_level_string(1, &en.format()), + Calculation::get_factorial_level_string(1, &en.format), "{factorial}" ); assert_eq!( - Calculation::get_factorial_level_string(2, &en.format()), + Calculation::get_factorial_level_string(2, &en.format), "double-{factorial}" ); assert_eq!( - Calculation::get_factorial_level_string(3, &en.format()), + Calculation::get_factorial_level_string(3, &en.format), "triple-{factorial}" ); assert_eq!( - Calculation::get_factorial_level_string(10, &en.format()), + Calculation::get_factorial_level_string(10, &en.format), "decuple-{factorial}" ); assert_eq!( - Calculation::get_factorial_level_string(45, &en.format()), + Calculation::get_factorial_level_string(45, &en.format), "quinquadragintuple-{factorial}" ); assert_eq!( - Calculation::get_factorial_level_string(50, &en.format()), + Calculation::get_factorial_level_string(50, &en.format), "quinquagintuple-{factorial}" ); assert_eq!( - Calculation::get_factorial_level_string(100, &en.format()), + Calculation::get_factorial_level_string(100, &en.format), "centuple-{factorial}" ); assert_eq!( - Calculation::get_factorial_level_string(521, &en.format()), + Calculation::get_factorial_level_string(521, &en.format), "unviginquingentuple-{factorial}" ); assert_eq!( - Calculation::get_factorial_level_string(1000, &en.format()), + Calculation::get_factorial_level_string(1000, &en.format), "milluple-{factorial}" ); assert_eq!( - Calculation::get_factorial_level_string(4321, &en.format()), + Calculation::get_factorial_level_string(4321, &en.format), "unvigintricenquadrilluple-{factorial}" ); assert_eq!( - Calculation::get_factorial_level_string(10000, &en.format()), + Calculation::get_factorial_level_string(10000, &en.format), "10000-{factorial}" ); let de = locale::get_de(); assert_eq!( - Calculation::get_factorial_level_string(1, &de.format()), + Calculation::get_factorial_level_string(1, &de.format), "{factorial}" ); assert_eq!( - Calculation::get_factorial_level_string(2, &de.format()), + Calculation::get_factorial_level_string(2, &de.format), "doppel{factorial}" ); assert_eq!( - Calculation::get_factorial_level_string(3, &de.format()), + Calculation::get_factorial_level_string(3, &de.format), "trippel{factorial}" ); assert_eq!( - Calculation::get_factorial_level_string(45, &de.format()), + Calculation::get_factorial_level_string(45, &de.format), "quinquadragintupel{factorial}" ); } @@ -818,7 +818,7 @@ mod tests { false, &TOO_BIG_NUMBER, &consts, - &consts.locales.get("en").unwrap().format(), + &consts.locales.get("en").unwrap().format, ) .unwrap(); assert_eq!(acc, "Factorial of 5 is 120 \n\n"); @@ -836,7 +836,7 @@ mod tests { false, &TOO_BIG_NUMBER, &consts, - &consts.locales.get("en").unwrap().format(), + &consts.locales.get("en").unwrap().format, ) .unwrap(); assert_eq!(acc, "Subfactorial of 5 is 120 \n\n"); @@ -857,7 +857,7 @@ mod tests { false, &TOO_BIG_NUMBER, &consts, - &consts.locales.get("en").unwrap().format(), + &consts.locales.get("en").unwrap().format, ) .unwrap(); assert_eq!(acc, "Factorial of 5 is approximately 1.2 × 10^5 \n\n"); @@ -875,7 +875,7 @@ mod tests { false, &TOO_BIG_NUMBER, &consts, - &consts.locales.get("en").unwrap().format(), + &consts.locales.get("en").unwrap().format, ) .unwrap(); assert_eq!(acc, "Factorial of 5 has approximately 3 digits \n\n"); @@ -893,7 +893,7 @@ mod tests { false, &TOO_BIG_NUMBER, &consts, - &consts.locales.get("en").unwrap().format(), + &consts.locales.get("en").unwrap().format, ) .unwrap(); assert_eq!(acc, "Factorial of 5 is 120 \n\n"); @@ -929,7 +929,7 @@ mod test { false, &TOO_BIG_NUMBER, &consts, - &consts.locales.get("en").unwrap().format(), + &consts.locales.get("en").unwrap().format, ) .unwrap(); assert_eq!(s, "Triple-factorial of 10 is 280 \n\n"); @@ -949,7 +949,7 @@ mod test { false, &TOO_BIG_NUMBER, &consts, - &consts.locales.get("en").unwrap().format(), + &consts.locales.get("en").unwrap().format, ) .unwrap(); assert_eq!(s, "Triple-factorial of 0.5 is approximately 280 \n\n"); @@ -969,7 +969,7 @@ mod test { false, &TOO_BIG_NUMBER, &consts, - &consts.locales.get("en").unwrap().format(), + &consts.locales.get("en").unwrap().format, ) .unwrap(); assert_eq!(s, "Triple-factorial of 10 is 280 \n\n"); @@ -991,7 +991,7 @@ mod test { false, &TOO_BIG_NUMBER, &consts, - &consts.locales.get("en").unwrap().format(), + &consts.locales.get("en").unwrap().format, ) .unwrap(); assert_eq!( @@ -1016,7 +1016,7 @@ mod test { false, &TOO_BIG_NUMBER, &consts, - &consts.locales.get("en").unwrap().format(), + &consts.locales.get("en").unwrap().format, ) .unwrap(); assert_eq!( @@ -1039,7 +1039,7 @@ mod test { false, &TOO_BIG_NUMBER, &consts, - &consts.locales.get("en").unwrap().format(), + &consts.locales.get("en").unwrap().format, ) .unwrap(); assert_eq!(s, "Factorial of triple-factorial of 5 is 3628800 \n\n"); @@ -1059,7 +1059,7 @@ mod test { false, &TOO_BIG_NUMBER, &consts, - &consts.locales.get("en").unwrap().format(), + &consts.locales.get("en").unwrap().format, ) .unwrap(); assert_eq!(s, "Negative factorial of 0 is 3628800 \n\n"); @@ -1082,7 +1082,7 @@ mod test { false, &TOO_BIG_NUMBER, &consts, - &consts.locales.get("en").unwrap().format(), + &consts.locales.get("en").unwrap().format, ) .unwrap(); assert_eq!(s, "Factorial of 0 is approximately 2.83947 × 10^10043 \n\n"); @@ -1102,7 +1102,7 @@ mod test { false, &TOO_BIG_NUMBER, &consts, - &consts.locales.get("en").unwrap().format(), + &consts.locales.get("en").unwrap().format, ) .unwrap(); assert_eq!(s, "Factorial of 0 has approximately 10043394 digits \n\n"); @@ -1122,7 +1122,7 @@ mod test { false, &TOO_BIG_NUMBER, &consts, - &consts.locales.get("en").unwrap().format(), + &consts.locales.get("en").unwrap().format, ) .unwrap(); assert_eq!(s, "Factorial of 0 is ∞\u{0303} \n\n"); @@ -1142,7 +1142,7 @@ mod test { false, &TOO_BIG_NUMBER, &consts, - &consts.locales.get("en").unwrap().format(), + &consts.locales.get("en").unwrap().format, ) .unwrap(); assert_eq!( @@ -1165,7 +1165,7 @@ mod test { false, &TOO_BIG_NUMBER, &consts, - &consts.locales.get("en").unwrap().format(), + &consts.locales.get("en").unwrap().format, ) .unwrap(); assert_eq!( @@ -1188,7 +1188,7 @@ mod test { true, &TOO_BIG_NUMBER, &consts, - &consts.locales.get("en").unwrap().format(), + &consts.locales.get("en").unwrap().format, ) .unwrap(); assert_eq!(s, "All that of 0 has on the order of ^(10)10 digits \n\n"); @@ -1212,7 +1212,7 @@ mod test { false, &TOO_BIG_NUMBER, &consts, - &consts.locales.get("en").unwrap().format(), + &consts.locales.get("en").unwrap().format, ) .unwrap(); assert_eq!(s, "Factorial of 9.2 is approximately 893.83924421 \n\n"); @@ -1236,7 +1236,7 @@ mod test { false, &TOO_BIG_NUMBER, &consts, - &consts.locales.get("en").unwrap().format(), + &consts.locales.get("en").unwrap().format, ) .unwrap(); assert_eq!( @@ -1264,7 +1264,7 @@ mod test { false, &TOO_BIG_NUMBER, &consts, - &consts.locales.get("en").unwrap().format(), + &consts.locales.get("en").unwrap().format, ) .unwrap(); assert_eq!( @@ -1292,7 +1292,7 @@ mod test { false, &TOO_BIG_NUMBER, &consts, - &consts.locales.get("en").unwrap().format(), + &consts.locales.get("en").unwrap().format, ) .unwrap(); assert_eq!( @@ -1322,7 +1322,7 @@ mod test { false, &TOO_BIG_NUMBER, &consts, - &consts.locales.get("en").unwrap().format(), + &consts.locales.get("en").unwrap().format, ) .unwrap(); assert_eq!( @@ -1349,7 +1349,7 @@ mod test { false, &TOO_BIG_NUMBER, &consts, - &consts.locales.get("en").unwrap().format(), + &consts.locales.get("en").unwrap().format, ) .unwrap(); assert_eq!( @@ -1373,7 +1373,7 @@ mod test { false, &TOO_BIG_NUMBER, &consts, - &consts.locales.get("en").unwrap().format(), + &consts.locales.get("en").unwrap().format, ) .unwrap(); assert_eq!(s, "Factorial of 0 has on the order of ^(4)10 digits \n\n"); @@ -1458,7 +1458,7 @@ mod test { false, false, &consts, - &locale::NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &locale::NumFormat { decimal: '.' }, ) .unwrap(); assert_eq!(acc, "4.9814983749 × 10^1017"); @@ -1474,7 +1474,7 @@ mod test { false, false, &consts, - &locale::NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &locale::NumFormat { decimal: '.' }, ) .unwrap(); assert_eq!(acc, "4.9814983749 × 10^(1017)"); @@ -1490,7 +1490,7 @@ mod test { false, false, &consts, - &locale::NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &locale::NumFormat { decimal: '.' }, ) .unwrap(); assert_eq!(acc, "4.9814983749234732849839849898438493843 × 10^1037"); @@ -1510,7 +1510,7 @@ mod test { false, false, &consts, - &locale::NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &locale::NumFormat { decimal: '.' }, ) .unwrap(); assert_eq!(acc, "4.9814983749234732849839849898438493843 × 10^(1037)"); diff --git a/factorion-lib/src/comment.rs b/factorion-lib/src/comment.rs index c5e175f2..19d50adf 100644 --- a/factorion-lib/src/comment.rs +++ b/factorion-lib/src/comment.rs @@ -372,8 +372,8 @@ impl CommentConstructed { .locales .get(&locale) .unwrap_or(consts.locales.get(&consts.default_locale).unwrap()) - .format() - .number_format(), + .format + .number_format, ); if commands.nested { @@ -502,7 +502,7 @@ impl CommentCalculated { let mut note = self .notify .as_ref() - .map(|user| locale.notes().mention().replace("{mention}", user) + "\n\n") + .map(|user| locale.notes.mention.replace("{mention}", user) + "\n\n") .unwrap_or_default(); if fell_back { @@ -518,9 +518,16 @@ impl CommentCalculated { let multiple = self.calculation_list.len() > 1; if !self.commands.no_note { if self.status.limit_hit { - let _ = note.write_str(locale.notes().limit_hit().map(AsRef::as_ref).unwrap_or( - "I have repeated myself enough, I won't do that calculation again.", - )); + let _ = note.write_str( + locale + .notes + .limit_hit + .as_ref() + .map(AsRef::as_ref) + .unwrap_or( + "I have repeated myself enough, I won't do that calculation again.", + ), + ); let _ = note.write_str("\n\n"); } else if self .calculation_list @@ -528,10 +535,10 @@ impl CommentCalculated { .any(Calculation::is_digit_tower) { if multiple { - let _ = note.write_str(locale.notes().tower_mult()); + let _ = note.write_str(&locale.notes.tower_mult); let _ = note.write_str("\n\n"); } else { - let _ = note.write_str(locale.notes().tower()); + let _ = note.write_str(&locale.notes.tower); let _ = note.write_str("\n\n"); } } else if self @@ -540,10 +547,10 @@ impl CommentCalculated { .any(Calculation::is_aproximate_digits) { if multiple { - let _ = note.write_str(locale.notes().digits_mult()); + let _ = note.write_str(&locale.notes.digits_mult); let _ = note.write_str("\n\n"); } else { - let _ = note.write_str(locale.notes().digits()); + let _ = note.write_str(&locale.notes.digits); let _ = note.write_str("\n\n"); } } else if self @@ -552,18 +559,18 @@ impl CommentCalculated { .any(Calculation::is_approximate) { if multiple { - let _ = note.write_str(locale.notes().approx_mult()); + let _ = note.write_str(&locale.notes.approx_mult); let _ = note.write_str("\n\n"); } else { - let _ = note.write_str(locale.notes().approx()); + let _ = note.write_str(&locale.notes.approx); let _ = note.write_str("\n\n"); } } else if self.calculation_list.iter().any(Calculation::is_rounded) { if multiple { - let _ = note.write_str(locale.notes().round_mult()); + let _ = note.write_str(&locale.notes.round_mult); let _ = note.write_str("\n\n"); } else { - let _ = note.write_str(locale.notes().round()); + let _ = note.write_str(&locale.notes.round); let _ = note.write_str("\n\n"); } } else if self @@ -572,10 +579,10 @@ impl CommentCalculated { .any(|c| c.is_too_long(too_big_number)) { if multiple { - let _ = note.write_str(locale.notes().too_big_mult()); + let _ = note.write_str(&locale.notes.too_big_mult); let _ = note.write_str("\n\n"); } else { - let _ = note.write_str(locale.notes().too_big()); + let _ = note.write_str(&locale.notes.too_big); let _ = note.write_str("\n\n"); } } @@ -592,13 +599,13 @@ impl CommentCalculated { false, too_big_number, consts, - &locale.format(), + &locale.format, ); acc }); // If the reply was too long try force shortening all factorials - if reply.len() + locale.bot_disclaimer().len() + 16 > self.max_length + if reply.len() + locale.bot_disclaimer.len() + 16 > self.max_length && !self.commands.shorten && !self .calculation_list @@ -607,9 +614,9 @@ impl CommentCalculated { { if note.is_empty() && !self.commands.no_note { if multiple { - let _ = note.write_str(locale.notes().too_big_mult()); + let _ = note.write_str(&locale.notes.too_big_mult); } else { - let _ = note.write_str(locale.notes().too_big()); + let _ = note.write_str(&locale.notes.too_big); } let _ = note.write_str("\n\n"); }; @@ -623,20 +630,19 @@ impl CommentCalculated { false, too_big_number, consts, - &locale.format(), + &locale.format, ); acc }); } let note = if !self.commands.no_note { - locale.notes().tetration().clone().into_owned() + "\n\n" + locale.notes.tetration.clone().into_owned() + "\n\n" } else { String::new() }; // If the reply was too long try agressive shortening all factorials - if reply.len() + locale.bot_disclaimer().len() + 16 > self.max_length - && !self.commands.steps + if reply.len() + locale.bot_disclaimer.len() + 16 > self.max_length && !self.commands.steps { reply = self .calculation_list @@ -648,19 +654,19 @@ impl CommentCalculated { true, too_big_number, consts, - &locale.format(), + &locale.format, ); acc }); } let note = if !self.commands.no_note { - locale.notes().remove().clone().into_owned() + "\n\n" + locale.notes.remove.clone().into_owned() + "\n\n" } else { String::new() }; // Remove factorials until we can fit them in a comment - if reply.len() + locale.bot_disclaimer().len() + 16 > self.max_length { + if reply.len() + locale.bot_disclaimer.len() + 16 > self.max_length { let mut factorial_list: Vec = self .calculation_list .iter() @@ -672,7 +678,7 @@ impl CommentCalculated { !self.commands.steps, too_big_number, consts, - &locale.format(), + &locale.format, ); res }) @@ -680,14 +686,14 @@ impl CommentCalculated { 'drop_last: { while note.len() + factorial_list.iter().map(|s| s.len()).sum::() - + locale.bot_disclaimer().len() + + locale.bot_disclaimer.len() + 16 > self.max_length { // remove last factorial (probably the biggest) factorial_list.pop(); if factorial_list.is_empty() { - reply = locale.notes().no_post().to_string(); + reply = locale.notes.no_post.to_string(); break 'drop_last; } } @@ -697,9 +703,9 @@ impl CommentCalculated { }); } } - if !locale.bot_disclaimer().is_empty() { + if !locale.bot_disclaimer.is_empty() { reply.push_str("\n*^("); - reply.push_str(locale.bot_disclaimer()); + reply.push_str(&locale.bot_disclaimer); reply.push_str(")*"); } reply @@ -727,7 +733,7 @@ mod tests { "24! -24! 2!? (2!?)!", true, &consts, - &NumFormat::V1(&crate::locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!( jobs, diff --git a/factorion-lib/src/de.json b/factorion-lib/src/de.json index a299a849..4ce9330d 100644 --- a/factorion-lib/src/de.json +++ b/factorion-lib/src/de.json @@ -1,46 +1,45 @@ -{"V2": - { - "bot_disclaimer": "Dieser Kommentar wurde automatisch geschrieben | [Quelltext](http://f.r0.fyi)", - "notes": { - "tower": "Das ist so groß, dass ich nicht mal die Anzahl der Ziffern angeben kann. Also habe ich Zehn-hoch Turm gebaut.", - "tower_mult": "Manche von denen sind so groß, dass ich nicht mal die Anzahl der Ziffern angeben kann. Also habe ich Zehn-hoch-Turm gebaut.", - "digits": "Das ist so groß, dass ich nicht mal eine gute Annäherung geben kann. Also muss ich eine Annäherung für die Anzahl der Ziffern geben.", - "digits_mult": "Manche von denen sind so groß, dass ich nicht mal eine gute Annäherung geben kann. Also muss ich eine Annäherung für die Anzahl der Ziffern geben.", - "approx": "Das ist so groß, dass ich es nicht errechnen kann. Also muss ich eine Annäherung geben.", - "approx_mult": "Manche von denen sind so groß, dass ich es nicht errechnen kann. Also muss ich eine Annäherung geben.", - "round": "So eine große Fakultät kann ich nicht von einer Kommazahl errechnen. Also muss ich irgendwann runden.", - "round_mult": "So große Fakultäten kann ich nicht von Kommazahlen errechnen. Also muss ich irgendwann runden.", - "too_big": "Wenn ich die Zahl ausschreiben würde, wäre der Kommentar zu lang. Also muss ich die wissenschaftliche Schreibweise nutzen.", - "too_big_mult": "Wenn ich die Zahlen ausschreiben würde, wäre der Kommentar zu lang. Also muss ich die wissenschaftliche Schreibweise nutzen.", - "remove": "Wenn ich alle Zahlen angeben würde, wäre der Kommentar zu lang. Also muss ich welche rausnehmen.", - "tetration": "Das ist so groß, dass selbst der Zehn-hoch-Turm nicht mehr in den Kommentar passt. Also muss ich tetrieren.", - "no_post": "Sorry, die Antwort für all das wäre einfach _zu_ lang. Ich probier lieber nicht das zu schicken lmao", - "limit_hit": "I habe mich genug wiederholt, das werde ich nicht nochmal berechnen.", - "mention": "Hey {mention}!" +{ + "bot_disclaimer": "Dieser Kommentar wurde automatisch geschrieben | [Quelltext](http://f.r0.fyi)", + "notes": { + "tower": "Das ist so groß, dass ich nicht mal die Anzahl der Ziffern angeben kann. Also habe ich Zehn-hoch Turm gebaut.", + "tower_mult": "Manche von denen sind so groß, dass ich nicht mal die Anzahl der Ziffern angeben kann. Also habe ich Zehn-hoch-Turm gebaut.", + "digits": "Das ist so groß, dass ich nicht mal eine gute Annäherung geben kann. Also muss ich eine Annäherung für die Anzahl der Ziffern geben.", + "digits_mult": "Manche von denen sind so groß, dass ich nicht mal eine gute Annäherung geben kann. Also muss ich eine Annäherung für die Anzahl der Ziffern geben.", + "approx": "Das ist so groß, dass ich es nicht errechnen kann. Also muss ich eine Annäherung geben.", + "approx_mult": "Manche von denen sind so groß, dass ich es nicht errechnen kann. Also muss ich eine Annäherung geben.", + "round": "So eine große Fakultät kann ich nicht von einer Kommazahl errechnen. Also muss ich irgendwann runden.", + "round_mult": "So große Fakultäten kann ich nicht von Kommazahlen errechnen. Also muss ich irgendwann runden.", + "too_big": "Wenn ich die Zahl ausschreiben würde, wäre der Kommentar zu lang. Also muss ich die wissenschaftliche Schreibweise nutzen.", + "too_big_mult": "Wenn ich die Zahlen ausschreiben würde, wäre der Kommentar zu lang. Also muss ich die wissenschaftliche Schreibweise nutzen.", + "remove": "Wenn ich alle Zahlen angeben würde, wäre der Kommentar zu lang. Also muss ich welche rausnehmen.", + "tetration": "Das ist so groß, dass selbst der Zehn-hoch-Turm nicht mehr in den Kommentar passt. Also muss ich tetrieren.", + "no_post": "Sorry, die Antwort für all das wäre einfach _zu_ lang. Ich probier lieber nicht das zu schicken lmao", + "limit_hit": "I habe mich genug wiederholt, das werde ich nicht nochmal berechnen.", + "write_out_unsupported": "Ich kann nur in Englisch Zahlen ausschreiben, also werde ich das tun.", + "mention": "Hey {mention}!" + }, + "format": { + "number_format": { + "decimal": "," }, - "format": { - "number_format": { - "decimal": "," - }, - "capitalize_calc": true, - "termial": "termial", - "factorial": "fakultät", - "uple": "upel{factorial}", - "sub": "sub{factorial}", - "negative": "negative {factorial}", - "num_overrides": { - "2": "doppel{factorial}", - "3": "trippel{factorial}" - }, - "force_num": false, - "nest": "{factorial} von {next}", - "exact": "{factorial} von {number} ist {result}", - "rough": "{factorial} von {number} ist grob {result}", - "approx": "{factorial} von {number} ist ungefähr {result}", - "digits": "{factorial} von {number} hat ungefähr {result} Ziffern", - "order": "{factorial} von {number} hat eine Größenordnung von {result} Ziffern", - "all_that": "All das von {number} hat eine Größenordnung von {result} Ziffern", - "rough_number": "grob {number}" - } + "capitalize_calc": true, + "termial": "termial", + "factorial": "fakultät", + "uple": "upel{factorial}", + "sub": "sub{factorial}", + "negative": "negative {factorial}", + "num_overrides": { + "2": "doppel{factorial}", + "3": "trippel{factorial}" + }, + "force_num": false, + "nest": "{factorial} von {next}", + "exact": "{factorial} von {number} ist {result}", + "rough": "{factorial} von {number} ist grob {result}", + "approx": "{factorial} von {number} ist ungefähr {result}", + "digits": "{factorial} von {number} hat ungefähr {result} Ziffern", + "order": "{factorial} von {number} hat eine Größenordnung von {result} Ziffern", + "all_that": "All das von {number} hat eine Größenordnung von {result} Ziffern", + "rough_number": "grob {number}" } } diff --git a/factorion-lib/src/en.json b/factorion-lib/src/en.json index a092b0f6..53815485 100644 --- a/factorion-lib/src/en.json +++ b/factorion-lib/src/en.json @@ -1,46 +1,45 @@ -{ "V2": - { - "bot_disclaimer": "This action was performed by a bot | [Source code](http://f.r0.fyi)", - "notes": { - "tower": "That is so large, that I can't even give the number of digits of it, so I have to make a power of ten tower.", - "tower_mult": "Some of these are so large, that I can't even give the number of digits of them, so I have to make a power of ten tower.", - "digits": "That number is so large, that I can't even approximate it well, so I can only give you an approximation on the number of digits.", - "digits_mult": "Some of these are so large, that I can't even approximate them well, so I can only give you an approximation on the number of digits.", - "approx": "That is so large, that I can't calculate it, so I'll have to approximate.", - "approx_mult": "Some of those are so large, that I can't calculate them, so I'll have to approximate.", - "round": "I can't calculate such a large factorial of decimals. So I had to round at some point.", - "round_mult": "I can't calculate that large factorials of decimals. So I had to round at some point.", - "too_big": "If I post the whole number, the comment would get too long. So I had to turn it into scientific notation.", - "too_big_mult": "If I post the whole numbers, the comment would get too long. So I had to turn them into scientific notation.", - "remove": "If I posted all numbers, the comment would get too long. So I had to remove some of them.", - "tetration": "That is so large, I can't even fit it in a comment with a power of 10 tower, so I'll have to use tetration!", - "no_post": "Sorry, but the reply text for all those numbers would be _really_ long, so I'd rather not even try posting lmao", - "limit_hit": "I have repeated myself enough, I won't do that calculation again.", - "mention": "Hey {mention}!" +{ + "bot_disclaimer": "This action was performed by a bot | [Source code](http://f.r0.fyi)", + "notes": { + "tower": "That is so large, that I can't even give the number of digits of it, so I have to make a power of ten tower.", + "tower_mult": "Some of these are so large, that I can't even give the number of digits of them, so I have to make a power of ten tower.", + "digits": "That number is so large, that I can't even approximate it well, so I can only give you an approximation on the number of digits.", + "digits_mult": "Some of these are so large, that I can't even approximate them well, so I can only give you an approximation on the number of digits.", + "approx": "That is so large, that I can't calculate it, so I'll have to approximate.", + "approx_mult": "Some of those are so large, that I can't calculate them, so I'll have to approximate.", + "round": "I can't calculate such a large factorial of decimals. So I had to round at some point.", + "round_mult": "I can't calculate that large factorials of decimals. So I had to round at some point.", + "too_big": "If I post the whole number, the comment would get too long. So I had to turn it into scientific notation.", + "too_big_mult": "If I post the whole numbers, the comment would get too long. So I had to turn them into scientific notation.", + "remove": "If I posted all numbers, the comment would get too long. So I had to remove some of them.", + "tetration": "That is so large, I can't even fit it in a comment with a power of 10 tower, so I'll have to use tetration!", + "no_post": "Sorry, but the reply text for all those numbers would be _really_ long, so I'd rather not even try posting lmao", + "limit_hit": "I have repeated myself enough, I won't do that calculation again.", + "write_out_unsupported": "I can only write out numbers in english, so I will do that.", + "mention": "Hey {mention}!" + }, + "format": { + "number_format": { + "decimal": "." }, - "format": { - "number_format": { - "decimal": "." - }, - "capitalize_calc": false, - "termial": "termial", - "factorial": "factorial", - "uple": "uple-{factorial}", - "sub": "sub{factorial}", - "negative": "negative {factorial}", - "num_overrides": { - "2": "double-{factorial}", - "3": "triple-{factorial}" - }, - "force_num": false, - "nest": "{factorial} of {next}", - "exact": "{factorial} of {number} is {result}", - "rough": "{factorial} of {number} is roughly {result}", - "approx": "{factorial} of {number} is approximately {result}", - "digits": "{factorial} of {number} has approximately {result} digits", - "order": "{factorial} of {number} has on the order of {result} digits", - "all_that": "All that of {number} has on the order of {result} digits", - "rough_number": "roughly {number}" - } + "capitalize_calc": false, + "termial": "termial", + "factorial": "factorial", + "uple": "uple-{factorial}", + "sub": "sub{factorial}", + "negative": "negative {factorial}", + "num_overrides": { + "2": "double-{factorial}", + "3": "triple-{factorial}" + }, + "force_num": false, + "nest": "{factorial} of {next}", + "exact": "{factorial} of {number} is {result}", + "rough": "{factorial} of {number} is roughly {result}", + "approx": "{factorial} of {number} is approximately {result}", + "digits": "{factorial} of {number} has approximately {result} digits", + "order": "{factorial} of {number} has on the order of {result} digits", + "all_that": "All that of {number} has on the order of {result} digits", + "rough_number": "roughly {number}" } } diff --git a/factorion-lib/src/en_fuck.json b/factorion-lib/src/en_fuck.json index 857824dd..a8f08b3c 100644 --- a/factorion-lib/src/en_fuck.json +++ b/factorion-lib/src/en_fuck.json @@ -1,46 +1,45 @@ -{ "V2": - { - "bot_disclaimer": "This action was performed by a fucking bot | [Source code](http://f.r0.fyi)", - "notes": { - "tower": "That is so fucking large, that I can't even give the number of digits of it, so I have to make a power of ten tower.", - "tower_mult": "Some of these are so fucking large, that I can't even give the number of digits of them, so I have to make a power of ten tower.", - "digits": "That number is so fucking large, that I can't even approximate it well, so I can only give you an approximation on the number of digits.", - "digits_mult": "Some of these are so fucking large, that I can't even approximate them well, so I can only give you an approximation on the number of digits.", - "approx": "That is so fucking large, that I can't calculate it, so I'll have to approximate.", - "approx_mult": "Some of those are so fucking large, that I can't calculate them, so I'll have to approximate.", - "round": "I can't calculate such a fucking large factorial of decimals. So I had to round at some point.", - "round_mult": "I can't calculate that large factorials of decimals. So I had to round at some point.", - "too_big": "If I post the whole number, the comment would get too fucking long. So I had to turn it into scientific notation.", - "too_big_mult": "If I post the whole numbers, the comment would get too fucking long. So I had to turn them into scientific notation.", - "remove": "If I posted all numbers, the comment would get too fucking long. So I had to remove some of them.", - "tetration": "That is so fucking large, I can't even fit it in a comment with a power of 10 tower, so I'll have to use tetration!", - "no_post": "Sorry, but the reply text for all those numbers would be _really_ fucking long, so I'd rather not even try posting lmao", - "limit_hit": "I have repeated myself enough, I won't do that fucking calculation again.", - "mention": "Hey {mention}!" +{ + "bot_disclaimer": "This action was performed by a fucking bot | [Source code](http://f.r0.fyi)", + "notes": { + "tower": "That is so fucking large, that I can't even give the number of digits of it, so I have to make a power of ten tower.", + "tower_mult": "Some of these are so fucking large, that I can't even give the number of digits of them, so I have to make a power of ten tower.", + "digits": "That number is so fucking large, that I can't even approximate it well, so I can only give you an approximation on the number of digits.", + "digits_mult": "Some of these are so fucking large, that I can't even approximate them well, so I can only give you an approximation on the number of digits.", + "approx": "That is so fucking large, that I can't calculate it, so I'll have to approximate.", + "approx_mult": "Some of those are so fucking large, that I can't calculate them, so I'll have to approximate.", + "round": "I can't calculate such a fucking large factorial of decimals. So I had to round at some point.", + "round_mult": "I can't calculate that large factorials of decimals. So I had to round at some point.", + "too_big": "If I post the whole number, the comment would get too fucking long. So I had to turn it into scientific notation.", + "too_big_mult": "If I post the whole numbers, the comment would get too fucking long. So I had to turn them into scientific notation.", + "remove": "If I posted all numbers, the comment would get too fucking long. So I had to remove some of them.", + "tetration": "That is so fucking large, I can't even fit it in a comment with a power of 10 tower, so I'll have to use tetration!", + "no_post": "Sorry, but the reply text for all those numbers would be _really_ fucking long, so I'd rather not even try posting lmao", + "limit_hit": "I have repeated myself enough, I won't do that fucking calculation again.", + "write_out_unsupported": "I can only write out numbers in english, so I will do that.", + "mention": "Hey {mention}!" + }, + "format": { + "number_format": { + "decimal": "." }, - "format": { - "number_format": { - "decimal": "." - }, - "capitalize_calc": false, - "termial": "termial", - "factorial": "fucktorial", - "uple": "uple-{factorial}", - "sub": "sub{factorial}", - "negative": "negative {factorial}", - "num_overrides": { - "2": "double-{factorial}", - "3": "triple-{factorial}" - }, - "force_num": false, - "nest": "{factorial} of {next}", - "exact": "{factorial} of {number} is {result}", - "rough": "{factorial} of {number} is roughly {result}", - "approx": "{factorial} of {number} is approximately {result}", - "digits": "{factorial} of {number} has approximately {result} digits", - "order": "{factorial} of {number} has on the order of {result} digits", - "all_that": "All that of {number} has on the order of {result} digits", - "rough_number": "roughly {number}" - } + "capitalize_calc": false, + "termial": "termial", + "factorial": "fucktorial", + "uple": "uple-{factorial}", + "sub": "sub{factorial}", + "negative": "negative {factorial}", + "num_overrides": { + "2": "double-{factorial}", + "3": "triple-{factorial}" + }, + "force_num": false, + "nest": "{factorial} of {next}", + "exact": "{factorial} of {number} is {result}", + "rough": "{factorial} of {number} is roughly {result}", + "approx": "{factorial} of {number} is approximately {result}", + "digits": "{factorial} of {number} has approximately {result} digits", + "order": "{factorial} of {number} has on the order of {result} digits", + "all_that": "All that of {number} has on the order of {result} digits", + "rough_number": "roughly {number}" } } diff --git a/factorion-lib/src/it.json b/factorion-lib/src/it.json index c1c73275..588fab71 100644 --- a/factorion-lib/src/it.json +++ b/factorion-lib/src/it.json @@ -1,46 +1,44 @@ -{ "V2": - { - "bot_disclaimer": "Questa azione è stata fatta da un bot | [Source code](http://f.r0.fyi)", - "notes": { - "tower": "Quel numero è così grande che non posso neanche scrivere il numero di cifre, quindi devo fare una torre di potenze di dieci.", - "tower_mult": "Alcuni di questi numeri sono così grandi che non posso neanche scrivere il numero di cifre, quindi devo fare una torre di potenze di dieci.", - "digits": "Quel numero è così grande che non posso neanche approssimarlo bene, quindi posso solo dare un'approssimazione del numero di cifre.", - "digits_mult": "Alcuni di quei numeri sono così grandi che non posso neanche approssimarlo bene, quindi posso solo dare un'approssimazione del numero di cifre", - "approx": "Quel numero è così grande, che non posso neanche calcolarlo, quindi dovrò approssimare.", - "approx_mult": "Alcuni di quei numeri sono così grandi, che non posso neanche calcolarli, quindi dovrò approssimare.", - "round": "Non posso calcolare un fattoriale con così tante cifre decimali. Quindi ho dovuto arrotondare a un certo punto.", - "round_mult": "Non posso calcolare dei fattoriali con così tante cifre decimali. Quindi ho dovuto arrotondare a un certo punto.", - "too_big": "Se scrivessi il numero per intero, il commento sarebbe troppo lungo. Quindi ho dovuto trasformarlo in una notazione scientifica.", - "too_big_mult": "Se scrivessi questi numeri per intero, il commento sarebbe troppo lungo. Quindi ho dovuto trasformarli in una notazioni scientifiche.", - "remove": "Se scrivessi tutti i numeri, il commento sarebbe troppo lungo. Quindi ne ho dovuto togliere alcuni.", - "tetration": "Quel numero è così grande che non posso neanche scriverlo come torre di potenze di 10, quindi dovrò usare la tetrazione!", - "no_post": "Scusa ma la risposta a tutti quei numeri sarebbe _troppo_ lunga, quindi preferisco neanche provare a scriverla lmao", - "limit_hit": "Mi sono ripetuto abbastanza, non farò più quel calcolo.", - "mention": "Ciao {mention}!" +{ + "bot_disclaimer": "Questa azione è stata fatta da un bot | [Source code](http://f.r0.fyi)", + "notes": { + "tower": "Quel numero è così grande che non posso neanche scrivere il numero di cifre, quindi devo fare una torre di potenze di dieci.", + "tower_mult": "Alcuni di questi numeri sono così grandi che non posso neanche scrivere il numero di cifre, quindi devo fare una torre di potenze di dieci.", + "digits": "Quel numero è così grande che non posso neanche approssimarlo bene, quindi posso solo dare un'approssimazione del numero di cifre.", + "digits_mult": "Alcuni di quei numeri sono così grandi che non posso neanche approssimarlo bene, quindi posso solo dare un'approssimazione del numero di cifre", + "approx": "Quel numero è così grande, che non posso neanche calcolarlo, quindi dovrò approssimare.", + "approx_mult": "Alcuni di quei numeri sono così grandi, che non posso neanche calcolarli, quindi dovrò approssimare.", + "round": "Non posso calcolare un fattoriale con così tante cifre decimali. Quindi ho dovuto arrotondare a un certo punto.", + "round_mult": "Non posso calcolare dei fattoriali con così tante cifre decimali. Quindi ho dovuto arrotondare a un certo punto.", + "too_big": "Se scrivessi il numero per intero, il commento sarebbe troppo lungo. Quindi ho dovuto trasformarlo in una notazione scientifica.", + "too_big_mult": "Se scrivessi questi numeri per intero, il commento sarebbe troppo lungo. Quindi ho dovuto trasformarli in una notazioni scientifiche.", + "remove": "Se scrivessi tutti i numeri, il commento sarebbe troppo lungo. Quindi ne ho dovuto togliere alcuni.", + "tetration": "Quel numero è così grande che non posso neanche scriverlo come torre di potenze di 10, quindi dovrò usare la tetrazione!", + "no_post": "Scusa ma la risposta a tutti quei numeri sarebbe _troppo_ lunga, quindi preferisco neanche provare a scriverla lmao", + "limit_hit": "Mi sono ripetuto abbastanza, non farò più quel calcolo.", + "mention": "Ciao {mention}!" + }, + "format": { + "number_format": { + "decimal": "," }, - "format": { - "number_format": { - "decimal": "," - }, - "capitalize_calc": false, - "termial": "termiale", - "factorial": "fattoriale", - "uple": "multi{factorial}", - "sub": "sotto{factorial}", - "negative": "{factorial} negativo", - "num_overrides": { - "2": "doppio-{factorial}", - "3": "triplo-{factorial}" - }, - "force_num": false, - "nest": "Il {factorial} di {next}", - "exact": "Il {factorial} di {number} è {result}", - "rough": "Il {factorial} di {number} è circa {result}", - "approx": "Il {factorial} di {number} è approssimativamente {result}", - "digits": "Il {factorial} di {number} ha circa {result} cifre", - "order": "Il {factorial} di {number} ha cifre sull'ordine di {result}", - "all_that": "Tutto questo applicato a {number} ha cifre sull'ordine di {result}", - "rough_number": "circa {number}" - } + "capitalize_calc": false, + "termial": "termiale", + "factorial": "fattoriale", + "uple": "multi{factorial}", + "sub": "sotto{factorial}", + "negative": "{factorial} negativo", + "num_overrides": { + "2": "doppio-{factorial}", + "3": "triplo-{factorial}" + }, + "force_num": false, + "nest": "Il {factorial} di {next}", + "exact": "Il {factorial} di {number} è {result}", + "rough": "Il {factorial} di {number} è circa {result}", + "approx": "Il {factorial} di {number} è approssimativamente {result}", + "digits": "Il {factorial} di {number} ha circa {result} cifre", + "order": "Il {factorial} di {number} ha cifre sull'ordine di {result}", + "all_that": "Tutto questo applicato a {number} ha cifre sull'ordine di {result}", + "rough_number": "circa {number}" } -} \ No newline at end of file +} diff --git a/factorion-lib/src/locale.rs b/factorion-lib/src/locale.rs index 30a245ad..42b6ced2 100644 --- a/factorion-lib/src/locale.rs +++ b/factorion-lib/src/locale.rs @@ -36,318 +36,58 @@ pub fn get_all() -> impl Iterator)> { .into_iter() } -/// This can be used to retroactively add fields, that exist in all versions. -macro_rules! get_field { - ($t:ty; $($var:ident),*; $field:ident: $ret:ty) => { - impl<'a> $t { - pub fn $field(&'a self) -> &'a $ret { - match self { - $(Self::$var(this) => &this.$field),* - } - } - } - }; -} -macro_rules! set_field { - ($t:ty; $($var:ident),*; $field:ident: $ret:ty) => { - concat_idents::concat_idents!(set_fn = set_, $field { - impl<'a> $t { - pub fn set_fn(&mut self, v: $ret) { - match self { - $(Self::$var(this) => this.$field = v),* - } - } - } - }); - }; -} -/// This can be used to retroactively add fields, that may not exist in older versions. (currently unused) -macro_rules! maybe_get_field { - ($t:ty; $($var_not:ident),*; $($var_do:ident),*; $field:ident: $ret:ty) => { - impl<'a> $t { - pub fn $field(&'a self) -> Option<&'a $ret> { - match self { - $(Self::$var_do(this) => Some(&this.$field),)* - $(Self::$var_not(_) => None,)* - } - } - } - }; -} -macro_rules! maybe_set_field { - ($t:ty; $($var_not:ident),*; $($var_do:ident),*; $field:ident: $ret:ty) => { - concat_idents::concat_idents!(set_fn = set_, $field { - impl<'a> $t { - pub fn set_fn(&mut self, v: $ret) -> bool { - match self { - $(Self::$var_do(this) => {this.$field = v; true})* - $(Self::$var_not(_) => false),* - } - } - } - }); - }; -} - -/// Versioned total locale -/// -/// Use the getter methods to (maybe) access the fields or setters to (maybe) override them #[derive(Debug, Clone)] #[cfg_attr(any(feature = "serde", test), derive(Serialize, Deserialize))] -#[non_exhaustive] -pub enum Locale<'a> { - V1(v1::Locale<'a>), - V2(v2::Locale<'a>), -} -get_field!(Locale<'a>; V1, V2; bot_disclaimer: Cow<'a, str> ); -set_field!(Locale<'a>; V1, V2; bot_disclaimer: Cow<'a, str> ); -impl<'a> Locale<'a> { - pub fn notes(&'a self) -> Notes<'a> { - match self { - Self::V1(this) => Notes::V1(&this.notes), - Self::V2(this) => Notes::V2(&this.notes), - } - } - pub fn notes_mut(&'a mut self) -> NotesMut<'a> { - match self { - Self::V1(this) => NotesMut::V1(&mut this.notes), - Self::V2(this) => NotesMut::V2(&mut this.notes), - } - } - pub fn format(&'a self) -> Format<'a> { - match self { - Self::V1(this) => Format::V1(&this.format), - Self::V2(this) => Format::V1(&this.format), - } - } - pub fn format_mut(&'a mut self) -> FormatMut<'a> { - match self { - Self::V1(this) => FormatMut::V1(&mut this.format), - Self::V2(this) => FormatMut::V1(&mut this.format), - } - } +pub struct Locale<'a> { + pub bot_disclaimer: Cow<'a, str>, + pub notes: Notes<'a>, + pub format: Format<'a>, } -/// Versioned locale just for the notes at the beginning of posts -/// -/// Use the getter methods to (maybe) access fields #[derive(Debug, Clone)] -#[non_exhaustive] -pub enum Notes<'a> { - V1(&'a v1::Notes<'a>), - V2(&'a v2::Notes<'a>), -} -get_field!(Notes<'a>; V1, V2; tower: Cow<'a, str>); -get_field!(Notes<'a>; V1, V2; tower_mult: Cow<'a, str>); -get_field!(Notes<'a>; V1, V2; digits: Cow<'a, str>); -get_field!(Notes<'a>; V1, V2; digits_mult: Cow<'a, str>); -get_field!(Notes<'a>; V1, V2; approx: Cow<'a, str>); -get_field!(Notes<'a>; V1, V2; approx_mult: Cow<'a, str>); -get_field!(Notes<'a>; V1, V2; round: Cow<'a, str>); -get_field!(Notes<'a>; V1, V2; round_mult: Cow<'a, str>); -get_field!(Notes<'a>; V1, V2; too_big: Cow<'a, str>); -get_field!(Notes<'a>; V1, V2; too_big_mult: Cow<'a, str>); -get_field!(Notes<'a>; V1, V2; remove: Cow<'a, str>); -get_field!(Notes<'a>; V1, V2; tetration: Cow<'a, str>); -get_field!(Notes<'a>; V1, V2; no_post: Cow<'a, str>); -get_field!(Notes<'a>; V1, V2; mention: Cow<'a, str>); -maybe_get_field!(Notes<'a>; V1; V2; limit_hit: Cow<'a, str>); -/// Versioned locale for the notes at the beginning of posts -/// -/// Use the setter methods to (possibly) override them -#[derive(Debug)] -#[non_exhaustive] -pub enum NotesMut<'a> { - V1(&'a mut v1::Notes<'a>), - V2(&'a mut v2::Notes<'a>), -} -set_field!(NotesMut<'a>; V1, V2; tower: Cow<'a, str>); -set_field!(NotesMut<'a>; V1, V2; tower_mult: Cow<'a, str>); -set_field!(NotesMut<'a>; V1, V2; digits: Cow<'a, str>); -set_field!(NotesMut<'a>; V1, V2; digits_mult: Cow<'a, str>); -set_field!(NotesMut<'a>; V1, V2; approx: Cow<'a, str>); -set_field!(NotesMut<'a>; V1, V2; approx_mult: Cow<'a, str>); -set_field!(NotesMut<'a>; V1, V2; round: Cow<'a, str>); -set_field!(NotesMut<'a>; V1, V2; round_mult: Cow<'a, str>); -set_field!(NotesMut<'a>; V1, V2; too_big: Cow<'a, str>); -set_field!(NotesMut<'a>; V1, V2; too_big_mult: Cow<'a, str>); -set_field!(NotesMut<'a>; V1, V2; remove: Cow<'a, str>); -set_field!(NotesMut<'a>; V1, V2; tetration: Cow<'a, str>); -set_field!(NotesMut<'a>; V1, V2; no_post: Cow<'a, str>); -set_field!(NotesMut<'a>; V1, V2; mention: Cow<'a, str>); -maybe_set_field!(NotesMut<'a>; V1; V2; limit_hit: Cow<'a, str>); -/// Versioned locale for the formatting of individual calculations -/// -/// Use the getter methods to (maybe) access fields -#[derive(Debug, Clone)] -#[non_exhaustive] -pub enum Format<'a> { - V1(&'a v1::Format<'a>), -} -get_field!(Format<'a>; V1; capitalize_calc: bool); -get_field!(Format<'a>; V1; termial: Cow<'a, str>); -get_field!(Format<'a>; V1; factorial: Cow<'a, str>); -get_field!(Format<'a>; V1; uple: Cow<'a, str>); -get_field!(Format<'a>; V1; sub: Cow<'a, str>); -get_field!(Format<'a>; V1; negative: Cow<'a, str>); -get_field!(Format<'a>; V1; num_overrides: HashMap>); -get_field!(Format<'a>; V1; force_num: bool); -get_field!(Format<'a>; V1; nest: Cow<'a, str>); -get_field!(Format<'a>; V1; rough_number: Cow<'a, str>); -get_field!(Format<'a>; V1; exact: Cow<'a, str>); -get_field!(Format<'a>; V1; rough: Cow<'a, str>); -get_field!(Format<'a>; V1; approx: Cow<'a, str>); -get_field!(Format<'a>; V1; digits: Cow<'a, str>); -get_field!(Format<'a>; V1; order: Cow<'a, str>); -get_field!(Format<'a>; V1; all_that: Cow<'a, str>); -impl<'a> Format<'a> { - pub fn number_format(&'a self) -> NumFormat<'a> { - match self { - Self::V1(this) => NumFormat::V1(&this.number_format), - } - } -} -/// Versioned locale for the formatting of individual calculations -/// -/// Use the setter methods to (possibly) override them -#[derive(Debug)] -#[non_exhaustive] -pub enum FormatMut<'a> { - V1(&'a mut v1::Format<'a>), -} -set_field!(FormatMut<'a>; V1; capitalize_calc: bool); -set_field!(FormatMut<'a>; V1; termial: Cow<'a, str>); -set_field!(FormatMut<'a>; V1; factorial: Cow<'a, str>); -set_field!(FormatMut<'a>; V1; uple: Cow<'a, str>); -set_field!(FormatMut<'a>; V1; sub: Cow<'a, str>); -set_field!(FormatMut<'a>; V1; negative: Cow<'a, str>); -set_field!(FormatMut<'a>; V1; num_overrides: HashMap>); -set_field!(FormatMut<'a>; V1; force_num: bool); -set_field!(FormatMut<'a>; V1; nest: Cow<'a, str>); -set_field!(FormatMut<'a>; V1; rough_number: Cow<'a, str>); -set_field!(FormatMut<'a>; V1; exact: Cow<'a, str>); -set_field!(FormatMut<'a>; V1; rough: Cow<'a, str>); -set_field!(FormatMut<'a>; V1; approx: Cow<'a, str>); -set_field!(FormatMut<'a>; V1; digits: Cow<'a, str>); -set_field!(FormatMut<'a>; V1; order: Cow<'a, str>); -set_field!(FormatMut<'a>; V1; all_that: Cow<'a, str>); -impl<'a> FormatMut<'a> { - pub fn number_format_mut(&'a mut self) -> NumFormatMut<'a> { - match self { - Self::V1(this) => NumFormatMut::V1(&mut this.number_format), - } - } -} -/// Versioned locale for how numbers are formatted -/// -/// Use the getter methods to (maybe) access fields -#[derive(Debug, Clone)] -#[non_exhaustive] -pub enum NumFormat<'a> { - V1(&'a v1::NumFormat), -} -get_field!(NumFormat<'a>; V1; decimal: char); -/// Versioned locale for how numbers are formatted -/// -/// Use the setter methods to (possibly) override them -#[derive(Debug)] -#[non_exhaustive] -pub enum NumFormatMut<'a> { - V1(&'a mut v1::NumFormat), +#[cfg_attr(any(feature = "serde", test), derive(Serialize, Deserialize))] +pub struct Notes<'a> { + pub tower: Cow<'a, str>, + pub tower_mult: Cow<'a, str>, + pub digits: Cow<'a, str>, + pub digits_mult: Cow<'a, str>, + pub approx: Cow<'a, str>, + pub approx_mult: Cow<'a, str>, + pub round: Cow<'a, str>, + pub round_mult: Cow<'a, str>, + pub too_big: Cow<'a, str>, + pub too_big_mult: Cow<'a, str>, + pub remove: Cow<'a, str>, + pub tetration: Cow<'a, str>, + pub no_post: Cow<'a, str>, + pub mention: Cow<'a, str>, + pub limit_hit: Option>, + pub write_out_unsupported: Option>, } -get_field!(NumFormatMut<'a>; V1; decimal: char); - -/// v1 of locales -pub mod v1 { - #[cfg(any(feature = "serde", test))] - use serde::{Deserialize, Serialize}; - use std::{borrow::Cow, collections::HashMap}; - - #[derive(Debug, Clone)] - #[cfg_attr(any(feature = "serde", test), derive(Serialize, Deserialize))] - pub struct Locale<'a> { - pub bot_disclaimer: Cow<'a, str>, - pub notes: Notes<'a>, - pub format: Format<'a>, - } - - #[derive(Debug, Clone)] - #[cfg_attr(any(feature = "serde", test), derive(Serialize, Deserialize))] - pub struct Notes<'a> { - pub tower: Cow<'a, str>, - pub tower_mult: Cow<'a, str>, - pub digits: Cow<'a, str>, - pub digits_mult: Cow<'a, str>, - pub approx: Cow<'a, str>, - pub approx_mult: Cow<'a, str>, - pub round: Cow<'a, str>, - pub round_mult: Cow<'a, str>, - pub too_big: Cow<'a, str>, - pub too_big_mult: Cow<'a, str>, - pub remove: Cow<'a, str>, - pub tetration: Cow<'a, str>, - pub no_post: Cow<'a, str>, - pub mention: Cow<'a, str>, - } - #[derive(Debug, Clone)] - #[cfg_attr(any(feature = "serde", test), derive(Serialize, Deserialize))] - pub struct Format<'a> { - pub capitalize_calc: bool, - pub termial: Cow<'a, str>, - pub factorial: Cow<'a, str>, - pub uple: Cow<'a, str>, - pub sub: Cow<'a, str>, - pub negative: Cow<'a, str>, - pub num_overrides: HashMap>, - pub force_num: bool, - pub nest: Cow<'a, str>, - pub rough_number: Cow<'a, str>, - pub exact: Cow<'a, str>, - pub rough: Cow<'a, str>, - pub approx: Cow<'a, str>, - pub digits: Cow<'a, str>, - pub order: Cow<'a, str>, - pub all_that: Cow<'a, str>, - pub number_format: NumFormat, - } - - #[derive(Debug, Clone)] - #[cfg_attr(any(feature = "serde", test), derive(Serialize, Deserialize))] - pub struct NumFormat { - pub decimal: char, - } +#[derive(Debug, Clone)] +#[cfg_attr(any(feature = "serde", test), derive(Serialize, Deserialize))] +pub struct Format<'a> { + pub capitalize_calc: bool, + pub termial: Cow<'a, str>, + pub factorial: Cow<'a, str>, + pub uple: Cow<'a, str>, + pub sub: Cow<'a, str>, + pub negative: Cow<'a, str>, + pub num_overrides: HashMap>, + pub force_num: bool, + pub nest: Cow<'a, str>, + pub rough_number: Cow<'a, str>, + pub exact: Cow<'a, str>, + pub rough: Cow<'a, str>, + pub approx: Cow<'a, str>, + pub digits: Cow<'a, str>, + pub order: Cow<'a, str>, + pub all_that: Cow<'a, str>, + pub number_format: NumFormat, } -/// v1 of locales -pub mod v2 { - #[cfg(any(feature = "serde", test))] - use serde::{Deserialize, Serialize}; - use std::borrow::Cow; - #[derive(Debug, Clone)] - #[cfg_attr(any(feature = "serde", test), derive(Serialize, Deserialize))] - pub struct Locale<'a> { - pub bot_disclaimer: Cow<'a, str>, - pub notes: Notes<'a>, - pub format: super::v1::Format<'a>, - } - - #[derive(Debug, Clone)] - #[cfg_attr(any(feature = "serde", test), derive(Serialize, Deserialize))] - pub struct Notes<'a> { - pub tower: Cow<'a, str>, - pub tower_mult: Cow<'a, str>, - pub digits: Cow<'a, str>, - pub digits_mult: Cow<'a, str>, - pub approx: Cow<'a, str>, - pub approx_mult: Cow<'a, str>, - pub round: Cow<'a, str>, - pub round_mult: Cow<'a, str>, - pub too_big: Cow<'a, str>, - pub too_big_mult: Cow<'a, str>, - pub remove: Cow<'a, str>, - pub tetration: Cow<'a, str>, - pub no_post: Cow<'a, str>, - pub mention: Cow<'a, str>, - pub limit_hit: Cow<'a, str>, - } +#[derive(Debug, Clone)] +#[cfg_attr(any(feature = "serde", test), derive(Serialize, Deserialize))] +pub struct NumFormat { + pub decimal: char, } diff --git a/factorion-lib/src/parse.rs b/factorion-lib/src/parse.rs index 168ac253..69800b0a 100644 --- a/factorion-lib/src/parse.rs +++ b/factorion-lib/src/parse.rs @@ -1,6 +1,6 @@ //! Parses text and extracts calculations -use crate::locale::{self, NumFormat}; +use crate::locale::NumFormat; use crate::rug::{Complete, Float, Integer, integer::IntegerExt64}; use crate::Consts; @@ -566,7 +566,7 @@ fn parse_num( let orig_text = &text[..]; *text = &text[2..]; let end = text - .find(|c: char| (!c.is_numeric() && !SEPARATORS.contains(&c)) || &c == locale.decimal()) + .find(|c: char| (!c.is_numeric() && !SEPARATORS.contains(&c)) || c == locale.decimal) .unwrap_or(text.len()); let part = &text[..end]; *text = &text[end..]; @@ -684,21 +684,21 @@ fn parse_num_simple( text: &mut &str, had_op: bool, consts: &Consts<'_>, - locale: &NumFormat<'_>, + locale: &NumFormat, prec: u32, ) -> Option { let integer_part = { let end = text - .find(|c: char| (!c.is_numeric() && !SEPARATORS.contains(&c)) || &c == locale.decimal()) + .find(|c: char| (!c.is_numeric() && !SEPARATORS.contains(&c)) || c == locale.decimal) .unwrap_or(text.len()); let part = &text[..end]; *text = &text[end..]; part }; - let decimal_part = if text.starts_with(*locale.decimal()) { + let decimal_part = if text.starts_with(locale.decimal) { *text = &text[1..]; let end = text - .find(|c: char| (!c.is_numeric() && !SEPARATORS.contains(&c)) || &c == locale.decimal()) + .find(|c: char| (!c.is_numeric() && !SEPARATORS.contains(&c)) || c == locale.decimal) .unwrap_or(text.len()); let part = &text[..end]; *text = &text[end..]; @@ -718,7 +718,7 @@ fn parse_num_simple( false }; let end = text - .find(|c: char| (!c.is_numeric() && !SEPARATORS.contains(&c)) || &c == locale.decimal()) + .find(|c: char| (!c.is_numeric() && !SEPARATORS.contains(&c)) || c == locale.decimal) .unwrap_or(text.len()); let part = &text[..end]; *text = &text[end..]; @@ -784,7 +784,7 @@ fn parse_num_simple( let fraction_part = if !had_op && text.starts_with(['/']) { *text = &text[1..]; let end = text - .find(|c: char| (!c.is_numeric() && !SEPARATORS.contains(&c)) || &c == locale.decimal()) + .find(|c: char| (!c.is_numeric() && !SEPARATORS.contains(&c)) || c == locale.decimal) .unwrap_or(text.len()); let part = &text[..end]; *text = &text[end..]; @@ -872,7 +872,7 @@ mod test { "just some words of encouragement!", true, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(jobs, []); } @@ -883,7 +883,7 @@ mod test { "a factorial 15!", true, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!( jobs, @@ -901,7 +901,7 @@ mod test { "a factorial 15!!! actually a multi", true, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!( jobs, @@ -919,7 +919,7 @@ mod test { "a factorial !15 actually a sub", true, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!( jobs, @@ -937,19 +937,14 @@ mod test { "not well defined !!!15", true, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(jobs, []); } #[test] fn test_termial() { let consts = Consts::default(); - let jobs = parse( - "a termial 15?", - true, - &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), - ); + let jobs = parse("a termial 15?", true, &consts, &NumFormat { decimal: '.' }); assert_eq!( jobs, [CalculationJob { @@ -966,7 +961,7 @@ mod test { "not enabled 15?", false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(jobs, []); } @@ -977,7 +972,7 @@ mod test { "a termial 15??? actually a multi", true, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!( jobs, @@ -995,7 +990,7 @@ mod test { "a termial ?15 actually a sub", true, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(jobs, []); } @@ -1006,7 +1001,7 @@ mod test { "a factorialchain (15!)!", true, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!( jobs, @@ -1028,7 +1023,7 @@ mod test { "a factorialchain !(15!)", true, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!( jobs, @@ -1050,7 +1045,7 @@ mod test { "a factorialchain -15!?", true, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!( jobs, @@ -1072,7 +1067,7 @@ mod test { "a factorial ---15!", true, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!( jobs, @@ -1090,7 +1085,7 @@ mod test { "a factorial --- 15!", true, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!( jobs, @@ -1108,7 +1103,7 @@ mod test { "a factorial (15)!", true, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!( jobs, @@ -1126,7 +1121,7 @@ mod test { "a factorial (15!)", true, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!( jobs, @@ -1144,7 +1139,7 @@ mod test { "a factorial 1.5!", true, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!( jobs, @@ -1162,7 +1157,7 @@ mod test { "a factorial (-1.5)!", true, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!( jobs, @@ -1180,7 +1175,7 @@ mod test { "a factorial -(--(-(-(-3))!))!", true, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!( jobs, @@ -1202,7 +1197,7 @@ mod test { ">!5 a factorial 15! !<", true, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(jobs, []); } @@ -1213,7 +1208,7 @@ mod test { ">!5 a factorial 15!", true, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!( jobs, @@ -1238,7 +1233,7 @@ mod test { "\\>!5 a factorial 15! !<", true, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!( jobs, @@ -1263,7 +1258,7 @@ mod test { ">!5 a factorial 15! \\!<", true, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!( jobs, @@ -1289,7 +1284,7 @@ mod test { "https://something.somewhere/with/path/and?tag=siufgiufgia3873844hi8743!hfsf", true, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(jobs, []); } @@ -1297,12 +1292,7 @@ mod test { #[test] fn test_uri_poi_doesnt_cause_infinite_loop() { let consts = Consts::default(); - let jobs = parse( - "84!:", - true, - &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), - ); + let jobs = parse("84!:", true, &consts, &NumFormat { decimal: '.' }); assert_eq!( jobs, [CalculationJob { @@ -1319,7 +1309,7 @@ mod test { "\\://something.somewhere/with/path/and?tag=siufgiufgia3873844hi8743!hfsf", true, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!( jobs, @@ -1338,7 +1328,7 @@ mod test { "(x-2)! (2 word)! ((x/k)-3)! (,x-4)!", true, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(jobs, []); } @@ -1346,12 +1336,7 @@ mod test { #[test] fn test_multi_number_paren() { let consts = Consts::default(); - let jobs = parse( - "(5-2)!", - true, - &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), - ); + let jobs = parse("(5-2)!", true, &consts, &NumFormat { decimal: '.' }); assert_eq!(jobs, []); } #[test] @@ -1359,12 +1344,7 @@ mod test { let consts = Consts::default(); arbtest(|u| { let text: &str = u.arbitrary()?; - let _ = parse( - text, - u.arbitrary()?, - &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), - ); + let _ = parse(text, u.arbitrary()?, &consts, &NumFormat { decimal: '.' }); Ok(()) }); } @@ -1372,18 +1352,13 @@ mod test { #[test] fn test_constant() { let consts = Consts::default(); - let jobs = parse( - "!espi!", - true, - &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), - ); + let jobs = parse("!espi!", true, &consts, &NumFormat { decimal: '.' }); assert_eq!(jobs, []); let jobs = parse( "some. pi!", true, &consts, - &consts.locales.get("en").unwrap().format().number_format(), + &consts.locales.get("en").unwrap().format.number_format, ); assert_eq!( jobs, @@ -1401,12 +1376,7 @@ mod test { #[test] fn test_fraction() { let consts = Consts::default(); - let jobs = parse( - "!5/6!", - true, - &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), - ); + let jobs = parse("!5/6!", true, &consts, &NumFormat { decimal: '.' }); assert_eq!( jobs, [ @@ -1422,12 +1392,7 @@ mod test { } ] ); - let jobs = parse( - "5/6!", - true, - &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), - ); + let jobs = parse("5/6!", true, &consts, &NumFormat { decimal: '.' }); assert_eq!( jobs, [CalculationJob { @@ -1436,12 +1401,7 @@ mod test { negative: 0 }] ); - let jobs = parse( - "(10/2)!", - true, - &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), - ); + let jobs = parse("(10/2)!", true, &consts, &NumFormat { decimal: '.' }); assert_eq!( jobs, [CalculationJob { @@ -1460,7 +1420,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!( num, @@ -1471,7 +1431,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: ',' }), + &NumFormat { decimal: ',' }, ); assert_eq!( num, @@ -1482,14 +1442,18 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, + ); + assert_eq!( + num, + Some(Number::Float(Float::with_val(FLOAT_PRECISION, 0.5).into())) ); let num = parse_num( &mut "1more !", false, true, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, Some(1.into())); let num = parse_num( @@ -1497,7 +1461,7 @@ mod test { false, true, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, Some(1000.into())); let num = parse_num( @@ -1505,7 +1469,7 @@ mod test { false, true, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, Some(1000.into())); let num = parse_num( @@ -1513,7 +1477,7 @@ mod test { false, true, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, Some(1000.into())); let num = parse_num( @@ -1521,7 +1485,7 @@ mod test { false, true, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: ',' }), + &NumFormat { decimal: ',' }, ); assert_eq!(num, Some(1000.into())); let num = parse_num( @@ -1529,7 +1493,7 @@ mod test { false, true, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, Some(1.into())); let num = parse_num( @@ -1537,7 +1501,7 @@ mod test { true, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, Some(1.into())); let num = parse_num( @@ -1545,7 +1509,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, Some(150.into())); let num = parse_num( @@ -1553,7 +1517,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, Some(150.into())); let num = parse_num( @@ -1561,7 +1525,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, Some(100.into())); let num = parse_num( @@ -1569,7 +1533,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, Some(100.into())); let num = parse_num( @@ -1577,7 +1541,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); let Some(Number::Float(f)) = num else { panic!("Not a float") @@ -1588,7 +1552,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!( num, @@ -1599,7 +1563,7 @@ mod test { true, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, None); let num = parse_num( @@ -1607,7 +1571,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, None); let num = parse_num( @@ -1615,7 +1579,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, Some(E(FLOAT_PRECISION))); let num = parse_num( @@ -1623,7 +1587,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, Some(PI(FLOAT_PRECISION))); let num = parse_num( @@ -1631,7 +1595,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, Some(PI(FLOAT_PRECISION))); let num = parse_num( @@ -1639,7 +1603,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, Some(PHI(FLOAT_PRECISION))); let num = parse_num( @@ -1647,7 +1611,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, Some(PHI(FLOAT_PRECISION))); let num = parse_num( @@ -1655,7 +1619,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, Some(TAU(FLOAT_PRECISION))); let num = parse_num( @@ -1663,7 +1627,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, Some(TAU(FLOAT_PRECISION))); let num = parse_num( @@ -1671,7 +1635,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, Some(Number::ComplexInfinity)); let num = parse_num( @@ -1679,7 +1643,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, Some(Number::ComplexInfinity)); let num = parse_num( @@ -1687,7 +1651,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!( num, @@ -1698,7 +1662,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, Some(Number::Exact(5.into()))); let num = parse_num( @@ -1706,7 +1670,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!( num, @@ -1717,7 +1681,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!( num, @@ -1731,7 +1695,7 @@ mod test { false, true, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, Some(Number::Exact(10.into()))); let num = parse_num( @@ -1739,7 +1703,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, Some(Number::Exact(2.into()))); let num = parse_num( @@ -1747,7 +1711,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, None); let num = parse_num( @@ -1755,7 +1719,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, None); let num = parse_num( @@ -1763,7 +1727,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, None); let num = parse_num( @@ -1771,7 +1735,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, None); let num = parse_num( @@ -1779,7 +1743,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!( num, @@ -1795,7 +1759,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!( num, @@ -1811,7 +1775,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, None); let num = parse_num( @@ -1819,7 +1783,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!( num, @@ -1835,7 +1799,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!( num, @@ -1851,7 +1815,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, None); let num = parse_num( @@ -1859,7 +1823,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, Some(Number::ApproximateDigits(false, 5.into()))); let num = parse_num( @@ -1867,7 +1831,7 @@ mod test { false, true, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, Some(Number::Exact(10.into()))); } @@ -1881,7 +1845,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, None); assert_eq!(text, "^(5!)"); @@ -1891,7 +1855,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, None); assert_eq!(text, "^(10 10"); @@ -1901,7 +1865,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, None); assert_eq!(text, "^(10)1"); @@ -1911,7 +1875,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, None); assert_eq!(text, "^(10^10^\\(5\\)"); @@ -1921,7 +1885,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, None); assert_eq!(text, "^10^\\(5\\)!"); @@ -1931,18 +1895,12 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!(num, None); assert_eq!(text, "^30!"); } - #[test] - fn test_parse_num_absorb() { - // Note that we want one extra character when we get None, as in such a situation a char will always be skipped - let consts = Consts::default(); - } - #[allow(clippy::uninlined_format_args)] #[test] fn test_biggest_num() { @@ -1952,7 +1910,7 @@ mod test { true, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert!(matches!(num, Some(Number::Approximate(_, _)))); let num = parse_num( @@ -1960,7 +1918,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert!(num.is_some()); } diff --git a/factorion-lib/src/ru.json b/factorion-lib/src/ru.json index a9c96ded..b628c56e 100644 --- a/factorion-lib/src/ru.json +++ b/factorion-lib/src/ru.json @@ -1,93 +1,91 @@ { - "V2": { - "bot_disclaimer": "Это действие выполнено ботом | [Исходный код](http://f.r0.fyi)", - "notes": { - "tower": "Число настолько велико, что я даже не могу указать количество его цифр. Поэтому использую башню степеней числа 10.", - "tower_mult": "Некоторые из этих чисел настолько велики, что я даже не могу указать количество их цифр. Поэтому использую башню степеней числа 10.", - "digits": "Это число настолько велико, что я не могу надёжно оценить его значение. Могу лишь приблизительно оценить количество цифр.", - "digits_mult": "Некоторые из этих чисел настолько велики, что я не могу надёжно их оценить. Могу лишь приблизительно оценить количество цифр.", - "approx": "Значение настолько велико, что вычислить его напрямую невозможно, поэтому привожу приближение.", - "approx_mult": "Некоторые из этих значений настолько велики, что вычислить их напрямую невозможно, поэтому привожу приближения.", - "round": "Я не могу вычислить факториал столь большого дробного числа. Пришлось выполнить округление на одном из этапов.", - "round_mult": "Я не могу вычислить факториалы столь больших дробных чисел. Пришлось выполнить округление на одном из этапов.", - "too_big": "Если вывести число полностью, комментарий получится слишком длинным. Поэтому использую научную запись.", - "too_big_mult": "Если вывести числа полностью, комментарий получится слишком длинным. Поэтому использую научную запись.", - "remove": "Если вывести все числа, комментарий станет слишком длинным. Поэтому некоторые пришлось опустить.", - "tetration": "Число настолько велико, что даже башня степеней числа 10 не помещается в комментарий. Приходится использовать тетрацию!", - "no_post": "Извини, но ответ для всех этих чисел был бы _слишком_ длинным, так что даже не буду пытаться отправлять лол", - "limit_hit": "Я уже много раз это делал, так что больше пересчитывать не буду.", - "mention": "Эй, {mention}!" + "bot_disclaimer": "Это действие выполнено ботом | [Исходный код](http://f.r0.fyi)", + "notes": { + "tower": "Число настолько велико, что я даже не могу указать количество его цифр. Поэтому использую башню степеней числа 10.", + "tower_mult": "Некоторые из этих чисел настолько велики, что я даже не могу указать количество их цифр. Поэтому использую башню степеней числа 10.", + "digits": "Это число настолько велико, что я не могу надёжно оценить его значение. Могу лишь приблизительно оценить количество цифр.", + "digits_mult": "Некоторые из этих чисел настолько велики, что я не могу надёжно их оценить. Могу лишь приблизительно оценить количество цифр.", + "approx": "Значение настолько велико, что вычислить его напрямую невозможно, поэтому привожу приближение.", + "approx_mult": "Некоторые из этих значений настолько велики, что вычислить их напрямую невозможно, поэтому привожу приближения.", + "round": "Я не могу вычислить факториал столь большого дробного числа. Пришлось выполнить округление на одном из этапов.", + "round_mult": "Я не могу вычислить факториалы столь больших дробных чисел. Пришлось выполнить округление на одном из этапов.", + "too_big": "Если вывести число полностью, комментарий получится слишком длинным. Поэтому использую научную запись.", + "too_big_mult": "Если вывести числа полностью, комментарий получится слишком длинным. Поэтому использую научную запись.", + "remove": "Если вывести все числа, комментарий станет слишком длинным. Поэтому некоторые пришлось опустить.", + "tetration": "Число настолько велико, что даже башня степеней числа 10 не помещается в комментарий. Приходится использовать тетрацию!", + "no_post": "Извини, но ответ для всех этих чисел был бы _слишком_ длинным, так что даже не буду пытаться отправлять лол", + "limit_hit": "Я уже много раз это делал, так что больше пересчитывать не буду.", + "mention": "Эй, {mention}!" + }, + "format": { + "number_format": { + "decimal": "," }, - "format": { - "number_format": { - "decimal": "," - }, - "capitalize_calc": true, - "termial": "термиал", - "factorial": "факториал", - "uple": "{n}-кратный {factorial}", - "sub": "Суб{factorial}", - "negative": "отрицательный-{factorial}", - "num_overrides": { - "2": "Двойной-{factorial}", - "3": "Тройной-{factorial}", - "4": "Четверной-{factorial}", - "5": "Пятикратный-{factorial}", - "6": "Шестикратный-{factorial}", - "7": "Семикратный-{factorial}", - "8": "Восьмикратный-{factorial}", - "9": "Девятикратный-{factorial}", - "10": "Десятикратный-{factorial}", - "11": "Одиннадцатикратный-{factorial}", - "12": "Двенадцатикратный-{factorial}", - "13": "Тринадцатикратный-{factorial}", - "14": "Четырнадцатикратный-{factorial}", - "15": "Пятнадцатикратный-{factorial}", - "16": "Шестнадцатикратный-{factorial}", - "17": "Семнадцатикратный-{factorial}", - "18": "Восемнадцатикратный-{factorial}", - "19": "Девятнадцатикратный-{factorial}", - "20": "Двадцатикратный-{factorial}", - "21": "Двадцать один кратный-{factorial}", - "22": "Двадцать два кратный-{factorial}", - "23": "Двадцать три кратный-{factorial}", - "24": "Двадцать четыре кратный-{factorial}", - "25": "Двадцать пять кратный-{factorial}", - "26": "Двадцать шесть кратный-{factorial}", - "27": "Двадцать семь кратный-{factorial}", - "28": "Двадцать восемь кратный-{factorial}", - "29": "Двадцать девять кратный-{factorial}", - "30": "Тридцатикратный-{factorial}", - "31": "Тридцать один кратный-{factorial}", - "32": "Тридцать два кратный-{factorial}", - "33": "Тридцать три кратный-{factorial}", - "34": "Тридцать четыре кратный-{factorial}", - "35": "Тридцать пять кратный-{factorial}", - "36": "Тридцать шесть кратный-{factorial}", - "37": "Тридцать семь кратный-{factorial}", - "38": "Тридцать восемь кратный-{factorial}", - "39": "Тридцать девять кратный-{factorial}", - "40": "Сорокакратный-{factorial}", - "41": "Сорок один кратный-{factorial}", - "42": "Сорок два кратный-{factorial}", - "43": "Сорок три кратный-{factorial}", - "44": "Сорок четыре кратный-{factorial}", - "45": "Сорок пять кратный-{factorial}", - "46": "Сорок шесть кратный-{factorial}", - "47": "Сорок семь кратный-{factorial}", - "48": "Сорок восемь кратный-{factorial}", - "49": "Сорок девять кратный-{factorial}", - "50": "Пятидесятикратный-{factorial}" - }, - "force_num": true, - "nest": "{factorial} от {next}", - "exact": "{factorial} от {number} равен {result}", - "rough": "{factorial} от {number} примерно {result}", - "approx": "{factorial} от {number} приблизительно {result}", - "digits": "{factorial} от {number} содержит примерно {result} цифр", - "order": "{factorial} от {number} порядка {result} цифр", - "all_that": "Вся эта конструкция от {number} порядка {result} цифр", - "rough_number": "примерно {number}" - } + "capitalize_calc": true, + "termial": "термиал", + "factorial": "факториал", + "uple": "{n}-кратный {factorial}", + "sub": "Суб{factorial}", + "negative": "отрицательный-{factorial}", + "num_overrides": { + "2": "Двойной-{factorial}", + "3": "Тройной-{factorial}", + "4": "Четверной-{factorial}", + "5": "Пятикратный-{factorial}", + "6": "Шестикратный-{factorial}", + "7": "Семикратный-{factorial}", + "8": "Восьмикратный-{factorial}", + "9": "Девятикратный-{factorial}", + "10": "Десятикратный-{factorial}", + "11": "Одиннадцатикратный-{factorial}", + "12": "Двенадцатикратный-{factorial}", + "13": "Тринадцатикратный-{factorial}", + "14": "Четырнадцатикратный-{factorial}", + "15": "Пятнадцатикратный-{factorial}", + "16": "Шестнадцатикратный-{factorial}", + "17": "Семнадцатикратный-{factorial}", + "18": "Восемнадцатикратный-{factorial}", + "19": "Девятнадцатикратный-{factorial}", + "20": "Двадцатикратный-{factorial}", + "21": "Двадцать один кратный-{factorial}", + "22": "Двадцать два кратный-{factorial}", + "23": "Двадцать три кратный-{factorial}", + "24": "Двадцать четыре кратный-{factorial}", + "25": "Двадцать пять кратный-{factorial}", + "26": "Двадцать шесть кратный-{factorial}", + "27": "Двадцать семь кратный-{factorial}", + "28": "Двадцать восемь кратный-{factorial}", + "29": "Двадцать девять кратный-{factorial}", + "30": "Тридцатикратный-{factorial}", + "31": "Тридцать один кратный-{factorial}", + "32": "Тридцать два кратный-{factorial}", + "33": "Тридцать три кратный-{factorial}", + "34": "Тридцать четыре кратный-{factorial}", + "35": "Тридцать пять кратный-{factorial}", + "36": "Тридцать шесть кратный-{factorial}", + "37": "Тридцать семь кратный-{factorial}", + "38": "Тридцать восемь кратный-{factorial}", + "39": "Тридцать девять кратный-{factorial}", + "40": "Сорокакратный-{factorial}", + "41": "Сорок один кратный-{factorial}", + "42": "Сорок два кратный-{factorial}", + "43": "Сорок три кратный-{factorial}", + "44": "Сорок четыре кратный-{factorial}", + "45": "Сорок пять кратный-{factorial}", + "46": "Сорок шесть кратный-{factorial}", + "47": "Сорок семь кратный-{factorial}", + "48": "Сорок восемь кратный-{factorial}", + "49": "Сорок девять кратный-{factorial}", + "50": "Пятидесятикратный-{factorial}" + }, + "force_num": true, + "nest": "{factorial} от {next}", + "exact": "{factorial} от {number} равен {result}", + "rough": "{factorial} от {number} примерно {result}", + "approx": "{factorial} от {number} приблизительно {result}", + "digits": "{factorial} от {number} содержит примерно {result} цифр", + "order": "{factorial} от {number} порядка {result} цифр", + "all_that": "Вся эта конструкция от {number} порядка {result} цифр", + "rough_number": "примерно {number}" } } From 9fc1c639f688ca08b88e80bab9f72f91e9bacf53 Mon Sep 17 00:00:00 2001 From: tolik518 Date: Sun, 8 Mar 2026 23:10:08 +0100 Subject: [PATCH 2/3] fixed test after master pull + cargo clippy --fix --- factorion-bot-discord/src/discord_api.rs | 8 ++++---- factorion-bot-discord/src/main.rs | 2 +- factorion-bot-reddit/src/main.rs | 19 ++++++++----------- factorion-bot-reddit/src/reddit_api.rs | 8 ++++---- factorion-lib/src/calculation_results.rs | 2 -- factorion-lib/src/calculation_tasks.rs | 24 ++++++++++++------------ factorion-lib/src/comment.rs | 4 ++-- factorion-lib/src/format.rs | 7 +++---- factorion-lib/src/parse.rs | 2 +- 9 files changed, 35 insertions(+), 41 deletions(-) diff --git a/factorion-bot-discord/src/discord_api.rs b/factorion-bot-discord/src/discord_api.rs index 35e9b1e2..bc8fc157 100644 --- a/factorion-bot-discord/src/discord_api.rs +++ b/factorion-bot-discord/src/discord_api.rs @@ -146,7 +146,7 @@ impl<'a> Handler<'a> { let extract_end = SystemTime::now(); factorion_lib::influxdb::discord::log_time_consumed( - &self.influx_client, + self.influx_client, extract_start, extract_end, "extract_factorials", @@ -163,7 +163,7 @@ impl<'a> Handler<'a> { let calc_end = SystemTime::now(); factorion_lib::influxdb::discord::log_time_consumed( - &self.influx_client, + self.influx_client, calc_start, calc_end, "calculate_factorials", @@ -208,7 +208,7 @@ impl<'a> Handler<'a> { // Log the reply to InfluxDB factorion_lib::influxdb::discord::log_message_reply( - &self.influx_client, + self.influx_client, &msg.id.to_string(), &msg.author.name, &msg.channel_id.to_string(), @@ -220,7 +220,7 @@ impl<'a> Handler<'a> { let end = SystemTime::now(); factorion_lib::influxdb::discord::log_time_consumed( - &self.influx_client, + self.influx_client, start, end, "process_message", diff --git a/factorion-bot-discord/src/main.rs b/factorion-bot-discord/src/main.rs index e0d92102..3c29685b 100644 --- a/factorion-bot-discord/src/main.rs +++ b/factorion-bot-discord/src/main.rs @@ -124,7 +124,7 @@ async fn main() -> Result<(), Box> { info!("InfluxDB client configured. Metrics will be logged."); } - discord_api::start_bot(token, consts, &*INFLUX_CLIENT).await?; + discord_api::start_bot(token, consts, &INFLUX_CLIENT).await?; Ok(()) } diff --git a/factorion-bot-reddit/src/main.rs b/factorion-bot-reddit/src/main.rs index eb16a0e4..7875013d 100644 --- a/factorion-bot-reddit/src/main.rs +++ b/factorion-bot-reddit/src/main.rs @@ -47,16 +47,13 @@ fn en_str() -> &'static str { } #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[derive(Default)] enum SubredditMode { All, PostOnly, + #[default] None, } -impl Default for SubredditMode { - fn default() -> Self { - Self::None - } -} #[tokio::main] async fn main() -> Result<(), Box> { @@ -135,7 +132,7 @@ async fn main() -> Result<(), Box> { let dont_reply = dont_reply == "true"; let sub_entries = if let Ok(path) = std::env::var("SUBREDDITS_FILE") { - if let Ok(_) = std::env::var("SUBREDDITS") { + if std::env::var("SUBREDDITS").is_ok() { panic!("SUBREDDITS and SUBREDDITS_FILE can not be set simultaneusly!") } let text = std::fs::read_to_string(path).unwrap(); @@ -277,7 +274,7 @@ async fn main() -> Result<(), Box> { continue; } let Ok(mut dense_id) = u64::from_str_radix(&comment.meta.thread, 36) else { - if comment.meta.thread == "" { + if comment.meta.thread.is_empty() { info!("Empty thread id on comment {}", comment.meta.id); } else { warn!("Failed to make id dense {}", comment.meta.thread); @@ -421,10 +418,10 @@ async fn main() -> Result<(), Box> { } factorion_lib::influxdb::reddit::log_comment_reply( influx_client, - &comment_id, - &comment_author, - &comment_subreddit, - &comment_locale, + comment_id, + comment_author, + comment_subreddit, + comment_locale, ) .await?; } diff --git a/factorion-bot-reddit/src/reddit_api.rs b/factorion-bot-reddit/src/reddit_api.rs index bde285e4..332727c2 100644 --- a/factorion-bot-reddit/src/reddit_api.rs +++ b/factorion-bot-reddit/src/reddit_api.rs @@ -268,7 +268,7 @@ impl RedditClient { reset_timer = Self::update_reset_timer(reset_timer, t); - if last_ids.mentions != "" + if !last_ids.mentions.is_empty() && a.len() == *COMMENT_COUNT.get().expect("Comment count uninitialized") as usize { @@ -296,7 +296,7 @@ impl RedditClient { reset_timer = Self::update_reset_timer(reset_timer, t); - if last_ids.comments != "" + if !last_ids.comments.is_empty() && a.len() == *COMMENT_COUNT.get().expect("Comment count uninitialized") as usize { @@ -324,7 +324,7 @@ impl RedditClient { reset_timer = Self::update_reset_timer(reset_timer, t); - if last_ids.posts != "" + if !last_ids.posts.is_empty() && posts.len() == *COMMENT_COUNT.get().expect("Comment count uninitialized") as usize { @@ -859,7 +859,7 @@ impl RedditClient { error!("Failed to construct comment {comment_id}!"); return None; }; - comment.meta.used_commands = !(comment.commands == pre_commands); + comment.meta.used_commands = (comment.commands != pre_commands); if let Some((mention, commands, mention_author)) = mention_map.get(comment_id) { comment.meta.id = mention.clone(); comment.commands = *commands; diff --git a/factorion-lib/src/calculation_results.rs b/factorion-lib/src/calculation_results.rs index 111a69d7..c9d170c3 100644 --- a/factorion-lib/src/calculation_results.rs +++ b/factorion-lib/src/calculation_results.rs @@ -6,8 +6,6 @@ use crate::format::{ use crate::impl_all_bitwise; use crate::impl_bitwise; use factorion_math::length; -use factorion_math::rug::Complete; -use factorion_math::rug::integer::IntegerExt64; #[cfg(any(feature = "serde", test))] use serde::{Deserialize, Serialize}; use std::ops::BitAnd; diff --git a/factorion-lib/src/calculation_tasks.rs b/factorion-lib/src/calculation_tasks.rs index db20c220..953727ce 100644 --- a/factorion-lib/src/calculation_tasks.rs +++ b/factorion-lib/src/calculation_tasks.rs @@ -202,7 +202,7 @@ impl CalculationJob { } -1 => { let res: Float = math::fractional_termial(num.as_float().clone()) - * if negative % 2 != 0 { -1 } else { 1 }; + * if !negative.is_multiple_of(2) { -1 } else { 1 }; if res.is_finite() { return Some(CalculationResult::Float(res.into())); } else { @@ -215,7 +215,7 @@ impl CalculationJob { } 1 => { let res: Float = math::fractional_factorial(num.as_float().clone()) - * if negative % 2 != 0 { -1 } else { 1 }; + * if !negative.is_multiple_of(2) { -1 } else { 1 }; if res.is_finite() { return Some(CalculationResult::Float(res.into())); } else { @@ -225,7 +225,7 @@ impl CalculationJob { 2.. => { let res: Float = math::fractional_multifactorial(num.as_float().clone(), level as u32) - * if negative % 2 != 0 { -1 } else { 1 }; + * if !negative.is_multiple_of(2) { -1 } else { 1 }; if res.is_finite() { return Some(CalculationResult::Float(res.into())); } else { @@ -287,7 +287,7 @@ impl CalculationJob { } else if calc_num > consts.upper_approximation_limit { let factorial = math::approximate_multifactorial_digits(calc_num.clone(), level as u32, prec); - CalculationResult::ApproximateDigits(negative % 2 != 0, factorial) + CalculationResult::ApproximateDigits(!negative.is_multiple_of(2), factorial) // Check if the number is within a reasonable range to compute } else if calc_num > consts.upper_calculation_limit { let factorial = if level == 0 { @@ -296,7 +296,7 @@ impl CalculationJob { math::approximate_multifactorial(calc_num.clone(), level as u32, prec) }; CalculationResult::Approximate( - ((factorial.0 * if negative % 2 != 0 { -1 } else { 1 }) as Float).into(), + ((factorial.0 * if !negative.is_multiple_of(2) { -1 } else { 1 }) as Float).into(), factorial.1, ) } else { @@ -304,7 +304,7 @@ impl CalculationJob { .to_u64() .unwrap_or_else(|| panic!("Failed to convert BigInt to u64: {calc_num}")); let factorial = math::factorial(calc_num, level as u32) - * if negative % 2 != 0 { -1 } else { 1 }; + * if !negative.is_multiple_of(2) { -1 } else { 1 }; CalculationResult::Exact(factorial) }) } else if level == 0 { @@ -312,11 +312,11 @@ impl CalculationJob { CalculationResult::ComplexInfinity } else if calc_num > consts.upper_approximation_limit { let factorial = math::approximate_multifactorial_digits(calc_num.clone(), 1, prec); - CalculationResult::ApproximateDigits(negative % 2 != 0, factorial) + CalculationResult::ApproximateDigits(!negative.is_multiple_of(2), factorial) } else if calc_num > consts.upper_subfactorial_limit { let factorial = math::approximate_subfactorial(calc_num.clone(), prec); CalculationResult::Approximate( - ((factorial.0 * if negative % 2 != 0 { -1 } else { 1 }) as Float).into(), + ((factorial.0 * if !negative.is_multiple_of(2) { -1 } else { 1 }) as Float).into(), factorial.1, ) } else { @@ -324,18 +324,18 @@ impl CalculationJob { .to_u64() .unwrap_or_else(|| panic!("Failed to convert BigInt to u64: {calc_num}")); let factorial = - math::subfactorial(calc_num) * if negative % 2 != 0 { -1 } else { 1 }; + math::subfactorial(calc_num) * if !negative.is_multiple_of(2) { -1 } else { 1 }; CalculationResult::Exact(factorial) }) } else if level < 0 { Some( if calc_num.significant_bits() > consts.upper_termial_approximation_limit { let termial = math::approximate_termial_digits(calc_num, -level as u32, prec); - CalculationResult::ApproximateDigits(negative % 2 != 0, termial) + CalculationResult::ApproximateDigits(!negative.is_multiple_of(2), termial) } else if calc_num > consts.upper_termial_limit { let termial = math::approximate_termial(calc_num, -level as u32, prec); CalculationResult::Approximate( - ((termial.0 * if negative % 2 != 0 { -1 } else { 1 }) as Float).into(), + ((termial.0 * if !negative.is_multiple_of(2) { -1 } else { 1 }) as Float).into(), termial.1, ) } else { @@ -344,7 +344,7 @@ impl CalculationJob { } else { math::termial(calc_num) }; - let termial = termial * if negative % 2 != 0 { -1 } else { 1 }; + let termial = termial * if !negative.is_multiple_of(2) { -1 } else { 1 }; CalculationResult::Exact(termial) }, ) diff --git a/factorion-lib/src/comment.rs b/factorion-lib/src/comment.rs index d485d51a..ac9127eb 100644 --- a/factorion-lib/src/comment.rs +++ b/factorion-lib/src/comment.rs @@ -7,7 +7,7 @@ use crate::rug::integer::IntegerExt64; use crate::rug::{Complete, Integer}; use crate::Consts; -use crate::calculation_results::{Calculation, FormatOptions, Number}; +use crate::calculation_results::{Calculation, FormatOptions}; use crate::calculation_tasks::{CalculationBase, CalculationJob}; use crate::parse::parse; @@ -732,7 +732,7 @@ impl CommentCalculated { } } reply = factorial_list.iter().fold(note, |mut acc, factorial| { - let _ = acc.write_str(&factorial); + let _ = acc.write_str(factorial); acc }); } diff --git a/factorion-lib/src/format.rs b/factorion-lib/src/format.rs index 173444d7..b1634890 100644 --- a/factorion-lib/src/format.rs +++ b/factorion-lib/src/format.rs @@ -354,7 +354,7 @@ pub fn format_float(acc: &mut String, number: &Float, consts: &Consts) -> std::f if exponent > consts.number_decimals_scientific || exponent < -(consts.number_decimals_scientific as isize) { - number = number / Float::with_val(consts.float_precision, &exponent).exp10(); + number /= Float::with_val(consts.float_precision, &exponent).exp10(); } let mut whole_number = number .to_integer_round(factorion_math::rug::float::Round::Down) @@ -366,12 +366,11 @@ pub fn format_float(acc: &mut String, number: &Float, consts: &Consts) -> std::f decimal_part.remove(0); decimal_part.remove(0); decimal_part.truncate(consts.number_decimals_scientific + 1); - if decimal_part.len() > consts.number_decimals_scientific { - if round(&mut decimal_part) { + if decimal_part.len() > consts.number_decimals_scientific + && round(&mut decimal_part) { decimal_part.clear(); whole_number += 1; } - } if let Some(mut digit) = decimal_part.pop() { while digit == '0' { digit = match decimal_part.pop() { diff --git a/factorion-lib/src/parse.rs b/factorion-lib/src/parse.rs index 1f4e6536..aba16d83 100644 --- a/factorion-lib/src/parse.rs +++ b/factorion-lib/src/parse.rs @@ -1827,7 +1827,7 @@ mod test { false, false, &consts, - &NumFormat::V1(&locale::v1::NumFormat { decimal: '.' }), + &NumFormat { decimal: '.' }, ); assert_eq!( num, From 9ec2e8aff039433ea808199b42f1918ac464f30b Mon Sep 17 00:00:00 2001 From: tolik518 Date: Sun, 8 Mar 2026 23:11:10 +0100 Subject: [PATCH 3/3] cargo fmt --- factorion-bot-reddit/src/main.rs | 3 +-- factorion-lib/src/calculation_tasks.rs | 9 ++++++--- factorion-lib/src/format.rs | 9 ++++----- 3 files changed, 11 insertions(+), 10 deletions(-) diff --git a/factorion-bot-reddit/src/main.rs b/factorion-bot-reddit/src/main.rs index 7875013d..1f599884 100644 --- a/factorion-bot-reddit/src/main.rs +++ b/factorion-bot-reddit/src/main.rs @@ -46,8 +46,7 @@ fn en_str() -> &'static str { "en" } -#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] -#[derive(Default)] +#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Default)] enum SubredditMode { All, PostOnly, diff --git a/factorion-lib/src/calculation_tasks.rs b/factorion-lib/src/calculation_tasks.rs index 953727ce..f303f14c 100644 --- a/factorion-lib/src/calculation_tasks.rs +++ b/factorion-lib/src/calculation_tasks.rs @@ -296,7 +296,8 @@ impl CalculationJob { math::approximate_multifactorial(calc_num.clone(), level as u32, prec) }; CalculationResult::Approximate( - ((factorial.0 * if !negative.is_multiple_of(2) { -1 } else { 1 }) as Float).into(), + ((factorial.0 * if !negative.is_multiple_of(2) { -1 } else { 1 }) as Float) + .into(), factorial.1, ) } else { @@ -316,7 +317,8 @@ impl CalculationJob { } else if calc_num > consts.upper_subfactorial_limit { let factorial = math::approximate_subfactorial(calc_num.clone(), prec); CalculationResult::Approximate( - ((factorial.0 * if !negative.is_multiple_of(2) { -1 } else { 1 }) as Float).into(), + ((factorial.0 * if !negative.is_multiple_of(2) { -1 } else { 1 }) as Float) + .into(), factorial.1, ) } else { @@ -335,7 +337,8 @@ impl CalculationJob { } else if calc_num > consts.upper_termial_limit { let termial = math::approximate_termial(calc_num, -level as u32, prec); CalculationResult::Approximate( - ((termial.0 * if !negative.is_multiple_of(2) { -1 } else { 1 }) as Float).into(), + ((termial.0 * if !negative.is_multiple_of(2) { -1 } else { 1 }) as Float) + .into(), termial.1, ) } else { diff --git a/factorion-lib/src/format.rs b/factorion-lib/src/format.rs index b1634890..21c0e969 100644 --- a/factorion-lib/src/format.rs +++ b/factorion-lib/src/format.rs @@ -366,11 +366,10 @@ pub fn format_float(acc: &mut String, number: &Float, consts: &Consts) -> std::f decimal_part.remove(0); decimal_part.remove(0); decimal_part.truncate(consts.number_decimals_scientific + 1); - if decimal_part.len() > consts.number_decimals_scientific - && round(&mut decimal_part) { - decimal_part.clear(); - whole_number += 1; - } + if decimal_part.len() > consts.number_decimals_scientific && round(&mut decimal_part) { + decimal_part.clear(); + whole_number += 1; + } if let Some(mut digit) = decimal_part.pop() { while digit == '0' { digit = match decimal_part.pop() {