use crate::core::{JsonPatchOp, PatchBody};
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Patch<'a, U> {
Merge(&'a U),
Implicit(&'a U),
Operations(&'a [JsonPatchOp]),
Query(&'a [JsonPatchOp]),
}
impl<U> Patch<'_, U> {
#[must_use]
pub fn content_type(&self) -> &'static str {
match self {
Self::Merge(_) => "application/merge-patch+json",
Self::Implicit(_) => "application/json",
Self::Operations(_) => "application/json-patch+json",
Self::Query(_) => "application/json-patch-query+json",
}
}
}
impl<U: PatchBody> Patch<'_, U> {
pub fn to_json(&self) -> Result<Vec<u8>, serde_json::Error> {
match self {
Self::Merge(body) | Self::Implicit(body) => serde_json::to_vec(body),
Self::Operations(ops) | Self::Query(ops) => serde_json::to_vec(ops),
}
}
}
impl<'a, U: PatchBody> From<&'a U> for Patch<'a, U> {
fn from(body: &'a U) -> Self {
Self::Merge(body)
}
}
impl<'a, U: PatchBody> From<&'a [JsonPatchOp]> for Patch<'a, U> {
fn from(ops: &'a [JsonPatchOp]) -> Self {
Self::Operations(ops)
}
}
impl<'a, U: PatchBody> From<&'a Vec<JsonPatchOp>> for Patch<'a, U> {
fn from(ops: &'a Vec<JsonPatchOp>) -> Self {
Self::Operations(ops)
}
}
impl<'a, U: PatchBody, const N: usize> From<&'a [JsonPatchOp; N]> for Patch<'a, U> {
fn from(ops: &'a [JsonPatchOp; N]) -> Self {
Self::Operations(ops)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(serde::Serialize)]
struct Update {
name: &'static str,
}
impl PatchBody for Update {}
#[test]
fn content_types_match_the_v5_spec() {
let update = Update { name: "n" };
let ops = [JsonPatchOp::remove("/x")];
assert_eq!(
Patch::Merge(&update).content_type(),
"application/merge-patch+json"
);
assert_eq!(Patch::Implicit(&update).content_type(), "application/json");
assert_eq!(
Patch::<Update>::Operations(&ops).content_type(),
"application/json-patch+json"
);
assert_eq!(
Patch::<Update>::Query(&ops).content_type(),
"application/json-patch-query+json"
);
}
#[test]
fn a_body_converts_to_a_merge_patch_and_ops_to_an_operation_list() {
let update = Update { name: "n" };
assert!(matches!(Patch::from(&update), Patch::Merge(_)));
let ops = vec![JsonPatchOp::remove("/x")];
assert!(matches!(Patch::<Update>::from(&ops), Patch::Operations(_)));
assert!(matches!(
Patch::<Update>::from(&ops[..]),
Patch::Operations(_)
));
let array = [JsonPatchOp::remove("/x")];
assert!(matches!(
Patch::<Update>::from(&array),
Patch::Operations(_)
));
}
#[test]
fn each_variant_serialises_the_body_it_carries() {
let update = Update { name: "n" };
assert_eq!(Patch::Merge(&update).to_json().unwrap(), br#"{"name":"n"}"#);
let ops = [JsonPatchOp::remove("/description")];
assert_eq!(
Patch::<Update>::Query(&ops).to_json().unwrap(),
br#"[{"op":"remove","path":"/description"}]"#
);
}
#[test]
fn remove_op_omits_value() {
let json = serde_json::to_string(&JsonPatchOp::remove("/description")).unwrap();
assert_eq!(json, r#"{"op":"remove","path":"/description"}"#);
}
}