Skip to content

Commit c7fb59c

Browse files
committed
feat(lambda-http): implement http-body::Body for lambda_http::body
1 parent f33fa05 commit c7fb59c

File tree

2 files changed

+53
-2
lines changed

2 files changed

+53
-2
lines changed

lambda-http/Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,9 @@ maintenance = { status = "actively-developed" }
1818

1919
[dependencies]
2020
base64 = "0.13.0"
21+
bytes = "1"
2122
http = "0.2"
23+
http-body = "0.4"
2224
lambda_runtime = { path = "../lambda-runtime", version = "0.4.1" }
2325
serde = { version = "^1", features = ["derive"] }
2426
serde_json = "^1"

lambda-http/src/body.rs

Lines changed: 51 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,17 @@
11
//! Provides an ALB / API Gateway oriented request and response body entity interface
22
3-
use std::{borrow::Cow, ops::Deref};
4-
53
use base64::display::Base64Display;
4+
use bytes::Bytes;
5+
use crate::Error;
6+
use http_body::{Body as HttpBody, SizeHint};
67
use serde::ser::{Error as SerError, Serialize, Serializer};
8+
use std::{
9+
borrow::Cow,
10+
mem::take,
11+
pin::Pin,
12+
ops::Deref,
13+
task::Poll,
14+
};
715

816
/// Representation of http request and response bodies as supported
917
/// by API Gateway and ALBs.
@@ -175,6 +183,47 @@ impl<'a> Serialize for Body {
175183
}
176184
}
177185

186+
impl HttpBody for Body {
187+
type Data = Bytes;
188+
type Error = Error;
189+
190+
fn poll_data(
191+
self: Pin<&mut Self>,
192+
_cx: &mut std::task::Context<'_>,
193+
) -> Poll<Option<Result<Self::Data, Self::Error>>> {
194+
let body = take(self.get_mut());
195+
Poll::Ready(
196+
match body {
197+
Body::Empty => None,
198+
Body::Text(s) => Some(Ok(s.into())),
199+
Body::Binary(b) => Some(Ok(b.into())),
200+
}
201+
)
202+
}
203+
204+
fn poll_trailers(
205+
self: Pin<&mut Self>,
206+
_cx: &mut std::task::Context<'_>,
207+
) -> Poll<Result<Option<http::HeaderMap>, Self::Error>> {
208+
Poll::Ready(Ok(None))
209+
}
210+
211+
fn is_end_stream(&self) -> bool {
212+
match self {
213+
Body::Empty => true,
214+
_ => false,
215+
}
216+
}
217+
218+
fn size_hint(&self) -> SizeHint {
219+
match self {
220+
Body::Empty => SizeHint::default(),
221+
Body::Text(ref s) => SizeHint::with_exact(s.len() as u64),
222+
Body::Binary(ref b) => SizeHint::with_exact(b.len() as u64),
223+
}
224+
}
225+
}
226+
178227
#[cfg(test)]
179228
mod tests {
180229
use super::*;

0 commit comments

Comments
 (0)