Skip to content

Instantly share code, notes, and snippets.

@ivan
Created August 14, 2023 06:58
Show Gist options
  • Save ivan/7ba69b621bacea525d6d11d0cebdbba4 to your computer and use it in GitHub Desktop.
Save ivan/7ba69b621bacea525d6d11d0cebdbba4 to your computer and use it in GitHub Desktop.
axum thing.rs
/// Error indicating failure to parse strictly a natural number
#[derive(thiserror::Error, Debug, Clone)]
#[error("could not parse as natural number without leading 0 or +")]
pub struct ParseNaturalNumberError;
/// Parse strictly, forbidding leading '0' or '+'
#[inline]
fn parse_natural_number<T: FromStr>(s: &str) -> Result<T, ParseNaturalNumberError> {
if s.starts_with('0') || s.starts_with('+') {
return Err(ParseNaturalNumberError);
}
s.parse::<T>().map_err(|_| ParseNaturalNumberError)
}
fn serde_parse_natural_number<'de, D, T: FromStr>(de: D) -> Result<T, D::Error>
where
D: Deserializer<'de>,
T: FromStr,
T::Err: fmt::Display,
{
let s = SmolStr::deserialize(de)?;
parse_natural_number(&s).map_err(de::Error::custom)
}
/// Strictly-parsed natural number, forbidding leading '0' or '+'
#[derive(Debug, Deserialize)]
pub(crate) struct NatNum<T: FromStr> (
#[serde(default, deserialize_with = "serde_parse_natural_number")]
pub T
) where T::Err: fmt::Display;
#[debug_handler]
async fn fofs_get(
Path((NatNum(pile_id), NatNum(cell_id), NatNum(file_id))): Path<(NatNum<i32>, NatNum<i32>, NatNum<i64>)>,
State(state): State<SharedFofsState>,
) -> Result<Response, Error> {
...
let body = axum::body::boxed(StreamBody::new(stream));
let response = Response::builder()
.status(StatusCode::OK)
.header("content-length", fofs_file_size)
.header("content-type", "application/octet-stream")
.body(body)
.unwrap();
Ok(response)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment