Skip to content

Commit 4cd3201

Browse files
authored
feat(lambda-http): implement http-body::Body for lambda_http::body (#406)
1 parent f33fa05 commit 4cd3201

File tree

2 files changed

+45
-2
lines changed

2 files changed

+45
-2
lines changed

Diff for: lambda-http/Cargo.toml

+2
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"

Diff for: lambda-http/src/body.rs

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

810
/// Representation of http request and response bodies as supported
911
/// by API Gateway and ALBs.
@@ -175,6 +177,45 @@ impl<'a> Serialize for Body {
175177
}
176178
}
177179

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

0 commit comments

Comments
 (0)