1use once_cell::sync::Lazy;
19use std::collections::HashMap;
20use thiserror::Error;
21
22#[derive(Error, Debug, Clone, PartialEq)]
24pub enum Gsm7Error {
25 #[error("Character not supported in GSM 7-bit: '{character}' (U+{code:04X})")]
27 UnsupportedCharacter { character: char, code: u32 },
28
29 #[error("Invalid escape sequence: 0x1B followed by 0x{code:02X}")]
31 InvalidEscapeSequence { code: u8 },
32
33 #[error("Invalid GSM 7-bit byte: 0x{byte:02X}")]
35 InvalidByte { byte: u8 },
36
37 #[error("Malformed GSM 7-bit data: {reason}")]
39 MalformedData { reason: String },
40}
41
42pub type Result<T> = std::result::Result<T, Gsm7Error>;
44
45#[derive(Debug, Clone)]
47pub struct Gsm7Config {
48 pub strict: bool,
50 pub replacement_char: char,
52}
53
54impl Default for Gsm7Config {
55 fn default() -> Self {
56 Self {
57 strict: false,
58 replacement_char: '�',
59 }
60 }
61}
62
63impl Gsm7Config {
64 pub fn strict() -> Self {
66 Self {
67 strict: true,
68 replacement_char: '�',
69 }
70 }
71}
72
73#[derive(Debug, Clone)]
75enum Code {
76 Single(u8),
78 Escape(u8),
80}
81
82static GSM_MAPS: Lazy<(HashMap<char, Code>, [Option<char>; 128], HashMap<u8, char>)> =
84 Lazy::new(|| {
85 let gsm_to_char = build_gsm_table();
86 let gsm_ext = build_gsm_ext_table();
87
88 let mut char_to_gsm = HashMap::new();
89 let mut gsm_array = [None; 128];
90
91 for (&code, &ch) in &gsm_to_char {
93 if let Some(character) = ch {
94 char_to_gsm.insert(character, Code::Single(code));
95 gsm_array[code as usize] = Some(character);
96 }
97 }
98
99 for (&code, &ch) in &gsm_ext {
101 char_to_gsm.insert(ch, Code::Escape(code));
102 }
103
104 (char_to_gsm, gsm_array, gsm_ext)
105 });
106
107pub fn encode(content: &str) -> Result<Vec<u8>> {
132 encode_with_config(content, &Gsm7Config::default())
133}
134
135pub fn encode_with_config(content: &str, config: &Gsm7Config) -> Result<Vec<u8>> {
146 let (char_to_gsm, _, _) = &*GSM_MAPS;
147 let mut bytes = Vec::with_capacity(content.len());
148
149 for ch in content.chars() {
150 match char_to_gsm.get(&ch) {
151 Some(Code::Single(b)) => bytes.push(*b),
152 Some(Code::Escape(b)) => {
153 bytes.push(0x1B);
154 bytes.push(*b);
155 }
156 None => {
157 if config.strict {
158 return Err(Gsm7Error::UnsupportedCharacter {
159 character: ch,
160 code: ch as u32,
161 });
162 } else {
163 if let Some(Code::Single(b)) = char_to_gsm.get(&config.replacement_char) {
165 bytes.push(*b);
166 } else {
167 bytes.push(0x20); }
169 }
170 }
171 }
172 }
173
174 Ok(bytes)
175}
176
177pub fn decode(data: &[u8]) -> Result<String> {
209 decode_with_config(data, &Gsm7Config::default())
210}
211
212pub fn decode_with_config(data: &[u8], config: &Gsm7Config) -> Result<String> {
223 let (_, gsm_array, gsm_ext) = &*GSM_MAPS;
224 let mut result = String::with_capacity(data.len());
225
226 let mut i = 0;
227 while i < data.len() {
228 let code = data[i];
229
230 if code == 0x1B {
231 if let Some(&next_code) = data.get(i + 1) {
233 match gsm_ext.get(&next_code) {
234 Some(&ch) => {
235 result.push(ch);
236 i += 2;
237 continue;
238 }
239 None => {
240 if config.strict {
241 return Err(Gsm7Error::InvalidEscapeSequence { code: next_code });
242 } else {
243 result.push(config.replacement_char);
244 i += 2;
245 continue;
246 }
247 }
248 }
249 } else {
250 if config.strict {
251 return Err(Gsm7Error::MalformedData {
252 reason: "Escape byte at end of input".to_string(),
253 });
254 } else {
255 result.push(config.replacement_char);
256 i += 1;
257 continue;
258 }
259 }
260 } else if code < 128 {
261 match gsm_array[code as usize] {
263 Some(ch) => result.push(ch),
264 None => {
265 if config.strict {
266 return Err(Gsm7Error::InvalidByte { byte: code });
267 } else {
268 result.push(config.replacement_char);
269 }
270 }
271 }
272 } else {
273 result.push(config.replacement_char);
275 }
276 i += 1;
277 }
278
279 Ok(result)
280}
281
282pub fn encoded_len(content: &str) -> Result<usize> {
295 let (char_to_gsm, _, _) = &*GSM_MAPS;
296 let mut len = 0;
297
298 for ch in content.chars() {
299 match char_to_gsm.get(&ch) {
300 Some(Code::Single(_)) => len += 1,
301 Some(Code::Escape(_)) => len += 2,
302 None => {
303 return Err(Gsm7Error::UnsupportedCharacter {
304 character: ch,
305 code: ch as u32,
306 });
307 }
308 }
309 }
310
311 Ok(len)
312}
313
314pub fn is_gsm7_compatible(content: &str) -> bool {
324 encoded_len(content).is_ok()
325}
326
327fn build_gsm_table() -> HashMap<u8, Option<char>> {
329 let mut map = HashMap::new();
330
331 let table: &[(u8, Option<char>)] = &[
332 (0x00, Some('@')),
333 (0x01, Some('£')),
334 (0x02, Some('$')),
335 (0x03, Some('¥')),
336 (0x04, Some('è')),
337 (0x05, Some('é')),
338 (0x06, Some('ù')),
339 (0x07, Some('ì')),
340 (0x08, Some('ò')),
341 (0x09, Some('Ç')),
342 (0x0A, Some('\n')),
343 (0x0B, Some('Ø')),
344 (0x0C, Some('ø')),
345 (0x0D, Some('\r')),
346 (0x0E, Some('Å')),
347 (0x0F, Some('å')),
348 (0x10, Some('Δ')),
349 (0x11, Some('_')),
350 (0x12, Some('Φ')),
351 (0x13, Some('Γ')),
352 (0x14, Some('Λ')),
353 (0x15, Some('Ω')),
354 (0x16, Some('Π')),
355 (0x17, Some('Ψ')),
356 (0x18, Some('Σ')),
357 (0x19, Some('Θ')),
358 (0x1A, Some('Ξ')),
359 (0x1B, None), (0x1C, Some('Æ')),
361 (0x1D, Some('æ')),
362 (0x1E, Some('ß')),
363 (0x1F, Some('É')),
364 (0x20, Some(' ')),
365 (0x21, Some('!')),
366 (0x22, Some('"')),
367 (0x23, Some('#')),
368 (0x24, Some('¤')),
369 (0x25, Some('%')),
370 (0x26, Some('&')),
371 (0x27, Some('\'')),
372 (0x28, Some('(')),
373 (0x29, Some(')')),
374 (0x2A, Some('*')),
375 (0x2B, Some('+')),
376 (0x2C, Some(',')),
377 (0x2D, Some('-')),
378 (0x2E, Some('.')),
379 (0x2F, Some('/')),
380 (0x30, Some('0')),
381 (0x31, Some('1')),
382 (0x32, Some('2')),
383 (0x33, Some('3')),
384 (0x34, Some('4')),
385 (0x35, Some('5')),
386 (0x36, Some('6')),
387 (0x37, Some('7')),
388 (0x38, Some('8')),
389 (0x39, Some('9')),
390 (0x3A, Some(':')),
391 (0x3B, Some(';')),
392 (0x3C, Some('<')),
393 (0x3D, Some('=')),
394 (0x3E, Some('>')),
395 (0x3F, Some('?')),
396 (0x40, Some('¡')),
397 (0x41, Some('A')),
398 (0x42, Some('B')),
399 (0x43, Some('C')),
400 (0x44, Some('D')),
401 (0x45, Some('E')),
402 (0x46, Some('F')),
403 (0x47, Some('G')),
404 (0x48, Some('H')),
405 (0x49, Some('I')),
406 (0x4A, Some('J')),
407 (0x4B, Some('K')),
408 (0x4C, Some('L')),
409 (0x4D, Some('M')),
410 (0x4E, Some('N')),
411 (0x4F, Some('O')),
412 (0x50, Some('P')),
413 (0x51, Some('Q')),
414 (0x52, Some('R')),
415 (0x53, Some('S')),
416 (0x54, Some('T')),
417 (0x55, Some('U')),
418 (0x56, Some('V')),
419 (0x57, Some('W')),
420 (0x58, Some('X')),
421 (0x59, Some('Y')),
422 (0x5A, Some('Z')),
423 (0x5B, Some('Ä')),
424 (0x5C, Some('Ö')),
425 (0x5D, Some('Ñ')),
426 (0x5E, Some('Ü')),
427 (0x5F, Some('§')),
428 (0x60, Some('¿')),
429 (0x61, Some('a')),
430 (0x62, Some('b')),
431 (0x63, Some('c')),
432 (0x64, Some('d')),
433 (0x65, Some('e')),
434 (0x66, Some('f')),
435 (0x67, Some('g')),
436 (0x68, Some('h')),
437 (0x69, Some('i')),
438 (0x6A, Some('j')),
439 (0x6B, Some('k')),
440 (0x6C, Some('l')),
441 (0x6D, Some('m')),
442 (0x6E, Some('n')),
443 (0x6F, Some('o')),
444 (0x70, Some('p')),
445 (0x71, Some('q')),
446 (0x72, Some('r')),
447 (0x73, Some('s')),
448 (0x74, Some('t')),
449 (0x75, Some('u')),
450 (0x76, Some('v')),
451 (0x77, Some('w')),
452 (0x78, Some('x')),
453 (0x79, Some('y')),
454 (0x7A, Some('z')),
455 (0x7B, Some('ä')),
456 (0x7C, Some('ö')),
457 (0x7D, Some('ñ')),
458 (0x7E, Some('ü')),
459 (0x7F, Some('à')),
460 ];
461
462 for &(code, ch) in table {
463 map.insert(code, ch);
464 }
465
466 map
467}
468
469fn build_gsm_ext_table() -> HashMap<u8, char> {
471 let mut map = HashMap::new();
472
473 let table: &[(u8, char)] = &[
474 (0x0A, '\x0C'), (0x14, '^'),
476 (0x28, '{'),
477 (0x29, '}'),
478 (0x2F, '\\'),
479 (0x3C, '['),
480 (0x3D, '~'),
481 (0x3E, ']'),
482 (0x40, '|'),
483 (0x65, '€'),
484 ];
485
486 for &(code, ch) in table {
487 map.insert(code, ch);
488 }
489
490 map
491}
492
493#[cfg(test)]
494mod tests {
495 use super::*;
496
497 #[test]
498 fn test_encode_decode_roundtrip() {
499 let test_cases = [
500 "Hello World!",
501 "Hello {world} €!",
502 "GSM 7-bit test: àáâãäåæçèéêë",
503 "Greek letters: ΔΦΓΛΩΠΨΣΘΞ",
504 "Special chars: @£$¥èé",
505 "Extension chars: {[]}\\~€|^",
506 "Numbers: 0123456789",
507 "Punctuation: !\"#¤%&'()*+,-./:;<=>?¡¿§",
508 ];
509
510 for text in &test_cases {
511 let encoded = encode(text).unwrap();
512 let decoded = decode(&encoded).unwrap();
513 assert_eq!(decoded, *text, "Failed roundtrip for: {}", text);
514 }
515 }
516
517 #[test]
518 fn test_unsupported_character() {
519 let encoded = encode("Hello 🦀 World").unwrap();
521 let decoded = decode(&encoded).unwrap();
522 assert_eq!(decoded, "Hello � World");
523 }
524
525 #[test]
526 fn test_empty_string() {
527 let encoded = encode("").unwrap();
528 assert!(encoded.is_empty());
529 let decoded = decode(&encoded).unwrap();
530 assert!(decoded.is_empty());
531 }
532
533 #[test]
534 fn test_encoded_len() {
535 assert_eq!(encoded_len("Hello").unwrap(), 5);
536 assert_eq!(encoded_len("Hello €").unwrap(), 7); assert_eq!(encoded_len("{[]}").unwrap(), 8); }
539
540 #[test]
541 fn test_is_gsm7_compatible() {
542 assert!(is_gsm7_compatible("Hello World!"));
543 assert!(is_gsm7_compatible("Hello {world} €!"));
544 assert!(!is_gsm7_compatible("Hello 🦀 World"));
545 }
546
547 #[test]
548 fn test_non_strict_mode() {
549 let config = Gsm7Config {
550 strict: false,
551 replacement_char: '?',
552 };
553
554 let encoded = encode_with_config("Hello 🦀 World", &config).unwrap();
555 let decoded = decode(&encoded).unwrap();
556 assert_eq!(decoded, "Hello ? World");
557 }
558
559 #[test]
560 fn test_invalid_byte_replaced() {
561 let invalid_data = vec![0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x81, 0x20, 0x57]; let decoded = decode(&invalid_data).unwrap();
564 assert_eq!(decoded, "Hello� W");
565 }
566
567 #[test]
568 fn test_multiple_invalid_bytes() {
569 let invalid_data = vec![0x48, 0x81, 0x65, 0x82, 0x6C, 0x83]; let decoded = decode(&invalid_data).unwrap();
572 assert_eq!(decoded, "H�e�l�");
573 }
574
575 #[test]
576 fn test_invalid_escape_sequence() {
577 let invalid_data = [0x1B, 0xFF];
579 let decoded = decode(&invalid_data).unwrap();
580 assert_eq!(decoded, "�");
581 }
582
583 #[test]
584 fn test_malformed_data() {
585 let invalid_data = [0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x1B];
587 let decoded = decode(&invalid_data).unwrap();
588 assert_eq!(decoded, "Hello�");
589 }
590
591 #[test]
592 fn test_all_basic_characters() {
593 for i in 0x20..=0x7F {
595 if let Some(ch) = build_gsm_table().get(&i).and_then(|&opt_ch| opt_ch) {
596 let text = ch.to_string();
597 let encoded = encode(&text).unwrap();
598 let decoded = decode(&encoded).unwrap();
599 assert_eq!(decoded, text, "Failed for character: {} (0x{:02X})", ch, i);
600 }
601 }
602 }
603
604 #[test]
605 fn test_all_extension_characters() {
606 let ext_table = build_gsm_ext_table();
607 for &ch in ext_table.values() {
608 let text = ch.to_string();
609 let encoded = encode(&text).unwrap();
610 let decoded = decode(&encoded).unwrap();
611 assert_eq!(decoded, text, "Failed for extension character: {}", ch);
612 }
613 }
614}