From: Scott Worley Date: Wed, 11 Oct 2023 01:16:08 +0000 (-0700) Subject: server: Hand-implement Serialize X-Git-Tag: v0.1.0~4 X-Git-Url: http://git.scottworley.com/tattlekey/commitdiff_plain/6c8d15f4b2c0bacf5cb9fe5ad527ce219b97e0e9?ds=inline server: Hand-implement Serialize Mostly for symmetry with Deserialize, for which the lack of #[serde(flatten)] support hurts much wors. --- diff --git a/server/Cargo.toml b/server/Cargo.toml index 9fbdf1f..01a4b3f 100644 --- a/server/Cargo.toml +++ b/server/Cargo.toml @@ -12,4 +12,4 @@ version = "0.0.1" [dependencies] csv = "1.3.0" -serde = { version = "1.0", features = ["derive"] } +serde = "1.0" diff --git a/server/src/main.rs b/server/src/main.rs index 96f35b2..500c2f5 100644 --- a/server/src/main.rs +++ b/server/src/main.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use serde::Serialize; +use serde::ser::{Serialize, SerializeStruct, Serializer}; use std::collections::HashMap; use std::net::UdpSocket; use std::time::{Duration, SystemTime, UNIX_EPOCH}; @@ -22,7 +22,7 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH}; const MESSAGE_SIZE: usize = 12; const LOGFILENAME: &str = "log.csv"; -#[derive(Eq, Debug, Hash, PartialEq, Serialize)] +#[derive(Eq, Debug, Hash, PartialEq)] struct MessageKey { epoch: u32, device: u16, @@ -34,6 +34,20 @@ struct Message { key: MessageKey, t: u64, } +impl Serialize for Message { + // https://github.com/BurntSushi/rust-csv/issues/155 + // https://github.com/BurntSushi/rust-csv/issues/98 + // https://github.com/BurntSushi/rust-csv/pull/223 + // csv doesn't support #[serde(flatten)], so we implement this directly. :( + fn serialize(&self, serializer: S) -> Result { + let mut row = serializer.serialize_struct("Message", 4)?; + row.serialize_field("epoch", &self.key.epoch)?; + row.serialize_field("device", &self.key.device)?; + row.serialize_field("seq", &self.key.seq)?; + row.serialize_field("t", &self.t)?; + row.end() + } +} impl From<&[u8; MESSAGE_SIZE]> for Message { fn from(value: &[u8; MESSAGE_SIZE]) -> Self { @@ -121,8 +135,7 @@ fn main() { continue; } let message = Message::try_from(filled_buf).expect("I can't count"); - log.serialize((&message.key, message.t)) - .expect("Couldn't write log"); + log.serialize(&message).expect("Couldn't write log"); log.flush().expect("Couldn't flush log"); merge_message(&mut presses, message); }