1use serde::Deserialize;
2use std::collections::HashMap;
3
4#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
5#[serde(rename_all = "snake_case")]
6pub enum EncodingMode {
7 BaseConversion,
8 Chunked,
9 ByteRange,
10}
11
12impl Default for EncodingMode {
13 fn default() -> Self {
14 EncodingMode::BaseConversion
15 }
16}
17
18#[derive(Debug, Deserialize, Clone)]
19pub struct AlphabetConfig {
20 #[serde(default)]
21 pub chars: String,
22 #[serde(default)]
23 pub mode: EncodingMode,
24 #[serde(default)]
25 pub padding: Option<String>,
26 #[serde(default)]
27 pub start_codepoint: Option<u32>,
28}
29
30#[derive(Debug, Deserialize)]
31pub struct AlphabetsConfig {
32 pub alphabets: HashMap<String, AlphabetConfig>,
33}
34
35impl AlphabetsConfig {
36 pub fn from_toml(content: &str) -> Result<Self, toml::de::Error> {
37 toml::from_str(content)
38 }
39
40 pub fn load_default() -> Result<Self, Box<dyn std::error::Error>> {
41 let content = include_str!("../alphabets.toml");
42 Ok(Self::from_toml(content)?)
43 }
44
45 pub fn get_alphabet(&self, name: &str) -> Option<&AlphabetConfig> {
46 self.alphabets.get(name)
47 }
48}
49
50#[cfg(test)]
51mod tests {
52 use super::*;
53
54 #[test]
55 fn test_load_default_config() {
56 let config = AlphabetsConfig::load_default().unwrap();
57 assert!(config.alphabets.contains_key("cards"));
58 }
59
60 #[test]
61 fn test_cards_alphabet_length() {
62 let config = AlphabetsConfig::load_default().unwrap();
63 let cards = config.get_alphabet("cards").unwrap();
64 assert_eq!(cards.chars.chars().count(), 52);
65 }
66
67 #[test]
68 fn test_base64_chunked_mode() {
69 let config = AlphabetsConfig::load_default().unwrap();
70 let base64 = config.get_alphabet("base64").unwrap();
71 assert_eq!(base64.mode, EncodingMode::Chunked);
72 assert_eq!(base64.padding, Some("=".to_string()));
73 }
74
75 #[test]
76 fn test_base64_math_mode() {
77 let config = AlphabetsConfig::load_default().unwrap();
78 let base64_math = config.get_alphabet("base64_math").unwrap();
79 assert_eq!(base64_math.mode, EncodingMode::BaseConversion);
80 }
81}
82