sqlx_postgres/message/
startup.rs1use crate::io::PgBufMutExt;
2use crate::io::{BufMutExt, ProtocolEncode};
3
4pub struct Startup<'a> {
11 pub username: Option<&'a str>,
13
14 pub database: Option<&'a str>,
16
17 pub params: &'a [(&'a str, &'a str)],
20}
21
22impl ProtocolEncode<'_> for Startup<'_> {
24 fn encode_with(&self, buf: &mut Vec<u8>, _context: ()) -> Result<(), crate::Error> {
25 buf.reserve(120);
26
27 buf.put_length_prefixed(|buf| {
28 buf.extend(&196_608_i32.to_be_bytes());
33
34 if let Some(username) = self.username {
35 encode_startup_param(buf, "user", username);
37 }
38
39 if let Some(database) = self.database {
40 encode_startup_param(buf, "database", database);
42 }
43
44 for (name, value) in self.params {
45 encode_startup_param(buf, name, value);
46 }
47
48 buf.push(0);
51
52 Ok(())
53 })
54 }
55}
56
57#[inline]
58fn encode_startup_param(buf: &mut Vec<u8>, name: &str, value: &str) {
59 buf.put_str_nul(name);
60 buf.put_str_nul(value);
61}
62
63#[test]
64fn test_encode_startup() {
65 const EXPECTED: &[u8] = b"\0\0\0)\0\x03\0\0user\0postgres\0database\0postgres\0\0";
66
67 let mut buf = Vec::new();
68 let m = Startup {
69 username: Some("postgres"),
70 database: Some("postgres"),
71 params: &[],
72 };
73
74 m.encode(&mut buf).unwrap();
75
76 assert_eq!(buf, EXPECTED);
77}
78
79#[cfg(all(test, not(debug_assertions)))]
80#[bench]
81fn bench_encode_startup(b: &mut test::Bencher) {
82 use test::black_box;
83
84 let mut buf = Vec::with_capacity(128);
85
86 b.iter(|| {
87 buf.clear();
88
89 black_box(Startup {
90 username: Some("postgres"),
91 database: Some("postgres"),
92 params: &[],
93 })
94 .encode(&mut buf);
95 });
96}