From c7f3c21fd04d8f407b36633afa05bc46736ffb41 Mon Sep 17 00:00:00 2001 From: Joe Ardent Date: Wed, 17 Sep 2025 12:55:23 -0700 Subject: [PATCH] Add function for parsing topology messages. --- src/lib.rs | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 4fcd203..aa3c747 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,5 @@ use std::{ - collections::HashMap, + collections::{BTreeMap, HashMap}, io::{BufRead, Write}, sync::{ Arc, Mutex, OnceLock, @@ -20,6 +20,7 @@ pub type NodeyNodeFace = Arc>; pub type OnInit = Box; pub type RpcFuture = Receiver; pub type RpcResult = std::result::Result, ErrorCode>; +pub type Topology = BTreeMap>; pub trait Node { fn handle(&mut self, runner: &Runner, msg: Message); @@ -224,9 +225,43 @@ pub fn check_err(msg: &Message) -> RpcResult { Ok(None) } +/// Convenience function for turning a list of `(&str, serde::Value)` pairs into +/// a Payload. pub fn mk_payload(payload: &[(&str, Value)]) -> Payload { payload .iter() .map(|p| (p.0.to_string(), p.1.clone())) .collect() } + +/// Convenience function for turning a `topology` message into a map of node -> +/// neighbors (String -> Vec). +pub fn parse_toplogy(msg: &Message) -> Option { + if msg.typ() != "topology" { + return None; + } + let topology = msg + .body + .payload + .get("topology") + .unwrap() + .as_object() + .cloned() + .unwrap(); + Some( + topology + .into_iter() + .map(|(node, neighbors)| { + ( + node, + neighbors + .as_array() + .unwrap() + .iter() + .map(|neighbor| neighbor.as_str().unwrap().to_string()) + .collect(), + ) + }) + .collect(), + ) +}