Skip to content

Commit

Permalink
feat: Add utility methods to CallResponse (#579)
Browse files Browse the repository at this point in the history
  • Loading branch information
adamspofford-dfinity authored Aug 6, 2024
1 parent 6c445e8 commit 60a64dd
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 2 deletions.
46 changes: 45 additions & 1 deletion ic-transport-types/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Out> {
/// The call completed, and the response is available.
Response(Out),
Expand All @@ -147,6 +147,50 @@ pub enum CallResponse<Out> {
Poll(RequestId),
}

impl<Out> CallResponse<Out> {
/// Maps the inner value, if this is `Response`.
#[inline]
pub fn map<Out2>(self, f: impl FnOnce(Out) -> Out2) -> CallResponse<Out2> {
match self {
Self::Poll(p) => CallResponse::Poll(p),
Self::Response(r) => CallResponse::Response(f(r)),
}
}
}

impl<T, E> CallResponse<Result<T, E>> {
/// Extracts an inner `Result`, if this is `Response`.
#[inline]
pub fn transpose(self) -> Result<CallResponse<T>, E> {
match self {
Self::Poll(p) => Ok(CallResponse::Poll(p)),
Self::Response(r) => r.map(CallResponse::Response),
}
}
}

impl<T> CallResponse<Option<T>> {
/// Extracts an inner `Option`, if this is `Response`.
#[inline]
pub fn transpose(self) -> Option<CallResponse<T>> {
match self {
Self::Poll(p) => Some(CallResponse::Poll(p)),
Self::Response(r) => r.map(CallResponse::Response),
}
}
}

impl<T> CallResponse<(T,)> {
/// Extracts the inner value of a 1-tuple, if this is `Response`.`
#[inline]
pub fn detuple(self) -> CallResponse<T> {
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")]
Expand Down
2 changes: 1 addition & 1 deletion ic-transport-types/src/request_id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit 60a64dd

Please sign in to comment.