From 223762d42641e917aedffecaafaab3e15274e111 Mon Sep 17 00:00:00 2001 From: Ivan Folgueira Bande Date: Wed, 30 Oct 2024 00:53:22 +0100 Subject: [PATCH] Properly decode a Vec --- waku-bindings/src/node/management.rs | 12 ++++++++++++ waku-bindings/src/utils.rs | 13 ++++++++----- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/waku-bindings/src/node/management.rs b/waku-bindings/src/node/management.rs index 56e3ee1..db7872d 100644 --- a/waku-bindings/src/node/management.rs +++ b/waku-bindings/src/node/management.rs @@ -11,6 +11,7 @@ use crate::general::Result; use crate::node::context::WakuNodeContext; use crate::utils::LibwakuResponse; use crate::utils::{get_trampoline, handle_json_response, handle_no_response, handle_response}; +use crate::utils::WakuDecode; /// Instantiates a Waku node /// as per the [specification](https://rfc.vac.dev/spec/36/#extern-char-waku_newchar-jsonconfig) @@ -101,6 +102,17 @@ pub fn waku_version(ctx: &WakuNodeContext) -> Result { handle_response(code, result) } +// Implement WakuDecode for Vec +impl WakuDecode for Vec { + fn decode(input: &str) -> Result { + input + .split(',') + .map(|s| s.trim().parse::().map_err(|err| err.to_string())) + .collect::>>() // Collect results into a Vec + .map_err(|err| format!("could not parse Multiaddr: {}", err)) + } +} + /// Get the multiaddresses the Waku node is listening to /// as per [specification](https://rfc.vac.dev/spec/36/#extern-char-waku_listen_addresses) pub fn waku_listen_addresses(ctx: &WakuNodeContext) -> Result> { diff --git a/waku-bindings/src/utils.rs b/waku-bindings/src/utils.rs index 8e50cba..f7337e7 100644 --- a/waku-bindings/src/utils.rs +++ b/waku-bindings/src/utils.rs @@ -1,6 +1,5 @@ use crate::general::Result; use core::str::FromStr; -use serde::de::DeserializeOwned; use std::convert::TryFrom; use std::{slice, str}; use waku_sys::WakuCallBack; @@ -32,9 +31,13 @@ impl TryFrom<(u32, &str)> for LibwakuResponse { } } -pub fn decode(input: String) -> Result { - serde_json::from_str(input.as_str()) - .map_err(|err| format!("could not deserialize waku response: {}", err)) +// Define the WakuDecode trait +pub trait WakuDecode: Sized { + fn decode(input: &str) -> Result; +} + +pub fn decode(input: String) -> Result { + T::decode(input.as_str()) } unsafe extern "C" fn trampoline( @@ -84,7 +87,7 @@ pub fn handle_no_response(code: i32, result: LibwakuResponse) -> Result<()> { } } -pub fn handle_json_response(code: i32, result: LibwakuResponse) -> Result { +pub fn handle_json_response(code: i32, result: LibwakuResponse) -> Result { match result { LibwakuResponse::Success(v) => decode(v.unwrap_or_default()), LibwakuResponse::Failure(v) => Err(v),