buup/transformers/
binary_encode.rs1use crate::{Transform, TransformError};
2
3#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
5pub struct BinaryEncode;
6
7impl Transform for BinaryEncode {
8 fn name(&self) -> &'static str {
9 "Binary Encode"
10 }
11
12 fn id(&self) -> &'static str {
13 "binaryencode"
14 }
15
16 fn description(&self) -> &'static str {
17 "Encode text into its binary representation (space-separated bytes)."
18 }
19
20 fn category(&self) -> crate::TransformerCategory {
21 crate::TransformerCategory::Encoder
22 }
23
24 fn transform(&self, input: &str) -> Result<String, TransformError> {
25 if input.is_empty() {
26 return Ok(String::new());
27 }
28
29 let binary_chunks: Vec<String> =
30 input.bytes().map(|byte| format!("{:08b}", byte)).collect();
31
32 Ok(binary_chunks.join(" "))
33 }
34
35 fn default_test_input(&self) -> &'static str {
36 "Hello, World!"
37 }
38}
39
40#[cfg(test)]
41mod tests {
42 use super::*;
43
44 #[test]
45 fn test_binary_encode_empty() {
46 let transformer = BinaryEncode;
47 let result = transformer.transform("").unwrap();
48 assert_eq!(result, "");
49 }
50
51 #[test]
52 fn test_binary_encode_simple() {
53 let transformer = BinaryEncode;
54 let result = transformer.transform("Hi").unwrap();
55 assert_eq!(result, "01001000 01101001");
57 }
58
59 #[test]
60 fn test_binary_encode_with_punctuation() {
61 let transformer = BinaryEncode;
62 let result = transformer
63 .transform(transformer.default_test_input())
64 .unwrap();
65 let expected = "01001000 01100101 01101100 01101100 01101111 00101100 00100000 01010111 01101111 01110010 01101100 01100100 00100001";
67 assert_eq!(result, expected);
68 }
69
70 #[test]
71 fn test_binary_encode_unicode() {
72 let transformer = BinaryEncode;
73 let result = transformer.transform("✓").unwrap();
77 assert_eq!(result, "11100010 10011100 10010011");
78 }
79}