sqlx_postgres/message/
backend_key_data.rs

1use byteorder::{BigEndian, ByteOrder};
2use sqlx_core::bytes::Bytes;
3
4use crate::error::Error;
5use crate::message::{BackendMessage, BackendMessageFormat};
6
7/// Contains cancellation key data. The frontend must save these values if it
8/// wishes to be able to issue `CancelRequest` messages later.
9#[derive(Debug)]
10pub struct BackendKeyData {
11    /// The process ID of this database.
12    pub process_id: u32,
13
14    /// The secret key of this database.
15    pub secret_key: u32,
16}
17
18impl BackendMessage for BackendKeyData {
19    const FORMAT: BackendMessageFormat = BackendMessageFormat::BackendKeyData;
20
21    fn decode_body(buf: Bytes) -> Result<Self, Error> {
22        let process_id = BigEndian::read_u32(&buf);
23        let secret_key = BigEndian::read_u32(&buf[4..]);
24
25        Ok(Self {
26            process_id,
27            secret_key,
28        })
29    }
30}
31
32#[test]
33fn test_decode_backend_key_data() {
34    const DATA: &[u8] = b"\0\0'\xc6\x89R\xc5+";
35
36    let m = BackendKeyData::decode_body(DATA.into()).unwrap();
37
38    assert_eq!(m.process_id, 10182);
39    assert_eq!(m.secret_key, 2303903019);
40}
41
42#[cfg(all(test, not(debug_assertions)))]
43#[bench]
44fn bench_decode_backend_key_data(b: &mut test::Bencher) {
45    const DATA: &[u8] = b"\0\0'\xc6\x89R\xc5+";
46
47    b.iter(|| {
48        BackendKeyData::decode_body(test::black_box(Bytes::from_static(DATA))).unwrap();
49    });
50}