smartsheet_rs/
utils.rs

1//! Library-specific utilities, mainly for internal use.
2//!
3use crate::types::Result;
4
5use std::io::{BufReader, Read};
6
7use hyper::body::Buf;
8use hyper::{Body, Response};
9use serde::de;
10
11pub fn is_default<T: Default + PartialEq>(t: &T) -> bool {
12    t == &T::default()
13}
14
15#[cfg(feature = "serde-std")]
16pub async fn resp_into_struct<T>(resp: Response<Body>) -> Result<T>
17where
18    T: de::DeserializeOwned,
19{
20    // asynchronously aggregate the chunks of the body
21    let body = hyper::body::aggregate(resp).await?;
22
23    // use a buffered reader
24    let reader = BufReader::new(body.reader());
25
26    // try to parse as json with serde_json
27    Ok(serde_json::from_reader(reader)?)
28}
29
30pub async fn into_struct_from_str<T>(resp: Response<Body>) -> Result<T>
31where
32    T: de::DeserializeOwned,
33{
34    let body_bytes = hyper::body::to_bytes(resp.into_body()).await?;
35
36    Ok(serde_json::from_str(std::str::from_utf8(&body_bytes)?)?)
37}
38
39pub async fn into_struct_from_slice<T>(resp: Response<Body>) -> Result<T>
40where
41    T: de::DeserializeOwned,
42{
43    // asynchronously concatenate the buffer from a body into bytes
44    let bytes = hyper::body::to_bytes(resp).await?;
45
46    // try to parse as json with serde_json
47    Ok(serde_json::from_slice(&bytes)?)
48}
49
50/// Read the body content of a mutable reference to a `Response` object
51/// into a string.
52pub async fn resp_to_string(resp: &mut Response<Body>) -> Result<String> {
53    // asynchronously aggregate the chunks of the body
54    let body = hyper::body::aggregate(resp).await?;
55
56    // use a buffered reader
57    let mut reader = BufReader::new(body.reader());
58
59    // read BufReader contents into a string
60    let mut body_string = String::new();
61    reader.read_to_string(&mut body_string)?;
62
63    Ok(body_string)
64}