Debian Codegraph @

tests/integration/from_into.rs

raw symbols SCIP
1 use std::num::ParseIntError;
2
3 use crate::prelude::*;
4
5 #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
6 #[serde(into = "String", try_from = "String")]
7 #[schemars(extend("pattern" = r"^[0-9a-f]{16}:[0-9a-f]{16}:[0-9a-f]{4}$"))]
8 pub struct EventSequenceNumber {
9 transaction_id: u64,
10 statement_id: u64,
11 write_id: u16,
12 }
13
14 impl From<EventSequenceNumber> for String {
15 fn from(value: EventSequenceNumber) -> Self {
16 format!(
17 "{:016x}:{:016x}:{:04x}",
18 value.transaction_id, value.statement_id, value.write_id
19 )
20 }
21 }
22
23 impl TryFrom<String> for EventSequenceNumber {
24 type Error = ParseIntError;
25
26 fn try_from(value: String) -> Result<Self, Self::Error> {
27 let mut parts = value.split(':');
28 Ok(Self {
29 transaction_id: parts.next().unwrap_or_default().parse()?,
30 statement_id: parts.next().unwrap_or_default().parse()?,
31 write_id: parts.next().unwrap_or_default().parse()?,
32 })
33 }
34 }
35
36 #[test]
37 fn into_and_try_from() {
38 test!(EventSequenceNumber)
39 .assert_snapshot()
40 .assert_allows_ser_roundtrip_default()
41 .assert_matches_de_roundtrip(arbitrary_values());
42 }
43
44 #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
45 #[serde(from = "i128")]
46 struct ClampingI8(i8);
47
48 impl From<i128> for ClampingI8 {
49 fn from(value: i128) -> Self {
50 Self(if value > i8::MAX as i128 {
51 i8::MAX
52 } else if value < i8::MIN as i128 {
53 i8::MIN
54 } else {
55 value as i8
56 })
57 }
58 }
59
60 #[test]
61 fn from() {
62 test!(ClampingI8)
63 .assert_snapshot()
64 .assert_allows_ser_roundtrip_default()
65 .assert_matches_de_roundtrip(arbitrary_values());
66 }