Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix config file parsing #382

Merged
merged 12 commits into from
Apr 4, 2023
50 changes: 6 additions & 44 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions espflash/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ directories-next = { version = "2.0.0", optional = true }
env_logger = { version = "0.10.0", optional = true }
esp-idf-part = "0.2.0"
flate2 = "1.0.25"
hex = { version = "0.4.3", features = ["serde"], optional = true }
indicatif = { version = "0.17.2", optional = true }
lazy_static = { version = "1.4.0", optional = true }
log = "0.4.17"
Expand All @@ -45,7 +46,6 @@ parse_int = { version = "0.6.0", optional = true }
regex = { version = "1.7.1", optional = true }
rppal = { version = "0.14.1", optional = true }
serde = { version = "1.0.152", features = ["derive"] }
serde-hex = { version = "0.1.0", optional = true }
serialport = "4.2.0"
sha2 = "0.10.6"
slip-codec = "0.3.3"
Expand All @@ -66,11 +66,11 @@ cli = [
"dep:dialoguer",
"dep:directories-next",
"dep:env_logger",
"dep:hex",
"dep:indicatif",
"dep:lazy_static",
"dep:parse_int",
"dep:regex",
"dep:serde-hex",
"dep:update-informer",
]
raspberry = ["dep:rppal"]
96 changes: 93 additions & 3 deletions espflash/src/cli/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ use std::{
use directories_next::ProjectDirs;
use miette::{IntoDiagnostic, Result, WrapErr};
use serde::{Deserialize, Serialize};
use serde_hex::{Compact, SerHex};
use serialport::UsbPortInfo;

/// A configured, known serial connection
Expand All @@ -35,13 +34,38 @@ pub struct Connection {
#[derive(Debug, Deserialize, Serialize, Default, Clone)]
pub struct UsbDevice {
/// USB Vendor ID
#[serde(with = "SerHex::<Compact>")]
#[serde(serialize_with = "parse_u16_hex", deserialize_with = "parse_hex_u16")]
pub vid: u16,
/// USB Product ID
#[serde(with = "SerHex::<Compact>")]
#[serde(serialize_with = "parse_u16_hex", deserialize_with = "parse_hex_u16")]
pub pid: u16,
}

fn parse_hex_u16<'de, D>(deserializer: D) -> Result<u16, D::Error>
where
D: serde::Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
let bytes = hex::decode(if s.len() % 2 == 1 {
format!("0{}", s)
} else {
s
})
.map_err(serde::de::Error::custom)?;
let padding = vec![0; 2_usize.saturating_sub(bytes.len())];
let vec = [&padding[..], &bytes[..]].concat();
let decimal = u16::from_be_bytes(vec.try_into().unwrap());
Ok(decimal)
}

fn parse_u16_hex<S>(decimal: &u16, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let hex_string = format!("{:04x}", decimal);
serializer.serialize_str(&hex_string)
}

impl UsbDevice {
/// Check if the given USB port matches this device
pub fn matches(&self, port: &UsbPortInfo) -> bool {
Expand Down Expand Up @@ -94,3 +118,69 @@ impl Config {
.wrap_err_with(|| format!("Failed to write config to {}", self.save_path.display()))
}
}

#[cfg(test)]
mod tests {
use super::*;
use serde::Deserialize;

#[derive(Debug, Deserialize, Serialize)]
struct TestData {
#[serde(serialize_with = "parse_u16_hex", deserialize_with = "parse_hex_u16")]
value: u16,
}

#[test]
fn test_parse_hex_u16() {
// Test no padding
let result: Result<TestData, _> = toml::from_str(r#"value = "aaaa""#);
assert_eq!(result.unwrap().value, 0xaaaa);

let result: Result<TestData, _> = toml::from_str(r#"value = "1234""#);
assert_eq!(result.unwrap().value, 0x1234);

// Test padding
let result: Result<TestData, _> = toml::from_str(r#"value = "a""#);
assert_eq!(result.unwrap().value, 0x0a);

let result: Result<TestData, _> = toml::from_str(r#"value = "10""#);
assert_eq!(result.unwrap().value, 0x10);

let result: Result<TestData, _> = toml::from_str(r#"value = "100""#);
assert_eq!(result.unwrap().value, 0x0100);

// Test uppercase
let result: Result<TestData, _> = toml::from_str(r#"value = "A1B2""#);
assert_eq!(result.unwrap().value, 0xA1B2);

// Test invalid
let result: Result<TestData, _> = toml::from_str(r#"value = "gg""#);
assert!(result.is_err());

let result: Result<TestData, _> = toml::from_str(r#"value = "10gg""#);
assert!(result.is_err());
}

#[test]
fn test_parse_u16_hex() {
// Valid hexadecimal input with 1 digit
let result: Result<TestData, _> = toml::from_str(r#"value = "1""#);
assert_eq!(result.unwrap().value, 0x1);

// Valid hexadecimal input with 2 digits
let result: Result<TestData, _> = toml::from_str(r#"value = "ff""#);
assert_eq!(result.unwrap().value, 0xff);

// Valid hexadecimal input with 3 digits
let result: Result<TestData, _> = toml::from_str(r#"value = "b1a""#);
assert_eq!(result.unwrap().value, 0xb1a);

// Valid hexadecimal input with 4 digits
let result: Result<TestData, _> = toml::from_str(r#"value = "abc1""#);
assert_eq!(result.unwrap().value, 0xabc1);

// Invalid input (non-hexadecimal character)
let result: Result<TestData, _> = toml::from_str(r#"value = "xyz""#);
assert!(result.is_err());
}
}