TheAlgorithms/Rust · error · io::Error
InvalidData
InvalidData
Error message
Invalid morse code
What it means
Returned by morse_code::decode when the input string contains any character outside the alphabet {'.', '-', ' ', '/'}. _check_all_parts (src/ciphers/morse_code.rs:87) splits the input on '/' and rejects any part containing a character other than dot, dash, or space, so decode fails with io::ErrorKind::InvalidData before any decoding happens. Note the split personality of the API: unknown-but-well-formed tokens (e.g. "........") do NOT error, they decode to '_'; only foreign characters raise this error.
Source
Thrown at src/ciphers/morse_code.rs:108
fn _decode_token(string: &str) -> String {
(*_morse_to_alphanumeric_dictionary()
.get(string)
.unwrap_or(&_UNKNOWN_MORSE_CHARACTER))
.to_string()
}
fn _decode_part(string: &str) -> String {
string.split(' ').map(_decode_token).collect::<String>()
}
/// Convert morse code to ascii.
///
/// Given a morse code, return the corresponding message.
/// If the code is invalid, the undecipherable part of the code is replaced by `_`.
pub fn decode(string: &str) -> Result<String, io::Error> {
if !_check_all_parts(string) {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Invalid morse code",
));
}
let mut partitions: Vec<String> = vec![];
for part in string.split('/') {
partitions.push(_decode_part(part));
}
Ok(partitions.join(" "))
}
#[cfg(test)]
mod tests {
use super::*;
View on GitHub (pinned to 2c53ddfa4b)
Solutions
- Strip or reject characters outside {'.', '-', ' ', '/'} before calling decode — e.g. trim() the input and filter out '\r'/'\n'/'\t'.
- If the input came from encode(), it is always valid: check for accidental mutation between encode and decode (regex replacements, whitespace normalization).
- Match on the returned Result and handle ErrorKind::InvalidData explicitly (report to the user) instead of unwrap()ing it.
- If you need lenient decoding, pre-map offending characters yourself — the library only substitutes '_' for well-formed tokens, never for foreign characters.
Example fix
// before
let text = morse_code::decode(&raw_input).unwrap(); // panics when raw_input = "1... . .-..\n"
// after
let cleaned: String = raw_input
.chars()
.filter(|c| matches!(c, '.' | '-' | ' ' | '/'))
.collect();
match morse_code::decode(&cleaned) {
Ok(text) => println!("{text}"),
Err(e) if e.kind() == std::io::ErrorKind::InvalidData => {
eprintln!("input is not morse code: {e}")
}
Err(e) => unreachable!("decode only returns InvalidData, got: {e}"),
} Defensive patterns
Strategy: try-catch
Validate before calling
fn is_valid_morse_input(s: &str) -> bool {
s.chars().all(|c| matches!(c, '.' | '-' | ' ' | '/'))
}
if is_valid_morse_input(&raw) {
let text = morse_code::decode(&raw).unwrap(); // safe: alphabet already checked
} Try / catch
match morse_code::decode(input) {
Ok(message) => message,
Err(e) if e.kind() == std::io::ErrorKind::InvalidData => {
// input is not morse at all: sanitize or reject it
Default::default()
}
Err(e) => unreachable!("decode only produces InvalidData, got: {e}"),
} Prevention
- Whitelist the alphabet {'.', '-', ' ', '/'} before calling decode.
- Trim trailing newlines and whitespace from file- or CLI-sourced input.
- Remember: unknown-but-well-formed tokens decode to '_' without erroring; only foreign characters raise InvalidData.
- Never unwrap() the Result — match on ErrorKind::InvalidData and report it.
When it happens
Trigger: decode("1... . .-.. .-.. --- / -- --- .-. ... .") (a digit leaked into the morse string — exactly the crate's own negative test); passing text with '\t', '\r', or '\n' separators or trailing newlines; passing prose that was never encoded; morse that uses '_' or '|' as word separators instead of '/'.
Common situations: Round-tripping user-typed morse from a CLI or chat bot without sanitizing; reading morse from files with Windows line endings; assuming decode substitutes '_' for any bad input (it only does so for well-formed unknown tokens, since encode maps unknown chars to "........"); post-processing encode() output (e.g. replacing spaces with tabs) before decoding.
Related errors
AI-assisted analysis of TheAlgorithms/Rust@2c53ddfa4b (2026-08-16).
Data as JSON: /api/errors/af6ef6b48306d35d.
Report an issue: GitHub.