]> git.scottworley.com Git - tattlekey/commitdiff
server: Hand-implement Serialize
authorScott Worley <scottworley@scottworley.com>
Wed, 11 Oct 2023 01:16:08 +0000 (18:16 -0700)
committerScott Worley <scottworley@scottworley.com>
Wed, 11 Oct 2023 01:50:46 +0000 (18:50 -0700)
Mostly for symmetry with Deserialize, for which the lack of #[serde(flatten)]
support hurts much wors.

server/Cargo.toml
server/src/main.rs

index 9fbdf1fb80b71e4f03f78887a0dacaaa7a172c37..01a4b3fbf374351086efd22491dc8ce4a10f3c16 100644 (file)
@@ -12,4 +12,4 @@ version = "0.0.1"
 
 [dependencies]
 csv = "1.3.0"
-serde = { version = "1.0", features = ["derive"] }
+serde = "1.0"
index 96f35b25e9360f2bcd9d38d7917620880bba2fa0..500c2f55f9fba7296c4eb17d68be5a7d75e86e8b 100644 (file)
@@ -14,7 +14,7 @@
 // You should have received a copy of the GNU General Public License
 // along with this program.  If not, see <https://www.gnu.org/licenses/>.
 
-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<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
+        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);
             }