| 1 | use byteorder::{BigEndian, ByteOrder}; |
| 2 | use sqlx_core::bytes::Bytes; |
| 3 | |
| 4 | use crate::error::Error; |
| 5 | use 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)] |
| 10 | pub 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 | |
| 18 | impl 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] |
| 33 | fn 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] |
| 44 | fn 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 | } |