From 60a64dd2d5368180f03a75df80f475d6e2caf21a Mon Sep 17 00:00:00 2001 From: Adam Spofford <93943719+adamspofford-dfinity@users.noreply.github.com> Date: Tue, 6 Aug 2024 11:00:40 -0400 Subject: [PATCH] feat: Add utility methods to CallResponse (#579) --- ic-transport-types/src/lib.rs | 46 +++++++++++++++++++++++++++- ic-transport-types/src/request_id.rs | 2 +- 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/ic-transport-types/src/lib.rs b/ic-transport-types/src/lib.rs index 689ecb3e..d5d3875f 100644 --- a/ic-transport-types/src/lib.rs +++ b/ic-transport-types/src/lib.rs @@ -138,7 +138,7 @@ pub enum TransportCallResponse { } /// The response from a request to the `call` endpoint. -#[derive(Debug, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq, Clone, Hash)] pub enum CallResponse { /// The call completed, and the response is available. Response(Out), @@ -147,6 +147,50 @@ pub enum CallResponse { Poll(RequestId), } +impl CallResponse { + /// Maps the inner value, if this is `Response`. + #[inline] + pub fn map(self, f: impl FnOnce(Out) -> Out2) -> CallResponse { + match self { + Self::Poll(p) => CallResponse::Poll(p), + Self::Response(r) => CallResponse::Response(f(r)), + } + } +} + +impl CallResponse> { + /// Extracts an inner `Result`, if this is `Response`. + #[inline] + pub fn transpose(self) -> Result, E> { + match self { + Self::Poll(p) => Ok(CallResponse::Poll(p)), + Self::Response(r) => r.map(CallResponse::Response), + } + } +} + +impl CallResponse> { + /// Extracts an inner `Option`, if this is `Response`. + #[inline] + pub fn transpose(self) -> Option> { + match self { + Self::Poll(p) => Some(CallResponse::Poll(p)), + Self::Response(r) => r.map(CallResponse::Response), + } + } +} + +impl CallResponse<(T,)> { + /// Extracts the inner value of a 1-tuple, if this is `Response`.` + #[inline] + pub fn detuple(self) -> CallResponse { + match self { + Self::Poll(p) => CallResponse::Poll(p), + Self::Response(r) => CallResponse::Response(r.0), + } + } +} + /// Possible responses to a query call. #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(tag = "status", rename_all = "snake_case")] diff --git a/ic-transport-types/src/request_id.rs b/ic-transport-types/src/request_id.rs index 8a3c5d7a..4e1f54d2 100644 --- a/ic-transport-types/src/request_id.rs +++ b/ic-transport-types/src/request_id.rs @@ -51,7 +51,7 @@ where } /// A Request ID. -#[derive(Clone, Copy, Debug, PartialOrd, Ord, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)] pub struct RequestId(Sha256Hash); impl RequestId {