Skip to content

Commit bceca92

Browse files
authored
Refactor: Replace String with impl AsRef<str> in public APIs and tests (daisy#449)
* Refactor: Replace `String` with `impl AsRef<str>` in public APIs and tests for improved flexibility * IDE autoformat changed imports on accident
1 parent 80ed8c5 commit bceca92

File tree

12 files changed

+207
-204
lines changed

12 files changed

+207
-204
lines changed

docs/callers.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ pub fn get_overview_text() -> Result<String>
6262
6363
/// Get the value of the named preference.
6464
/// None is returned if `name` is not a known preference.
65-
pub fn get_preference(name: String) -> Result<String>
65+
pub fn get_preference(name: impl AsRef<str>) -> Result<String>
6666
6767
/// Set a MathCAT preference. The preference name should be a known preference name.
6868
/// The value should either be a string or a number (depending upon the preference being set)
@@ -92,7 +92,7 @@ pub fn get_preference(name: String) -> Result<String>
9292
/// A value can be overwritten by calling this function again with a different value.
9393
///
9494
/// FIX: Some preferences are both API and user preferences and something such as '!name' should be used for overrides. Not implemented yet.
95-
pub fn set_preference(name: String, value: String) -> Result<()>
95+
pub fn set_preference(name: impl AsRef<str>, value: impl AsRef<str>) -> Result<()>
9696
9797
/// Given a key code along with the modifier keys, the current node is moved accordingly (or value reported in some cases).
9898
/// `key` is the [keycode](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode#constants_for_keycode_value) for the key (in JavaScript, `ev.key_code`)
@@ -132,7 +132,7 @@ pub fn do_navigate_keypress(key: usize, shift_key: bool, control_key: bool, alt_
132132
/// `MoveTo0`, `MoveTo1`, `MoveTo2`, `MoveTo3`, `MoveTo4`, `MoveTo5`, `MoveTo6`, `MoveTo7`, `MoveTo8`, `MoveTo9`
133133
///
134134
/// When done with Navigation, call with `Exit`
135-
pub fn do_navigate_command(command: String) -> Result<String>
135+
pub fn do_navigate_command(command: impl AsRef<str>) -> Result<String>
136136
137137
/// Return the MathML associated with the current (navigation) node.
138138
/// The returned result is the `id` of the node and the offset (0-based) from that node (not yet implemented)

src/braille.rs

Lines changed: 29 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -298,13 +298,13 @@ pub fn get_navigation_node_from_braille_position(mathml: Element, position: usiz
298298
// save the current highlight state, set the state to be the end points so we can find the braille, then restore the state
299299
// FIX: this can fail if there is 8-dot braille
300300
use crate::interface::{get_preference, set_preference};
301-
let saved_highlight_style = get_preference("BrailleNavHighlight".to_string()).unwrap();
302-
set_preference("BrailleNavHighlight".to_string(), "EndPoints".to_string()).unwrap();
301+
let saved_highlight_style = get_preference("BrailleNavHighlight").unwrap();
302+
set_preference("BrailleNavHighlight", "EndPoints").unwrap();
303303

304304
N_PROBES.with(|n| {*n.borrow_mut() = 0});
305305
// dive into the child of the <math> element (should only be one)
306306
let search_state = find_navigation_node(mathml, as_element(mathml.children()[0]), position)?;
307-
set_preference("BrailleNavHighlight".to_string(), saved_highlight_style.to_string()).unwrap();
307+
set_preference("BrailleNavHighlight", saved_highlight_style.as_str()).unwrap();
308308

309309
// we know the attr value exists because it was found internally
310310
// FIX: what should be done if we never did the search?
@@ -2237,13 +2237,13 @@ fn ASCIIMath_cleanup(_pref_manager: Ref<PreferenceManager>, raw_braille: String)
22372237

22382238

22392239
/************** Braille xpath functionality ***************/
2240-
use crate::canonicalize::{name, as_element, as_text};
2241-
use crate::xpath_functions::{is_leaf, IsBracketed, validate_one_node};
2240+
use crate::canonicalize::{as_element, as_text, name};
2241+
use crate::xpath_functions::{is_leaf, validate_one_node, IsBracketed};
2242+
use std::result::Result as StdResult;
22422243
use sxd_document::dom::ParentOfChild;
2243-
use sxd_xpath::{Value, context, nodeset::*};
2244-
use sxd_xpath::function::{Function, Args};
22452244
use sxd_xpath::function::Error as XPathError;
2246-
use std::result::Result as StdResult;
2245+
use sxd_xpath::function::{Args, Function};
2246+
use sxd_xpath::{context, nodeset::*, Value};
22472247

22482248
pub struct NemethNestingChars;
22492249
const NEMETH_FRAC_LEVEL: &str = "data-nemeth-frac-level"; // name of attr where value is cached
@@ -2781,7 +2781,7 @@ impl NeedsToBeGrouped {
27812781
// if the fraction starts with a "-", it is still a numeric fraction that doesn't need parens
27822782
let mut numerator = as_element(children[0]);
27832783
let denominator = as_element(children[children.len()-1]);
2784-
let decimal_separator = crate::interface::get_preference("DecimalSeparators".to_string()).unwrap()
2784+
let decimal_separator = crate::interface::get_preference("DecimalSeparators").unwrap()
27852785
.chars().next().unwrap_or('.');
27862786
if is_integer(denominator, decimal_separator) {
27872787
// check numerator being either an integer "- integer"
@@ -3066,7 +3066,7 @@ mod tests {
30663066
#[allow(unused_imports)]
30673067
use crate::init_logger;
30683068
use crate::interface::*;
3069-
3069+
30703070
#[test]
30713071
fn ueb_highlight_24() -> Result<()> { // issue 24
30723072
let mathml_str = "<math display='block' id='id-0'>
@@ -3080,16 +3080,16 @@ mod tests {
30803080
</math>";
30813081
crate::interface::set_rules_dir(super::super::abs_rules_dir_path()).unwrap();
30823082
set_mathml(mathml_str.to_string()).unwrap();
3083-
set_preference("BrailleCode".to_string(), "UEB".to_string()).unwrap();
3084-
set_preference("BrailleNavHighlight".to_string(), "All".to_string()).unwrap();
3085-
let braille = get_braille("id-2".to_string())?;
3083+
set_preference("BrailleCode", "UEB").unwrap();
3084+
set_preference("BrailleNavHighlight", "All").unwrap();
3085+
let braille = get_braille("id-2")?;
30863086
assert_eq!("⣼⣙⠰⠁⠉", braille);
3087-
set_navigation_node("id-2".to_string(), 0)?;
3087+
set_navigation_node("id-2", 0)?;
30883088
assert_eq!( get_braille_position()?, (0,2));
30893089

3090-
let braille = get_braille("id-4".to_string())?;
3090+
let braille = get_braille("id-4")?;
30913091
assert_eq!("⠼⠙⣰⣁⠉", braille);
3092-
set_navigation_node("id-4".to_string(), 0)?;
3092+
set_navigation_node("id-4", 0)?;
30933093
assert_eq!( get_braille_position()?, (2,4));
30943094
return Ok( () );
30953095
}
@@ -3136,10 +3136,10 @@ mod tests {
31363136
</math>";
31373137
crate::interface::set_rules_dir(super::super::abs_rules_dir_path()).unwrap();
31383138
set_mathml(mathml_str.to_string()).unwrap();
3139-
set_preference("BrailleNavHighlight".to_string(), "Off".to_string()).unwrap();
3140-
3141-
set_preference("BrailleCode".to_string(), "Nemeth".to_string()).unwrap();
3142-
let braille = get_braille("".to_string())?;
3139+
set_preference("BrailleNavHighlight", "Off").unwrap();
3140+
3141+
set_preference("BrailleCode", "Nemeth").unwrap();
3142+
let braille = get_braille("")?;
31433143
let answers= &[2, 3, 3, 3, 3, 4, 7, 8, 9, 9, 10, 13, 12, 14, 12, 15, 17, 19, 21, 10, 4, 23, 25, 4];
31443144
let answers = answers.map(|num| format!("id-{}", num));
31453145
debug!("\n*** Testing Nemeth ***");
@@ -3152,8 +3152,8 @@ mod tests {
31523152
assert_eq!(answers[i], id, "\nNemeth test ith position={}", i);
31533153
}
31543154

3155-
set_preference("BrailleCode".to_string(), "UEB".to_string()).unwrap();
3156-
let braille = get_braille("".to_string())?;
3155+
set_preference("BrailleCode", "UEB").unwrap();
3156+
let braille = get_braille("")?;
31573157
let answers= &[0, 0, 0, 2, 3, 3, 3, 3, 4, 7, 7, 8, 9, 9, 10, 13, 12, 14, 14, 15, 15, 17, 17, 19, 19, 21, 10, 4, 4, 23, 23, 25, 25, 4, 0, 0];
31583158
let answers = answers.map(|num| format!("id-{}", num));
31593159
debug!("\n\n*** Testing UEB ***");
@@ -3165,8 +3165,8 @@ mod tests {
31653165
debug!("Time taken: {}ms", instant.elapsed().as_millis());
31663166
assert_eq!(answers[i], id, "\nUEB test ith position={}", i);
31673167
}
3168-
set_preference("BrailleCode".to_string(), "CMU".to_string()).unwrap();
3169-
let braille = get_braille("".to_string())?;
3168+
set_preference("BrailleCode", "CMU").unwrap();
3169+
let braille = get_braille("")?;
31703170
let answers= &[2, 3, 5, 7, 8, 9, 9, 9, 10, 10, 11, 13, 12, 14, 14, 15, 17, 17, 19, 19, 21, 11, 5, 4, 22, 23, 23, 25, 25, 22,];
31713171
let answers = answers.map(|num| format!("id-{}", num));
31723172
debug!("\n\n*** Testing CMU ***");
@@ -3188,12 +3188,12 @@ mod tests {
31883188
let mathml_str = "<math><msup><mi>x</mi><mi>n</mi></msup></math>";
31893189
crate::interface::set_rules_dir(super::super::abs_rules_dir_path()).unwrap();
31903190
set_mathml(mathml_str.to_string()).unwrap();
3191-
set_preference("BrailleCode".to_string(), "UEB".to_string()).unwrap();
3192-
set_preference("UEB_START_MODE".to_string(), "Grade2".to_string()).unwrap();
3193-
let braille = get_braille("".to_string())?;
3191+
set_preference("BrailleCode", "UEB").unwrap();
3192+
set_preference("UEB_START_MODE", "Grade2").unwrap();
3193+
let braille = get_braille("")?;
31943194
assert_eq!("⠭⠰⠔⠝", braille, "Grade2");
3195-
set_preference("UEB_START_MODE".to_string(), "Grade1".to_string()).unwrap();
3196-
let braille = get_braille("".to_string())?;
3195+
set_preference("UEB_START_MODE", "Grade1").unwrap();
3196+
let braille = get_braille("")?;
31973197
assert_eq!("⠭⠔⠝", braille, "Grade1");
31983198
return Ok( () );
31993199
}

src/infer_intent.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -628,8 +628,8 @@ mod tests {
628628
// this forces initialization
629629
crate::interface::set_rules_dir(super::super::abs_rules_dir_path()).unwrap();
630630
// crate::speech::SpeechRules::initialize_all_rules().unwrap();
631-
set_preference("IntentErrorRecovery".to_string(), intent_error_recovery.to_string()).unwrap();
632-
set_preference("SpeechStyle".to_string(), "SimpleSpeak".to_string()).unwrap(); // avoids possibility of "LiteralSpeak"
631+
set_preference("IntentErrorRecovery", intent_error_recovery).unwrap();
632+
set_preference("SpeechStyle", "SimpleSpeak").unwrap(); // avoids possibility of "LiteralSpeak"
633633
let package1 = &parser::parse(mathml).expect("Failed to parse test input");
634634
let mathml = get_element(package1);
635635
trim_element(mathml, false);

src/interface.rs

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -188,18 +188,19 @@ pub fn get_overview_text() -> Result<String> {
188188

189189
/// Get the value of the named preference.
190190
/// None is returned if `name` is not a known preference.
191-
pub fn get_preference(name: String) -> Result<String> {
191+
pub fn get_preference(name: impl AsRef<str>) -> Result<String> {
192192
enable_logs();
193+
let name = name.as_ref();
193194
use crate::prefs::NO_PREFERENCE;
194195
return crate::speech::SPEECH_RULES.with(|rules| {
195196
let rules = rules.borrow();
196197
let pref_manager = rules.pref_manager.borrow();
197-
let mut value = pref_manager.pref_to_string(&name);
198+
let mut value = pref_manager.pref_to_string(name);
198199
if value == NO_PREFERENCE {
199-
value = pref_manager.pref_to_string(&name);
200+
value = pref_manager.pref_to_string(name);
200201
}
201202
if value == NO_PREFERENCE {
202-
bail!("No preference named '{}'", &name);
203+
bail!("No preference named '{}'", name);
203204
} else {
204205
return Ok(value);
205206
}
@@ -226,10 +227,11 @@ pub fn get_preference(name: String) -> Result<String> {
226227
/// A value can be overwritten by calling this function again with a different value.
227228
///
228229
/// Be careful setting preferences -- these potentially override user settings, so only preferences that really need setting should be set.
229-
pub fn set_preference(name: String, value: String) -> Result<()> {
230+
pub fn set_preference(name: impl AsRef<str>, value: impl AsRef<str>) -> Result<()> {
230231
enable_logs();
232+
let name = name.as_ref();
231233
// "LanguageAuto" allows setting the language dir without actually changing the value of "Language" from Auto
232-
let mut value = value;
234+
let mut value = value.as_ref().to_string();
233235
if name == "Language" || name == "LanguageAuto" {
234236
// check the format
235237
if value != "Auto" {
@@ -274,14 +276,14 @@ pub fn set_preference(name: String, value: String) -> Result<()> {
274276
}
275277
let lower_case_value = value.to_lowercase();
276278
if lower_case_value == "true" || lower_case_value == "false" {
277-
pref_manager.set_api_boolean_pref(&name, value.to_lowercase() == "true");
279+
pref_manager.set_api_boolean_pref(name, value.to_lowercase() == "true");
278280
} else {
279-
match name.as_str() {
281+
match name {
280282
"Pitch" | "Rate" | "Volume" | "CapitalLetters_Pitch" | "MathRate" | "PauseFactor" => {
281-
pref_manager.set_api_float_pref(&name, to_float(&name, &value)?)
283+
pref_manager.set_api_float_pref(name, to_float(name, &value)?)
282284
}
283285
_ => {
284-
pref_manager.set_string_pref(&name, &value)?;
286+
pref_manager.set_string_pref(name, &value)?;
285287
}
286288
}
287289
};
@@ -301,14 +303,14 @@ pub fn set_preference(name: String, value: String) -> Result<()> {
301303
/// Get the braille associated with the MathML that was set by [`set_mathml`].
302304
/// The braille returned depends upon the preference for the `code` preference (default `Nemeth`).
303305
/// If 'nav_node_id' is given, it is highlighted based on the value of `BrailleNavHighlight` (default: `EndPoints`)
304-
pub fn get_braille(nav_node_id: String) -> Result<String> {
306+
pub fn get_braille(nav_node_id: impl AsRef<str>) -> Result<String> {
305307
enable_logs();
306308
// use std::time::{Instant};
307309
// let instant = Instant::now();
308310
return MATHML_INSTANCE.with(|package_instance| {
309311
let package_instance = package_instance.borrow();
310312
let mathml = get_element(&package_instance);
311-
let braille = crate::braille::braille_mathml(mathml, &nav_node_id)?.0;
313+
let braille = crate::braille::braille_mathml(mathml, nav_node_id.as_ref())?.0;
312314
// info!("Time taken: {}ms", instant.elapsed().as_millis());
313315
return Ok(braille);
314316
});
@@ -418,9 +420,9 @@ pub fn do_navigate_keypress(
418420
/// `MoveTo0`, `MoveTo1`, `MoveTo2`, `MoveTo3`, `MoveTo4`, `MoveTo5`, `MoveTo6`, `MoveTo7`, `MoveTo8`, `MoveTo9`
419421
///
420422
/// When done with Navigation, call with `Exit`
421-
pub fn do_navigate_command(command: String) -> Result<String> {
423+
pub fn do_navigate_command(command: impl AsRef<str>) -> Result<String> {
422424
enable_logs();
423-
let command = NAV_COMMANDS.get_key(&command); // gets a &'static version of the command
425+
let command = NAV_COMMANDS.get_key(command.as_ref()); // gets a &'static version of the command
424426
if command.is_none() {
425427
bail!("Unknown command in call to DoNavigateCommand()");
426428
};
@@ -434,12 +436,12 @@ pub fn do_navigate_command(command: String) -> Result<String> {
434436

435437
/// Given an 'id' and an offset (for tokens), set the navigation node to that id.
436438
/// An error is returned if the 'id' doesn't exist
437-
pub fn set_navigation_node(id: String, offset: usize) -> Result<()> {
439+
pub fn set_navigation_node(id: impl AsRef<str>, offset: usize) -> Result<()> {
438440
enable_logs();
439441
return MATHML_INSTANCE.with(|package_instance| {
440442
let package_instance = package_instance.borrow();
441443
let mathml = get_element(&package_instance);
442-
return set_navigation_node_from_id(mathml, id, offset);
444+
return set_navigation_node_from_id(mathml, id.as_ref(), offset);
443445
});
444446
}
445447

src/lib.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -86,9 +86,9 @@ pub fn are_strs_canonically_equal_with_locale(test: &str, target: &str, ignore_a
8686
// this forces initialization
8787
crate::interface::set_rules_dir(abs_rules_dir_path()).unwrap();
8888
crate::speech::SPEECH_RULES.with(|rules| rules.borrow_mut().read_files().unwrap());
89-
set_preference("Language".to_string(), "en".to_string()).unwrap();
90-
set_preference("BlockSeparators".to_string(), block_separators.to_string()).unwrap();
91-
set_preference("DecimalSeparators".to_string(), decimal_separators.to_string()).unwrap();
89+
set_preference("Language", "en").unwrap();
90+
set_preference("BlockSeparators", block_separators).unwrap();
91+
set_preference("DecimalSeparators", decimal_separators).unwrap();
9292

9393
let package1 = &parser::parse(test).expect("Failed to parse test input");
9494
let mathml = get_element(package1);

0 commit comments

Comments
 (0)