DEV Community

Cover image for Building a Terminal-Based Morse Code Translator
Tramposo
Tramposo

Posted on

1

Building a Terminal-Based Morse Code Translator

Project Overview

This Morse code translator is a terminal application that allows real-time translation between text and Morse code. It features a color-coded, interactive interface and supports letters, numbers, and common punctuation marks.

Terminal UI of a Morse code translator supporting letters, numbers and punctuation marks

Let's break down some key parts of the code to see these concepts in action.

Code Breakdown

The MorseTranslator Struct

pub struct MorseTranslator {
    to_morse: HashMap<char, String>,
    from_morse: HashMap<String, char>,
}

impl MorseTranslator {
    pub fn new() -> Self {
        let mut to_morse = HashMap::new();
        let mut from_morse = HashMap::new();

        // Populate with hashmaps...

        MorseTranslator { to_morse, from_morse }
    }

    pub fn to_morse(&self, text: &str) -> String {
        text.to_uppercase()
            .chars()
            .map(|c| {
                if c.is_whitespace() {
                    "  ".to_string()
                } else {
                    self.to_morse.get(&c).cloned().unwrap_or_else(|| c.to_string())
                }
            })
            .collect::<Vec<String>>()
            .join(" ")
    }

    // from_morse method...
}
Enter fullscreen mode Exit fullscreen mode

This struct allows:

  • Use of HashMap for efficient lookup
  • Implementation of methods
  • Rust's iterator methods like map and collect

Terminal UI Handling

pub fn run_terminal_ui() -> crossterm::Result<()> {
    let mut text = String::new();
    let mut morse = String::new();
    let translator = MorseTranslator::new();
    let mut active_field = 0; // 0 for text, 1 for morse

    execute!(stdout(), Hide)?;

    loop {
        // Clear screen and set colors...

        match read()? {
            Event::Key(event) => match event.code {
                KeyCode::Esc => break,
                KeyCode::Tab => {
                    active_field = 1 - active_field;
                    // Update translations...
                },
                KeyCode::Char(c) => {
                    // Handle character input...
                },
                _ => {}
            },
            _ => {}
        }
    }

    execute!(stdout(), Show)?;
    Ok(())
}
Enter fullscreen mode Exit fullscreen mode

This function showcases:

  • Error handling with the ? operator
  • Pattern matching with match
  • Mutable state management in a loop

Conclusion and Next Steps

Building this Morse code translator is an engaging way to learn Rust's fundamentals while creating something useful. As you become more comfortable with these concepts, you can extend the project in various ways:

  • Add sound output for Morse code
  • Implement file I/O for saving and loading translations

The full code for this project is available on GitHub. Feel free to fork, experiment, and learn.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs