Line data Source code
1 : #![warn(missing_docs)]
2 :
3 : use camino::Utf8Path;
4 : use serde::{de::Visitor, Deserialize, Serialize};
5 : use std::fmt;
6 : use std::ops::{Add, AddAssign};
7 : use std::str::FromStr;
8 : use std::sync::atomic::{AtomicU64, Ordering};
9 :
10 : use crate::seqwait::MonotonicCounter;
11 :
12 : /// Transaction log block size in bytes
13 : pub const XLOG_BLCKSZ: u32 = 8192;
14 :
15 : /// A Postgres LSN (Log Sequence Number), also known as an XLogRecPtr
16 866202291 : #[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd, Hash)]
17 : pub struct Lsn(pub u64);
18 :
19 : impl Serialize for Lsn {
20 244739 : fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
21 244739 : where
22 244739 : S: serde::Serializer,
23 244739 : {
24 244739 : if serializer.is_human_readable() {
25 47660 : serializer.collect_str(self)
26 : } else {
27 197079 : self.0.serialize(serializer)
28 : }
29 244739 : }
30 : }
31 :
32 : impl<'de> Deserialize<'de> for Lsn {
33 13313024 : fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
34 13313024 : where
35 13313024 : D: serde::Deserializer<'de>,
36 13313024 : {
37 13313024 : struct LsnVisitor {
38 13313024 : is_human_readable_deserializer: bool,
39 13313024 : }
40 13313024 :
41 13313024 : impl<'de> Visitor<'de> for LsnVisitor {
42 13313024 : type Value = Lsn;
43 13313024 :
44 13313024 : fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
45 4 : if self.is_human_readable_deserializer {
46 13313024 : formatter.write_str(
47 2 : "value in form of hex string({upper_u32_hex}/{lower_u32_hex}) representing u64 integer",
48 2 : )
49 13313024 : } else {
50 13313024 : formatter.write_str("value in form of integer(u64)")
51 13313024 : }
52 13313024 : }
53 13313024 :
54 13313024 : fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
55 13299506 : where
56 13299506 : E: serde::de::Error,
57 13299506 : {
58 13299506 : Ok(Lsn(v))
59 13299506 : }
60 13313024 :
61 13313024 : fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
62 13514 : where
63 13514 : E: serde::de::Error,
64 13514 : {
65 13514 : Lsn::from_str(v).map_err(|e| E::custom(e))
66 13514 : }
67 13313024 : }
68 13313024 :
69 13313024 : if deserializer.is_human_readable() {
70 13516 : deserializer.deserialize_str(LsnVisitor {
71 13516 : is_human_readable_deserializer: true,
72 13516 : })
73 : } else {
74 13299508 : deserializer.deserialize_u64(LsnVisitor {
75 13299508 : is_human_readable_deserializer: false,
76 13299508 : })
77 : }
78 13313024 : }
79 : }
80 :
81 : /// Allows (de)serialization of an `Lsn` always as `u64`.
82 : ///
83 : /// ### Example
84 : ///
85 : /// ```rust
86 : /// # use serde::{Serialize, Deserialize};
87 : /// use utils::lsn::Lsn;
88 : ///
89 : /// #[derive(PartialEq, Serialize, Deserialize, Debug)]
90 : /// struct Foo {
91 : /// #[serde(with = "utils::lsn::serde_as_u64")]
92 : /// always_u64: Lsn,
93 : /// }
94 : ///
95 : /// let orig = Foo { always_u64: Lsn(1234) };
96 : ///
97 : /// let res = serde_json::to_string(&orig).unwrap();
98 : /// assert_eq!(res, r#"{"always_u64":1234}"#);
99 : ///
100 : /// let foo = serde_json::from_str::<Foo>(&res).unwrap();
101 : /// assert_eq!(foo, orig);
102 : /// ```
103 : ///
104 : pub mod serde_as_u64 {
105 : use super::Lsn;
106 :
107 : /// Serializes the Lsn as u64 disregarding the human readability of the format.
108 : ///
109 : /// Meant to be used via `#[serde(with = "...")]` or `#[serde(serialize_with = "...")]`.
110 0 : pub fn serialize<S: serde::Serializer>(lsn: &Lsn, serializer: S) -> Result<S::Ok, S::Error> {
111 0 : use serde::Serialize;
112 0 : lsn.0.serialize(serializer)
113 0 : }
114 :
115 : /// Deserializes the Lsn as u64 disregarding the human readability of the format.
116 : ///
117 : /// Meant to be used via `#[serde(with = "...")]` or `#[serde(deserialize_with = "...")]`.
118 9 : pub fn deserialize<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Lsn, D::Error> {
119 9 : use serde::Deserialize;
120 9 : u64::deserialize(deserializer).map(Lsn)
121 9 : }
122 : }
123 :
124 : /// We tried to parse an LSN from a string, but failed
125 2 : #[derive(Debug, PartialEq, Eq, thiserror::Error)]
126 : #[error("LsnParseError")]
127 : pub struct LsnParseError;
128 :
129 : impl Lsn {
130 : /// Maximum possible value for an LSN
131 : pub const MAX: Lsn = Lsn(u64::MAX);
132 :
133 : /// Invalid value for InvalidXLogRecPtr, as defined in xlogdefs.h
134 : pub const INVALID: Lsn = Lsn(0);
135 :
136 : /// Subtract a number, returning None on overflow.
137 2702978 : pub fn checked_sub<T: Into<u64>>(self, other: T) -> Option<Lsn> {
138 2702978 : let other: u64 = other.into();
139 2702978 : self.0.checked_sub(other).map(Lsn)
140 2702978 : }
141 :
142 : /// Subtract a number, returning the difference as i128 to avoid overflow.
143 1400630 : pub fn widening_sub<T: Into<u64>>(self, other: T) -> i128 {
144 1400630 : let other: u64 = other.into();
145 1400630 : i128::from(self.0) - i128::from(other)
146 1400630 : }
147 :
148 : /// Parse an LSN from a filename in the form `0000000000000000`
149 0 : pub fn from_filename<F>(filename: F) -> Result<Self, LsnParseError>
150 0 : where
151 0 : F: AsRef<Utf8Path>,
152 0 : {
153 0 : Lsn::from_hex(filename.as_ref().as_str())
154 0 : }
155 :
156 : /// Parse an LSN from a string in the form `0000000000000000`
157 129351 : pub fn from_hex<S>(s: S) -> Result<Self, LsnParseError>
158 129351 : where
159 129351 : S: AsRef<str>,
160 129351 : {
161 129351 : let s: &str = s.as_ref();
162 129351 : let n = u64::from_str_radix(s, 16).or(Err(LsnParseError))?;
163 101268 : Ok(Lsn(n))
164 129351 : }
165 :
166 : /// Compute the offset into a segment
167 : #[inline]
168 170743234 : pub fn segment_offset(self, seg_sz: usize) -> usize {
169 170743234 : (self.0 % seg_sz as u64) as usize
170 170743234 : }
171 :
172 : /// Compute LSN of the segment start.
173 : #[inline]
174 1482 : pub fn segment_lsn(self, seg_sz: usize) -> Lsn {
175 1482 : Lsn(self.0 - (self.0 % seg_sz as u64))
176 1482 : }
177 :
178 : /// Compute the segment number
179 : #[inline]
180 1755407 : pub fn segment_number(self, seg_sz: usize) -> u64 {
181 1755407 : self.0 / seg_sz as u64
182 1755407 : }
183 :
184 : /// Compute the offset into a block
185 : #[inline]
186 167499305 : pub fn block_offset(self) -> u64 {
187 167499305 : const BLCKSZ: u64 = XLOG_BLCKSZ as u64;
188 167499305 : self.0 % BLCKSZ
189 167499305 : }
190 :
191 : /// Compute the block offset of the first byte of this Lsn within this
192 : /// segment
193 : #[inline]
194 599 : pub fn page_lsn(self) -> Lsn {
195 599 : Lsn(self.0 - self.block_offset())
196 599 : }
197 :
198 : /// Compute the block offset of the first byte of this Lsn within this
199 : /// segment
200 : #[inline]
201 599 : pub fn page_offset_in_segment(self, seg_sz: usize) -> u64 {
202 599 : (self.0 - self.block_offset()) - self.segment_lsn(seg_sz).0
203 599 : }
204 :
205 : /// Compute the bytes remaining in this block
206 : ///
207 : /// If the LSN is already at the block boundary, it will return `XLOG_BLCKSZ`.
208 : #[inline]
209 164971198 : pub fn remaining_in_block(self) -> u64 {
210 164971198 : const BLCKSZ: u64 = XLOG_BLCKSZ as u64;
211 164971198 : BLCKSZ - (self.0 % BLCKSZ)
212 164971198 : }
213 :
214 : /// Compute the bytes remaining to fill a chunk of some size
215 : ///
216 : /// If the LSN is already at the chunk boundary, it will return 0.
217 765 : pub fn calc_padding<T: Into<u64>>(self, sz: T) -> u64 {
218 765 : let sz: u64 = sz.into();
219 765 : // By using wrapping_sub, we can subtract first and then mod second.
220 765 : // If it's done the other way around, then we would return a full
221 765 : // chunk size if we're already at the chunk boundary.
222 765 : // (Regular subtraction will panic on overflow in debug builds.)
223 765 : (sz.wrapping_sub(self.0)) % sz
224 765 : }
225 :
226 : /// Align LSN on 8-byte boundary (alignment of WAL records).
227 310596443 : pub fn align(&self) -> Lsn {
228 310596443 : Lsn((self.0 + 7) & !7)
229 310596443 : }
230 :
231 : /// Align LSN on 8-byte boundary (alignment of WAL records).
232 152591751 : pub fn is_aligned(&self) -> bool {
233 152591751 : *self == self.align()
234 152591751 : }
235 :
236 : /// Return if the LSN is valid
237 : /// mimics postgres XLogRecPtrIsInvalid macro
238 18208085 : pub fn is_valid(self) -> bool {
239 18208085 : self != Lsn::INVALID
240 18208085 : }
241 : }
242 :
243 : impl From<u64> for Lsn {
244 13622829 : fn from(n: u64) -> Self {
245 13622829 : Lsn(n)
246 13622829 : }
247 : }
248 :
249 : impl From<Lsn> for u64 {
250 9871446 : fn from(lsn: Lsn) -> u64 {
251 9871446 : lsn.0
252 9871446 : }
253 : }
254 :
255 : impl FromStr for Lsn {
256 : type Err = LsnParseError;
257 :
258 : /// Parse an LSN from a string in the form `00000000/00000000`
259 : ///
260 : /// If the input string is missing the '/' character, then use `Lsn::from_hex`
261 16147 : fn from_str(s: &str) -> Result<Self, Self::Err> {
262 16147 : let mut splitter = s.trim().split('/');
263 16147 : if let (Some(left), Some(right), None) = (splitter.next(), splitter.next(), splitter.next())
264 : {
265 16147 : let left_num = u32::from_str_radix(left, 16).map_err(|_| LsnParseError)?;
266 16141 : let right_num = u32::from_str_radix(right, 16).map_err(|_| LsnParseError)?;
267 16137 : Ok(Lsn((left_num as u64) << 32 | right_num as u64))
268 : } else {
269 0 : Err(LsnParseError)
270 : }
271 16147 : }
272 : }
273 :
274 : impl fmt::Display for Lsn {
275 7576621 : fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
276 7576621 : write!(f, "{:X}/{:X}", self.0 >> 32, self.0 & 0xffffffff)
277 7576621 : }
278 : }
279 :
280 : impl fmt::Debug for Lsn {
281 17514 : fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
282 17514 : write!(f, "{:X}/{:X}", self.0 >> 32, self.0 & 0xffffffff)
283 17514 : }
284 : }
285 :
286 : impl Add<u64> for Lsn {
287 : type Output = Lsn;
288 :
289 82714504 : fn add(self, other: u64) -> Self::Output {
290 82714504 : // panic if the addition overflows.
291 82714504 : Lsn(self.0.checked_add(other).unwrap())
292 82714504 : }
293 : }
294 :
295 : impl AddAssign<u64> for Lsn {
296 325832038 : fn add_assign(&mut self, other: u64) {
297 325832038 : // panic if the addition overflows.
298 325832038 : self.0 = self.0.checked_add(other).unwrap();
299 325832038 : }
300 : }
301 :
302 : /// An [`Lsn`] that can be accessed atomically.
303 : pub struct AtomicLsn {
304 : inner: AtomicU64,
305 : }
306 :
307 : impl AtomicLsn {
308 : /// Creates a new atomic `Lsn`.
309 6274 : pub fn new(val: u64) -> Self {
310 6274 : AtomicLsn {
311 6274 : inner: AtomicU64::new(val),
312 6274 : }
313 6274 : }
314 :
315 : /// Atomically retrieve the `Lsn` value from memory.
316 3005941 : pub fn load(&self) -> Lsn {
317 3005941 : Lsn(self.inner.load(Ordering::Acquire))
318 3005941 : }
319 :
320 : /// Atomically store a new `Lsn` value to memory.
321 15846 : pub fn store(&self, lsn: Lsn) {
322 15846 : self.inner.store(lsn.0, Ordering::Release);
323 15846 : }
324 :
325 : /// Adds to the current value, returning the previous value.
326 : ///
327 : /// This operation will panic on overflow.
328 2 : pub fn fetch_add(&self, val: u64) -> Lsn {
329 2 : let prev = self.inner.fetch_add(val, Ordering::AcqRel);
330 2 : assert!(prev.checked_add(val).is_some(), "AtomicLsn overflow");
331 2 : Lsn(prev)
332 2 : }
333 :
334 : /// Atomically sets the Lsn to the max of old and new value, returning the old value.
335 4 : pub fn fetch_max(&self, lsn: Lsn) -> Lsn {
336 4 : let prev = self.inner.fetch_max(lsn.0, Ordering::AcqRel);
337 4 : Lsn(prev)
338 4 : }
339 : }
340 :
341 : impl From<Lsn> for AtomicLsn {
342 424 : fn from(lsn: Lsn) -> Self {
343 424 : Self::new(lsn.0)
344 424 : }
345 : }
346 :
347 : /// Pair of LSN's pointing to the end of the last valid record and previous one
348 0 : #[derive(Debug, Clone, Copy)]
349 : pub struct RecordLsn {
350 : /// LSN at the end of the current record
351 : pub last: Lsn,
352 : /// LSN at the end of the previous record
353 : pub prev: Lsn,
354 : }
355 :
356 : /// Expose `self.last` as counter to be able to use RecordLsn in SeqWait
357 : impl MonotonicCounter<Lsn> for RecordLsn {
358 74770902 : fn cnt_advance(&mut self, lsn: Lsn) {
359 74770902 : assert!(self.last <= lsn);
360 74770902 : let new_prev = self.last;
361 74770902 : self.last = lsn;
362 74770902 : self.prev = new_prev;
363 74770902 : }
364 77928579 : fn cnt_value(&self) -> Lsn {
365 77928579 : self.last
366 77928579 : }
367 : }
368 :
369 : /// Implements [`rand::distributions::uniform::UniformSampler`] so we can sample [`Lsn`]s.
370 : ///
371 : /// This is used by the `pagebench` pageserver benchmarking tool.
372 : pub struct LsnSampler(<u64 as rand::distributions::uniform::SampleUniform>::Sampler);
373 :
374 : impl rand::distributions::uniform::SampleUniform for Lsn {
375 : type Sampler = LsnSampler;
376 : }
377 :
378 : impl rand::distributions::uniform::UniformSampler for LsnSampler {
379 : type X = Lsn;
380 :
381 0 : fn new<B1, B2>(low: B1, high: B2) -> Self
382 0 : where
383 0 : B1: rand::distributions::uniform::SampleBorrow<Self::X> + Sized,
384 0 : B2: rand::distributions::uniform::SampleBorrow<Self::X> + Sized,
385 0 : {
386 0 : Self(
387 0 : <u64 as rand::distributions::uniform::SampleUniform>::Sampler::new(
388 0 : low.borrow().0,
389 0 : high.borrow().0,
390 0 : ),
391 0 : )
392 0 : }
393 :
394 0 : fn new_inclusive<B1, B2>(low: B1, high: B2) -> Self
395 0 : where
396 0 : B1: rand::distributions::uniform::SampleBorrow<Self::X> + Sized,
397 0 : B2: rand::distributions::uniform::SampleBorrow<Self::X> + Sized,
398 0 : {
399 0 : Self(
400 0 : <u64 as rand::distributions::uniform::SampleUniform>::Sampler::new_inclusive(
401 0 : low.borrow().0,
402 0 : high.borrow().0,
403 0 : ),
404 0 : )
405 0 : }
406 :
407 0 : fn sample<R: rand::prelude::Rng + ?Sized>(&self, rng: &mut R) -> Self::X {
408 0 : Lsn(self.0.sample(rng))
409 0 : }
410 : }
411 :
412 : #[cfg(test)]
413 : mod tests {
414 : use crate::bin_ser::BeSer;
415 :
416 : use super::*;
417 :
418 : use serde::ser::Serialize;
419 : use serde_assert::{Deserializer, Serializer, Token, Tokens};
420 :
421 2 : #[test]
422 2 : fn test_lsn_strings() {
423 2 : assert_eq!("12345678/AAAA5555".parse(), Ok(Lsn(0x12345678AAAA5555)));
424 2 : assert_eq!("aaaa/bbbb".parse(), Ok(Lsn(0x0000AAAA0000BBBB)));
425 2 : assert_eq!("1/A".parse(), Ok(Lsn(0x000000010000000A)));
426 2 : assert_eq!("0/0".parse(), Ok(Lsn(0)));
427 2 : "ABCDEFG/12345678".parse::<Lsn>().unwrap_err();
428 2 : "123456789/AAAA5555".parse::<Lsn>().unwrap_err();
429 2 : "12345678/AAAA55550".parse::<Lsn>().unwrap_err();
430 2 : "-1/0".parse::<Lsn>().unwrap_err();
431 2 : "1/-1".parse::<Lsn>().unwrap_err();
432 2 :
433 2 : assert_eq!(format!("{}", Lsn(0x12345678AAAA5555)), "12345678/AAAA5555");
434 2 : assert_eq!(format!("{}", Lsn(0x000000010000000A)), "1/A");
435 :
436 2 : assert_eq!(
437 2 : Lsn::from_hex("12345678AAAA5555"),
438 2 : Ok(Lsn(0x12345678AAAA5555))
439 2 : );
440 2 : assert_eq!(Lsn::from_hex("0"), Ok(Lsn(0)));
441 2 : assert_eq!(Lsn::from_hex("F12345678AAAA5555"), Err(LsnParseError));
442 :
443 2 : let expected_lsn = Lsn(0x3C490F8);
444 2 : assert_eq!(" 0/3C490F8".parse(), Ok(expected_lsn));
445 2 : assert_eq!("0/3C490F8 ".parse(), Ok(expected_lsn));
446 2 : assert_eq!(" 0/3C490F8 ".parse(), Ok(expected_lsn));
447 2 : }
448 :
449 2 : #[test]
450 2 : fn test_lsn_math() {
451 2 : assert_eq!(Lsn(1234) + 11u64, Lsn(1245));
452 :
453 2 : assert_eq!(
454 2 : {
455 2 : let mut lsn = Lsn(1234);
456 2 : lsn += 11u64;
457 2 : lsn
458 2 : },
459 2 : Lsn(1245)
460 2 : );
461 :
462 2 : assert_eq!(Lsn(1234).checked_sub(1233u64), Some(Lsn(1)));
463 2 : assert_eq!(Lsn(1234).checked_sub(1235u64), None);
464 :
465 2 : assert_eq!(Lsn(1235).widening_sub(1234u64), 1);
466 2 : assert_eq!(Lsn(1234).widening_sub(1235u64), -1);
467 2 : assert_eq!(Lsn(u64::MAX).widening_sub(0u64), i128::from(u64::MAX));
468 2 : assert_eq!(Lsn(0).widening_sub(u64::MAX), -i128::from(u64::MAX));
469 :
470 2 : let seg_sz: usize = 16 * 1024 * 1024;
471 2 : assert_eq!(Lsn(0x1000007).segment_offset(seg_sz), 7);
472 2 : assert_eq!(Lsn(0x1000007).segment_number(seg_sz), 1u64);
473 :
474 2 : assert_eq!(Lsn(0x4007).block_offset(), 7u64);
475 2 : assert_eq!(Lsn(0x4000).block_offset(), 0u64);
476 2 : assert_eq!(Lsn(0x4007).remaining_in_block(), 8185u64);
477 2 : assert_eq!(Lsn(0x4000).remaining_in_block(), 8192u64);
478 :
479 2 : assert_eq!(Lsn(0xffff01).calc_padding(seg_sz as u64), 255u64);
480 2 : assert_eq!(Lsn(0x2000000).calc_padding(seg_sz as u64), 0u64);
481 2 : assert_eq!(Lsn(0xffff01).calc_padding(8u32), 7u64);
482 2 : assert_eq!(Lsn(0xffff00).calc_padding(8u32), 0u64);
483 2 : }
484 :
485 2 : #[test]
486 2 : fn test_atomic_lsn() {
487 2 : let lsn = AtomicLsn::new(0);
488 2 : assert_eq!(lsn.fetch_add(1234), Lsn(0));
489 2 : assert_eq!(lsn.load(), Lsn(1234));
490 2 : lsn.store(Lsn(5678));
491 2 : assert_eq!(lsn.load(), Lsn(5678));
492 :
493 2 : assert_eq!(lsn.fetch_max(Lsn(6000)), Lsn(5678));
494 2 : assert_eq!(lsn.fetch_max(Lsn(5000)), Lsn(6000));
495 2 : }
496 :
497 2 : #[test]
498 2 : fn test_lsn_serde() {
499 2 : let original_lsn = Lsn(0x0123456789abcdef);
500 2 : let expected_readable_tokens = Tokens(vec![Token::U64(0x0123456789abcdef)]);
501 2 : let expected_non_readable_tokens =
502 2 : Tokens(vec![Token::Str(String::from("1234567/89ABCDEF"))]);
503 2 :
504 2 : // Testing human_readable ser/de
505 2 : let serializer = Serializer::builder().is_human_readable(false).build();
506 2 : let readable_ser_tokens = original_lsn.serialize(&serializer).unwrap();
507 2 : assert_eq!(readable_ser_tokens, expected_readable_tokens);
508 :
509 2 : let mut deserializer = Deserializer::builder()
510 2 : .is_human_readable(false)
511 2 : .tokens(readable_ser_tokens)
512 2 : .build();
513 2 : let des_lsn = Lsn::deserialize(&mut deserializer).unwrap();
514 2 : assert_eq!(des_lsn, original_lsn);
515 :
516 : // Testing NON human_readable ser/de
517 2 : let serializer = Serializer::builder().is_human_readable(true).build();
518 2 : let non_readable_ser_tokens = original_lsn.serialize(&serializer).unwrap();
519 2 : assert_eq!(non_readable_ser_tokens, expected_non_readable_tokens);
520 :
521 2 : let mut deserializer = Deserializer::builder()
522 2 : .is_human_readable(true)
523 2 : .tokens(non_readable_ser_tokens)
524 2 : .build();
525 2 : let des_lsn = Lsn::deserialize(&mut deserializer).unwrap();
526 2 : assert_eq!(des_lsn, original_lsn);
527 :
528 : // Testing mismatching ser/de
529 2 : let serializer = Serializer::builder().is_human_readable(false).build();
530 2 : let non_readable_ser_tokens = original_lsn.serialize(&serializer).unwrap();
531 2 :
532 2 : let mut deserializer = Deserializer::builder()
533 2 : .is_human_readable(true)
534 2 : .tokens(non_readable_ser_tokens)
535 2 : .build();
536 2 : Lsn::deserialize(&mut deserializer).unwrap_err();
537 2 :
538 2 : let serializer = Serializer::builder().is_human_readable(true).build();
539 2 : let readable_ser_tokens = original_lsn.serialize(&serializer).unwrap();
540 2 :
541 2 : let mut deserializer = Deserializer::builder()
542 2 : .is_human_readable(false)
543 2 : .tokens(readable_ser_tokens)
544 2 : .build();
545 2 : Lsn::deserialize(&mut deserializer).unwrap_err();
546 2 : }
547 :
548 2 : #[test]
549 2 : fn test_lsn_ensure_roundtrip() {
550 2 : let original_lsn = Lsn(0xaaaabbbb);
551 2 :
552 2 : let serializer = Serializer::builder().is_human_readable(false).build();
553 2 : let ser_tokens = original_lsn.serialize(&serializer).unwrap();
554 2 :
555 2 : let mut deserializer = Deserializer::builder()
556 2 : .is_human_readable(false)
557 2 : .tokens(ser_tokens)
558 2 : .build();
559 2 :
560 2 : let des_lsn = Lsn::deserialize(&mut deserializer).unwrap();
561 2 : assert_eq!(des_lsn, original_lsn);
562 2 : }
563 :
564 2 : #[test]
565 2 : fn test_lsn_bincode_serde() {
566 2 : let lsn = Lsn(0x0123456789abcdef);
567 2 : let expected_bytes = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef];
568 2 :
569 2 : let ser_bytes = lsn.ser().unwrap();
570 2 : assert_eq!(ser_bytes, expected_bytes);
571 :
572 2 : let des_lsn = Lsn::des(&ser_bytes).unwrap();
573 2 : assert_eq!(des_lsn, lsn);
574 2 : }
575 :
576 2 : #[test]
577 2 : fn test_lsn_bincode_ensure_roundtrip() {
578 2 : let original_lsn = Lsn(0x01_02_03_04_05_06_07_08);
579 2 : let expected_bytes = vec![0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08];
580 2 :
581 2 : let ser_bytes = original_lsn.ser().unwrap();
582 2 : assert_eq!(ser_bytes, expected_bytes);
583 :
584 2 : let des_lsn = Lsn::des(&ser_bytes).unwrap();
585 2 : assert_eq!(des_lsn, original_lsn);
586 2 : }
587 : }
|