Skip to content

Commit

Permalink
Clean up json serialization
Browse files Browse the repository at this point in the history
  • Loading branch information
davidlang42 committed Feb 5, 2023
1 parent cd52e13 commit 899e030
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 45 deletions.
7 changes: 4 additions & 3 deletions src/bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use std::fs;
use std::io;

#[derive(Debug)]
pub enum ParseError {
pub enum BytesError {
IncorrectCheckSum {
expected: Vec<u8>,
found: Vec<u8>
Expand All @@ -18,10 +18,11 @@ pub trait Bytes<const N: usize> {
const BYTE_SIZE: usize = N;

fn to_bytes(&self) -> [u8; N];
fn from_bytes(bytes: [u8; N]) -> Result<Self, ParseError> where Self: Sized;
fn from_bytes(bytes: [u8; N]) -> Result<Self, BytesError> where Self: Sized;
fn to_json(&self) -> String;
fn from_json(json: String) -> Self;
fn to_structured_json(&self) -> StructuredJson;
fn from_structured_json(structured_json: StructuredJson) -> Self;
//TODO to_json/from_json
}

pub enum StructuredJson {
Expand Down
37 changes: 10 additions & 27 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,6 @@ mod json;

const VERSION: &str = env!("CARGO_PKG_VERSION");

#[derive(Serialize, Deserialize)]
struct JsonData {
version: String,
last_updated: String,
rd300nx: Box<RD300NX>
}

fn main() {
let mut args = env::args();
let cmd = args.next().unwrap();
Expand Down Expand Up @@ -63,19 +56,14 @@ fn decode(rds_path: Option<String>) {
println!("File should be {} bytes but found {}", RD300NX::BYTE_SIZE, size);
} else {
let rds = RD300NX::from_bytes(bytes.try_into().unwrap()).expect("Error decoding RDS data");
let json = JsonData {
version: VERSION.to_string(),
last_updated: chrono::offset::Local::now().format("%Y-%m-%d %H:%M:%S").to_string(),
rd300nx: Box::new(rds)
};
println!("{}", serde_json::to_string(&json).expect("Error serializing JSON"));
println!("{}", rds.to_json());
}
}

fn encode(json_path: Option<String>) {
let json = load_json(json_path);
let rds = load_json(json_path);
let mut stdout = io::stdout().lock();
stdout.write_all(&json.rd300nx.to_bytes()).expect("Error writing to std out");
stdout.write_all(&rds.to_bytes()).expect("Error writing to std out");
stdout.flush().expect("Error flushing std out");
}

Expand All @@ -92,11 +80,11 @@ fn read_data(path: Option<String>) -> (usize, Vec<u8>) {
(size, bytes)
}

fn load_json(path: Option<String>) -> JsonData {
fn load_json(path: Option<String>) -> Box<RD300NX> {
let (_, bytes) = read_data(path);
let text: String = bytes.into_iter().map(|u| u as char).collect();
let json: JsonData = serde_json::from_str(&text).expect("Error deserializing JSON");
json
let rds = RD300NX::from_json(text);
Box::new(rds)
}

fn split(arg1: String, arg2: Option<String>) {
Expand All @@ -105,19 +93,14 @@ fn split(arg1: String, arg2: Option<String>) {
} else {
(None, arg1)
};
let json = load_json(filename);
let structure = json.rd300nx.to_structured_json();
let rds = load_json(filename);
let structure = rds.to_structured_json();
let count = structure.save(PathBuf::from(&folder)).expect("Error saving structured JSON");
println!("Split JSON into {} files in '{}'", count.files, folder);
}

fn merge(folder: String) {
let structure = StructuredJson::load(PathBuf::from(&folder)).expect("Error loading structured JSON");
let rds = RD300NX::from_structured_json(structure);
let json = JsonData {//TODO duplicated code
version: VERSION.to_string(),
last_updated: chrono::offset::Local::now().format("%Y-%m-%d %H:%M:%S").to_string(),
rd300nx: Box::new(rds)
};
println!("{}", serde_json::to_string(&json).expect("Error serializing JSON"));
}
println!("{}", rds.to_json());
}
52 changes: 37 additions & 15 deletions src/roland.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::fmt::Debug;

use crate::bits::{Bits, BitStream};
use crate::bytes::{Bytes, ParseError, StructuredJson};
use crate::bytes::{Bytes, BytesError, StructuredJson};
use crate::json::serialize_chars_as_string;
use crate::json::serialize_array_as_vec;

Expand All @@ -27,7 +27,7 @@ pub struct LiveSet {
}

impl Bytes<183762> for RD300NX {
fn from_bytes(bytes: [u8; Self::BYTE_SIZE]) -> Result<Self, ParseError> {
fn from_bytes(bytes: [u8; Self::BYTE_SIZE]) -> Result<Self, BytesError> {
let mut data = BitStream::read(bytes);
let user_sets = parse_many(&mut data)?;
let bank_a = parse_many(&mut data)?;
Expand Down Expand Up @@ -55,7 +55,7 @@ impl Bytes<183762> for RD300NX {
let bytes = rds.to_bytes();
let expected_check_sum: [u8; 2] = bytes[(bytes.len()-2)..bytes.len()].try_into().unwrap();
if found_check_sum != expected_check_sum {
return Err(ParseError::IncorrectCheckSum {
return Err(BytesError::IncorrectCheckSum {
expected: expected_check_sum.into_iter().collect(),
found: found_check_sum.into_iter().collect()
});
Expand Down Expand Up @@ -111,6 +111,14 @@ impl Bytes<183762> for RD300NX {
footer
}
}

fn to_json(&self) -> String {
serde_json::to_string(&self).expect("Error serializing JSON")
}

fn from_json(json: String) -> Self {
serde_json::from_str(&json).expect("Error deserializing JSON")
}
}

impl RD300NX {
Expand Down Expand Up @@ -147,7 +155,7 @@ impl LiveSet {
}

impl Bytes<2160> for LiveSet {
fn from_bytes(bytes: [u8; Self::BYTE_SIZE]) -> Result<Self, ParseError> {
fn from_bytes(bytes: [u8; Self::BYTE_SIZE]) -> Result<Self, BytesError> {
let mut data = BitStream::read(bytes);
let mut name = [char::default(); 16];
for i in 0..name.len() {
Expand All @@ -162,7 +170,7 @@ impl Bytes<2160> for LiveSet {
let bytes = live_set.to_bytes();
let expected_check_sum = bytes[bytes.len() - 1];
if found_check_sum != expected_check_sum {
return Err(ParseError::IncorrectCheckSum {
return Err(BytesError::IncorrectCheckSum {
expected: vec![expected_check_sum],
found: vec![found_check_sum]
});
Expand All @@ -179,12 +187,19 @@ impl Bytes<2160> for LiveSet {
}

fn to_structured_json(&self) -> StructuredJson {
StructuredJson::SingleJson(serde_json::to_string(&self).expect("Error serializing JSON"))//TODO duplicated code
StructuredJson::SingleJson(self.to_json())
}

fn from_structured_json(structured_json: StructuredJson) -> Self {
let text = structured_json.to_single_json();
serde_json::from_str(&text).expect("Error deserializing JSON") //TODO duplicated code
Self::from_json(structured_json.to_single_json())
}

fn to_json(&self) -> String {
serde_json::to_string(&self).expect("Error serializing JSON")
}

fn from_json(json: String) -> Self {
serde_json::from_str(&json).expect("Error deserializing JSON")
}
}

Expand All @@ -196,7 +211,7 @@ pub struct Footer {
}

impl Bytes<160> for Footer {
fn from_bytes(bytes: [u8; Self::BYTE_SIZE]) -> Result<Self, ParseError> {
fn from_bytes(bytes: [u8; Self::BYTE_SIZE]) -> Result<Self, BytesError> {
let mut data = BitStream::read(bytes);
let other = data.get_bits();
let mut hardware_version = [char::default(); 16];
Expand All @@ -218,26 +233,33 @@ impl Bytes<160> for Footer {
}

fn to_structured_json(&self) -> StructuredJson {
StructuredJson::SingleJson(serde_json::to_string(&self).expect("Error serializing JSON"))//TODO duplicated code
StructuredJson::SingleJson(self.to_json())
}

fn from_structured_json(structured_json: StructuredJson) -> Self {
let text = structured_json.to_single_json();
serde_json::from_str(&text).expect("Error deserializing JSON") //TODO duplicated code
Self::from_json(structured_json.to_single_json())
}

fn to_json(&self) -> String {
serde_json::to_string(&self).expect("Error serializing JSON")
}

fn from_json(json: String) -> Self {
serde_json::from_str(&json).expect("Error deserializing JSON")
}
}

fn validate(ch: char) -> Result<char, ParseError> {
fn validate(ch: char) -> Result<char, BytesError> {
// Roland keyboards use chars 32 ' ' through 126 '~' inclusive
let ascii = ch as u8;
if ascii < 32 || ascii > 126 {
Err(ParseError::InvalidCharacter(ch))
Err(BytesError::InvalidCharacter(ch))
} else {
Ok(ch)
}
}

fn parse_many<const B: usize, T: Bytes<B> + Debug, const N: usize>(data: &mut BitStream) -> Result<Box<[T; N]>, ParseError> {
fn parse_many<const B: usize, T: Bytes<B> + Debug, const N: usize>(data: &mut BitStream) -> Result<Box<[T; N]>, BytesError> {
let mut parsed = Vec::new();
for _ in 0..N {
parsed.push(T::from_bytes(data.get_bytes())?);
Expand Down

0 comments on commit 899e030

Please sign in to comment.