Skip to main content

bulk_client/common/
serialization.rs

1//! Binary serialization primitives.
2//!
3//! Two contexts use slightly different wire formats:
4//!
5//! | Context            | String-length prefix | Used by                    |
6//! |--------------------|----------------------|----------------------------|
7//! | Order-ID hashing   | `u32` (4 bytes LE)   | `LimitOrder::order_id()`   |
8//! | Transaction signing| `u64` (8 bytes LE)   | `Transaction::serialize()`  |
9//!
10//! Both are little-endian throughout.
11
12use solana_pubkey::Pubkey;
13
14/// Write a `u8` (1 byte).
15#[inline]
16#[allow(unused)]
17pub fn write_u8(buf: &mut Vec<u8>, v: u8) {
18    buf.push(v);
19}
20
21/// Write a `u32` in little-endian.
22#[inline]
23#[allow(unused)]
24pub fn write_u32(buf: &mut Vec<u8>, v: u32) {
25    buf.extend_from_slice(&v.to_le_bytes());
26}
27
28/// Write a `u64` in little-endian.
29#[inline]
30#[allow(unused)]
31pub fn write_u64(buf: &mut Vec<u8>, v: u64) {
32    buf.extend_from_slice(&v.to_le_bytes());
33}
34
35/// Write an `f64` in little-endian.
36#[inline]
37#[allow(unused)]
38pub fn write_f64(buf: &mut Vec<u8>, v: f64) {
39    buf.extend_from_slice(&v.to_le_bytes());
40}
41
42/// Write a boolean as a single byte (0 or 1).
43#[inline]
44#[allow(unused)]
45pub fn write_bool(buf: &mut Vec<u8>, v: bool) {
46    buf.push(if v { 1 } else { 0 });
47}
48
49/// Write a length-prefixed UTF-8 string with a **u32** length prefix.
50/// Used for order-ID hash generation.
51#[allow(unused)]
52pub fn write_string_u32(buf: &mut Vec<u8>, s: &str) {
53    let bytes = s.as_bytes();
54    write_u32(buf, bytes.len() as u32);
55    buf.extend_from_slice(bytes);
56}
57
58/// Write a length-prefixed UTF-8 string with a **u64** length prefix.
59/// Used for transaction serialization (signing).
60#[allow(unused)]
61pub fn write_string_u64(buf: &mut Vec<u8>, s: &str) {
62    let bytes = s.as_bytes();
63    write_u64(buf, bytes.len() as u64);
64    buf.extend_from_slice(bytes);
65}
66
67/// Write a [`Pubkey`]'s raw 32 bytes into the buffer.
68#[inline]
69#[allow(unused)]
70pub fn write_pubkey_bytes(buf: &mut Vec<u8>, key: &Pubkey) {
71    buf.extend_from_slice(&key.to_bytes());
72}