{"record":{"id":"af6ef6b48306d35d","repo":"TheAlgorithms/Rust","slug":"invaliddata","errorCode":"InvalidData","errorMessage":"Invalid morse code","messagePattern":"Invalid morse code","errorType":"exception","errorClass":"io::Error","httpStatus":null,"severity":"error","filePath":"src/ciphers/morse_code.rs","lineNumber":108,"sourceCode":"\nfn _decode_token(string: &str) -> String {\n    (*_morse_to_alphanumeric_dictionary()\n        .get(string)\n        .unwrap_or(&_UNKNOWN_MORSE_CHARACTER))\n    .to_string()\n}\n\nfn _decode_part(string: &str) -> String {\n    string.split(' ').map(_decode_token).collect::<String>()\n}\n\n/// Convert morse code to ascii.\n///\n/// Given a morse code, return the corresponding message.\n/// If the code is invalid, the undecipherable part of the code is replaced by `_`.\npub fn decode(string: &str) -> Result<String, io::Error> {\n    if !_check_all_parts(string) {\n        return Err(io::Error::new(\n            io::ErrorKind::InvalidData,\n            \"Invalid morse code\",\n        ));\n    }\n\n    let mut partitions: Vec<String> = vec![];\n\n    for part in string.split('/') {\n        partitions.push(_decode_part(part));\n    }\n\n    Ok(partitions.join(\" \"))\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n","sourceCodeStart":90,"sourceCodeEnd":126,"githubUrl":"https://github.com/TheAlgorithms/Rust/blob/2c53ddfa4b43da4df34bc2f990c5e806f455cb90/src/ciphers/morse_code.rs#L90-L126","documentation":"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.","triggerScenarios":"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 '/'.","commonSituations":"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.","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."],"exampleFix":"// before\nlet text = morse_code::decode(&raw_input).unwrap(); // panics when raw_input = \"1... . .-..\\n\"\n\n// after\nlet cleaned: String = raw_input\n    .chars()\n    .filter(|c| matches!(c, '.' | '-' | ' ' | '/'))\n    .collect();\nmatch morse_code::decode(&cleaned) {\n    Ok(text) => println!(\"{text}\"),\n    Err(e) if e.kind() == std::io::ErrorKind::InvalidData => {\n        eprintln!(\"input is not morse code: {e}\")\n    }\n    Err(e) => unreachable!(\"decode only returns InvalidData, got: {e}\"),\n}","handlingStrategy":"try-catch","validationCode":"fn is_valid_morse_input(s: &str) -> bool {\n    s.chars().all(|c| matches!(c, '.' | '-' | ' ' | '/'))\n}\n\nif is_valid_morse_input(&raw) {\n    let text = morse_code::decode(&raw).unwrap(); // safe: alphabet already checked\n}","typeGuard":null,"tryCatchPattern":"match morse_code::decode(input) {\n    Ok(message) => message,\n    Err(e) if e.kind() == std::io::ErrorKind::InvalidData => {\n        // input is not morse at all: sanitize or reject it\n        Default::default()\n    }\n    Err(e) => unreachable!(\"decode only produces InvalidData, got: {e}\"),\n}","preventionTips":["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."],"tags":["rust","morse-code","input-validation","io-error","decode"],"backgroundTag":"invalid-input-format","analyzedSha":"2c53ddfa4b43da4df34bc2f990c5e806f455cb90","analyzedAt":"2026-08-16T21:59:20.899Z","schemaVersion":2},"datasetVersion":"2026-08-16T23:17:17.608Z"}