Skip to main content

nautilus_binance/common/
encoder.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Deterministic two-way encoder for Binance integration prefixes.
17//!
18//! The Binance integration ID is automatically prefixed to supported system-generated
19//! client order IDs placed through the Binance adapter. Prefixing is transparent
20//! to strategies and requires no user configuration.
21//! Inbound order events are decoded back to the original `ClientOrderId`
22//! before reaching the trading system.
23//!
24//! Binance's [Link and Trade] program requires the `newClientOrderId`
25//! parameter to start with `x-{BROKER_ID}` for order attribution. Binance
26//! enforces a 36-character limit on this field with the regex
27//! `^[\.A-Z\:/a-z0-9_-]{1,36}$`.
28//!
29//! Internal Nautilus `ClientOrderId` values (O-format: 23+ chars, UUID: 32-36
30//! chars) exceed the 36-char limit when combined with the integration prefix. This
31//! module provides compact, deterministic, two-way encoding via pure functions.
32//!
33//! [Link and Trade]: https://www.binance.com/en/support/faq/detail/a78a065d0c4846aaa1af474d8e712ab9
34//!
35//! # Wire format
36//!
37//! ```text
38//! Legacy:    x-TD67BGP9-{signal}{base62_payload}
39//! Short tag: x-TD67BGP9A{base62_payload}
40//! ```
41//!
42//! The prefix `x-{BROKER_ID}-` is 11 chars (for an 8-char integration ID), leaving
43//! 25 chars for the encoded component. Spot and Futures use separate integration
44//! IDs defined in [`consts`](super::consts). The supplementary `A` format omits
45//! the separator after the integration ID and occupies 24 characters in total.
46//!
47//! # Signal chars
48//!
49//! The first character after the prefix identifies the original format so the
50//! decoder can reconstruct the exact original `ClientOrderId` string.
51//!
52//! | Signal | Original format            | Payload length | Total |
53//! |--------|----------------------------|----------------|-------|
54//! | `T`    | O-format with hyphens      | 13 base62      | 25    |
55//! | `t`    | O-format without hyphens   | 13 base62      | 25    |
56//! | `U`    | UUID with hyphens          | 22 base62      | 34    |
57//! | `u`    | UUID without hyphens       | 22 base62      | 34    |
58//! | `R`    | Raw passthrough            | variable       | <= 36 |
59//! | `A`    | O-format with a short tag  | 13 base62      | 24    |
60//!
61//! # O-format packing (72 bits -> 13 base62 chars)
62//!
63//! The O-format `ClientOrderId` `O-YYYYMMDD-HHMMSS-TTT-SSS-CCC` is packed
64//! into a 72-bit integer:
65//!
66//! ```text
67//! bits [71:40] (32 bits): seconds since 2020-01-01 epoch
68//! bits [39:30] (10 bits): trader tag (0-1023)
69//! bits [29:20] (10 bits): strategy tag (0-1023)
70//! bits [19:0]  (20 bits): count (0-1048575)
71//! ```
72//!
73//! # Short-tag O-format packing (77 bits -> 13 base62 chars)
74//!
75//! The `A` format preserves hyphenated factory IDs such as
76//! `O-20260922-160119-V2-000-8`. One tag contains one or two ASCII alphanumeric
77//! characters; the other is a canonical numeric tag in `[0, 1023]`, padded to
78//! at least three digits. The count is in `[0, 4194303]` without leading zeros.
79//! Timestamps cover `[2020-01-01 00:00:00, 2156-02-07 06:28:15]` UTC.
80//!
81//! ```text
82//! bits [76:45] (32 bits): seconds since 2020-01-01 epoch
83//! bit  [44]    (1 bit):  short tag is the strategy tag
84//! bits [43:32] (12 bits): one/two-character base62 tag, with length
85//! bits [31:22] (10 bits): numeric tag
86//! bits [21:0]  (22 bits): count
87//! ```
88//!
89//! Exact reconstruction preserves tag spelling and rejects normalized dates.
90//! Existing numeric, UUID, and raw encodings take precedence and retain their
91//! wire representation. Historical unprefixed fallback outputs contain at least
92//! 25 characters, so the 24-character supplementary format cannot be mistaken
93//! for any historical encoder output. A custom ID resembling this format is
94//! short enough to use the existing `R` wrapper.
95//!
96//! IDs outside the supported compact formats and raw prefix budget are sent
97//! unchanged with a warning; Binance's length and character limits still apply.
98//!
99//! # UUID packing (128 bits -> 22 base62 chars)
100//!
101//! The UUID is parsed from hex into a 128-bit integer and base62-encoded.
102//!
103//! # Decoding
104//!
105//! The decoder recognizes the 24-character `x-{BROKER_ID}A` format first,
106//! then the legacy `x-{BROKER_ID}-` signal formats. Other strings pass through
107//! unchanged, including historical unprefixed IDs. This keeps a longer custom
108//! ID starting with `x-{BROKER_ID}A` distinct from the short-tag format.
109//!
110//! Existing-order operations without a venue order ID query both supplementary
111//! and historical unprefixed identities. Different matching venue IDs are
112//! rejected as ambiguous before modification or cancellation.
113//!
114//! # Performance
115//!
116//! Base62 encoding uses a stack buffer and ten-digit chunks to limit wide
117//! integer division. Prefix construction writes directly into the result string.
118//! The `bench_encode_decode_timing` test provides a local timing check.
119//! Existing-order compatibility resolution may add two HTTP lookups.
120//!
121//! An isolated codec comparison compiled with `opt-level=3` measures the following
122//! median nanoseconds per operation over 25 interleaved batches of 100,000 calls.
123//! Timings are machine-dependent and exclude HTTP requests.
124//!
125//! | Format                   | Encode before | Encode after | Decode before | Decode after |
126//! | ------------------------ | ------------- | ------------ | ------------- | ------------ |
127//! | O-format with hyphens    | 102           | 44           | 201           | 124          |
128//! | O-format without hyphens | 99            | 41           | 192           | 116          |
129//! | UUID with hyphens        | 243           | 60           | 72            | 47           |
130//! | UUID without hyphens     | 240           | 57           | 67            | 43           |
131//! | Raw prefixed ID          | 34            | 16           | 39            | 21           |
132//! | Short-tag O-format       | N/A           | 174          | N/A           | 117          |
133//!
134//! Short-tag IDs previously used unprefixed passthrough (37 ns encode, 38 ns decode),
135//! which performs no compression and is not equivalent to short-tag encoding.
136
137use std::fmt::Write;
138
139use anyhow::Context;
140use nautilus_model::identifiers::ClientOrderId;
141
142/// Base62 encoding alphabet: `0-9 A-Z a-z`.
143const BASE62_CHARS: &[u8; 62] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
144
145/// Lookup table mapping ASCII byte values to base62 digit values.
146/// Invalid characters map to `0xFF`.
147const BASE62_DECODE: [u8; 128] = {
148    let mut table = [0xFFu8; 128];
149    let mut i = 0u8;
150    while i < 62 {
151        table[BASE62_CHARS[i as usize] as usize] = i;
152        i += 1;
153    }
154    table
155};
156
157/// Base epoch for O-format timestamp encoding: 2020-01-01 00:00:00 UTC.
158const O_FORMAT_EPOCH: i64 = 1_577_836_800;
159
160/// Fixed base62 output length for O-format packed values (72 bits).
161const O_FORMAT_B62_LEN: usize = 13;
162
163/// Fixed base62 output length for UUID packed values (128 bits).
164const UUID_B62_LEN: usize = 22;
165
166/// Maximum `newClientOrderId` length allowed by the Binance API.
167const MAX_CLIENT_ORDER_ID_LEN: usize = 36;
168
169const SIGNAL_O_HYPHENS: u8 = b'T';
170const SIGNAL_O_NO_HYPHENS: u8 = b't';
171const SIGNAL_UUID_HYPHENS: u8 = b'U';
172const SIGNAL_UUID_NO_HYPHENS: u8 = b'u';
173const SIGNAL_RAW: u8 = b'R';
174const SIGNAL_O_TAGS: u8 = b'A';
175const O_TAGS_B62_LEN: usize = 13;
176const O_TAGS_COUNT_BITS: u32 = 22;
177const O_TAGS_COUNT_MAX: u32 = (1 << O_TAGS_COUNT_BITS) - 1;
178
179/// Encodes a `ClientOrderId` into a Binance-compatible string with an integration prefix.
180///
181/// The encoding is deterministic and reversible with [`decode_broker_id`].
182#[must_use]
183pub fn encode_broker_id(client_order_id: &ClientOrderId, broker_id: &str) -> String {
184    let id_str = client_order_id.as_str();
185    let budget = MAX_CLIENT_ORDER_ID_LEN - (3 + broker_id.len());
186
187    if let Some((packed, has_hyphens)) = pack_o_format(id_str) {
188        let signal = if has_hyphens {
189            SIGNAL_O_HYPHENS
190        } else {
191            SIGNAL_O_NO_HYPHENS
192        };
193        let b62 = encode_base62::<O_FORMAT_B62_LEN>(packed);
194        return build_encoded(broker_id, signal, &b62);
195    }
196
197    if let Some((value, has_hyphens)) = parse_uuid_hex(id_str) {
198        let signal = if has_hyphens {
199            SIGNAL_UUID_HYPHENS
200        } else {
201            SIGNAL_UUID_NO_HYPHENS
202        };
203        let b62 = encode_base62::<UUID_B62_LEN>(value);
204        return build_encoded(broker_id, signal, &b62);
205    }
206
207    if id_str.len() < budget {
208        return build_encoded(broker_id, SIGNAL_RAW, id_str.as_bytes());
209    }
210
211    // Keep the new format shorter than any historical passthrough ID
212    if 3 + broker_id.len() + O_TAGS_B62_LEN < budget
213        && let Some(packed) = pack_o_tags(id_str)
214    {
215        return build_encoded(
216            broker_id,
217            SIGNAL_O_TAGS,
218            &encode_base62::<O_TAGS_B62_LEN>(packed),
219        );
220    }
221
222    log::warn!(
223        "ClientOrderId '{id_str}' ({} chars) exceeds broker ID encoding budget ({budget} chars), sending without prefix",
224        id_str.len(),
225    );
226    id_str.to_string()
227}
228
229/// Decodes an encoded string back to the original `ClientOrderId` value.
230///
231/// If the string starts with a known integration prefix, the payload is decoded and
232/// the original ID is reconstructed. Strings without a recognized prefix are
233/// returned as-is for backward compatibility.
234#[must_use]
235pub fn decode_broker_id(encoded: &str, broker_id: &str) -> String {
236    match decode_broker_id_checked(encoded, broker_id) {
237        Ok(decoded) => decoded,
238        Err(e) => {
239            log::warn!("Failed to decode broker client order ID: {e}");
240            encoded.to_string()
241        }
242    }
243}
244
245/// Decodes and validates an inbound Binance client order ID.
246///
247/// Strings without the expected integration prefix are treated as legacy IDs and
248/// validated without decoding.
249///
250/// # Errors
251///
252/// Returns an error if the integration encoding is malformed or the
253/// decoded client order ID is invalid.
254pub(crate) fn decode_client_order_id(
255    encoded: &str,
256    broker_id: &str,
257) -> anyhow::Result<ClientOrderId> {
258    let decoded = decode_broker_id_checked(encoded, broker_id)?;
259    ClientOrderId::new_checked(decoded)
260        .with_context(|| format!("invalid Binance client order ID '{encoded}'"))
261}
262
263fn decode_broker_id_checked(encoded: &str, broker_id: &str) -> anyhow::Result<String> {
264    if let Some(data) = tagged_payload(encoded, broker_id) {
265        let packed =
266            decode_base62(data).context("invalid tagged O-format broker client order ID")?;
267        return unpack_o_tags(packed);
268    }
269
270    let Some(payload) = encoded
271        .strip_prefix("x-")
272        .and_then(|s| s.strip_prefix(broker_id))
273        .and_then(|s| s.strip_prefix('-'))
274    else {
275        return Ok(encoded.to_string());
276    };
277
278    let Some((&signal, data)) = payload.as_bytes().split_first() else {
279        anyhow::bail!("missing broker client order ID signal");
280    };
281
282    match signal {
283        SIGNAL_O_HYPHENS | SIGNAL_O_NO_HYPHENS => {
284            anyhow::ensure!(
285                data.len() == O_FORMAT_B62_LEN,
286                "invalid O-format broker client order ID payload length"
287            );
288            let packed = decode_base62(data).context("invalid O-format broker client order ID")?;
289            Ok(unpack_o_format(packed, signal == SIGNAL_O_HYPHENS))
290        }
291        SIGNAL_UUID_HYPHENS | SIGNAL_UUID_NO_HYPHENS => {
292            anyhow::ensure!(
293                data.len() == UUID_B62_LEN,
294                "invalid UUID broker client order ID payload length"
295            );
296            let value = decode_base62(data).context("invalid UUID broker client order ID")?;
297            Ok(format_uuid(value, signal == SIGNAL_UUID_HYPHENS))
298        }
299        SIGNAL_RAW => {
300            let raw = std::str::from_utf8(data).context("invalid raw broker client order ID")?;
301            anyhow::ensure!(
302                !raw.is_empty(),
303                "missing raw broker client order ID payload"
304            );
305            Ok(raw.to_string())
306        }
307        _ => anyhow::bail!(
308            "unknown broker client order ID signal byte '{}'",
309            signal as char
310        ),
311    }
312}
313
314pub(crate) fn legacy_client_order_id(encoded: &str, broker_id: &str) -> Option<String> {
315    let packed = decode_base62(tagged_payload(encoded, broker_id)?)?;
316    unpack_o_tags(packed).ok()
317}
318
319fn tagged_payload<'a>(encoded: &'a str, broker_id: &str) -> Option<&'a [u8]> {
320    if encoded.len() != 3 + broker_id.len() + O_TAGS_B62_LEN
321        || encoded.len() >= MAX_CLIENT_ORDER_ID_LEN - (3 + broker_id.len())
322    {
323        return None;
324    }
325
326    let payload = encoded.strip_prefix("x-")?.strip_prefix(broker_id)?;
327    let (&signal, data) = payload.as_bytes().split_first()?;
328    (signal == SIGNAL_O_TAGS).then_some(data)
329}
330
331fn build_encoded(broker_id: &str, signal: u8, payload: &[u8]) -> String {
332    let tagged = signal == SIGNAL_O_TAGS;
333    let mut result =
334        String::with_capacity(3 + broker_id.len() + usize::from(!tagged) + payload.len());
335    result.push_str("x-");
336    result.push_str(broker_id);
337
338    if !tagged {
339        result.push('-');
340    }
341
342    result.push(signal as char);
343    result.push_str(std::str::from_utf8(payload).expect("encoded ID is valid UTF-8"));
344    result
345}
346
347fn encode_base62<const N: usize>(mut value: u128) -> [u8; N] {
348    const DIGITS: usize = 10;
349    const RADIX: u128 = 62u128.pow(DIGITS as u32);
350    let mut buf = [b'0'; N];
351    for chunk in buf.rchunks_mut(DIGITS) {
352        let mut part = (value % RADIX) as u64;
353        value /= RADIX;
354
355        for byte in chunk.iter_mut().rev() {
356            *byte = BASE62_CHARS[(part % 62) as usize];
357            part /= 62;
358        }
359    }
360    buf
361}
362
363fn decode_base62(encoded: &[u8]) -> Option<u128> {
364    let mut value: u128 = 0;
365
366    for &byte in encoded {
367        let digit = BASE62_DECODE[byte as usize & 0x7F];
368
369        if digit == 0xFF || !byte.is_ascii() {
370            return None;
371        }
372        value = value.checked_mul(62)?.checked_add(digit as u128)?;
373    }
374    Some(value)
375}
376
377fn parse_digits(bytes: &[u8]) -> Option<u32> {
378    let mut n: u32 = 0;
379
380    for &b in bytes {
381        if !b.is_ascii_digit() {
382            return None;
383        }
384        n = n * 10 + (b - b'0') as u32;
385    }
386    Some(n)
387}
388
389fn pack_o_format(id_str: &str) -> Option<(u128, bool)> {
390    let b = id_str.as_bytes();
391
392    if b.first() != Some(&b'O') {
393        return None;
394    }
395
396    let (year, month, day, hour, minute, second, trader, strategy, count, has_hyphens) =
397        if b.get(1) == Some(&b'-') {
398            // With hyphens: O-YYYYMMDD-HHMMSS-TTT-SSS-CCC
399            // Find hyphen positions manually to avoid Vec allocation
400            if b.len() < 23 || b[10] != b'-' || b[17] != b'-' {
401                return None;
402            }
403            let h4 = memchr_byte(b'-', &b[18..])?;
404            let trader_end = 18 + h4;
405            let h5 = memchr_byte(b'-', &b[trader_end + 1..])?;
406            let strategy_end = trader_end + 1 + h5;
407
408            (
409                parse_digits(&b[2..6])?,
410                parse_digits(&b[6..8])?,
411                parse_digits(&b[8..10])?,
412                parse_digits(&b[11..13])?,
413                parse_digits(&b[13..15])?,
414                parse_digits(&b[15..17])?,
415                parse_digits(&b[18..trader_end])?,
416                parse_digits(&b[trader_end + 1..strategy_end])?,
417                parse_digits(&b[strategy_end + 1..])?,
418                true,
419            )
420        } else {
421            // Without hyphens: OYYYYMMDDHHMMSSTTTSSSCC...
422            if b.len() < 22 {
423                return None;
424            }
425            (
426                parse_digits(&b[1..5])?,
427                parse_digits(&b[5..7])?,
428                parse_digits(&b[7..9])?,
429                parse_digits(&b[9..11])?,
430                parse_digits(&b[11..13])?,
431                parse_digits(&b[13..15])?,
432                parse_digits(&b[15..18])?,
433                parse_digits(&b[18..21])?,
434                parse_digits(&b[21..])?,
435                false,
436            )
437        };
438
439    if trader > 1023 || strategy > 1023 || count > 0xF_FFFF {
440        return None;
441    }
442
443    let secs_since_epoch = civil_to_epoch(year, month, day, hour, minute, second)? - O_FORMAT_EPOCH;
444
445    if secs_since_epoch < 0 {
446        return None;
447    }
448
449    let packed = (secs_since_epoch as u128) << 40
450        | (trader as u128) << 30
451        | (strategy as u128) << 20
452        | (count as u128);
453
454    Some((packed, has_hyphens))
455}
456
457fn unpack_o_format(packed: u128, has_hyphens: bool) -> String {
458    let count = (packed & 0xF_FFFF) as u32;
459    let strategy = ((packed >> 20) & 0x3FF) as u32;
460    let trader = ((packed >> 30) & 0x3FF) as u32;
461    let secs_since_epoch = (packed >> 40) as i64;
462
463    let timestamp = secs_since_epoch + O_FORMAT_EPOCH;
464    let Some((year, month, day, hour, minute, second)) = epoch_to_civil(timestamp) else {
465        log::warn!("Failed to decode O-format timestamp: {timestamp}");
466        return format!("DECODE_ERROR_{packed}");
467    };
468
469    let mut result = String::with_capacity(MAX_CLIENT_ORDER_ID_LEN);
470
471    if has_hyphens {
472        write!(result, "O-{year:04}{month:02}{day:02}-{hour:02}{minute:02}{second:02}-{trader:03}-{strategy:03}-{count}")
473            .expect("writing to String should not fail");
474    } else {
475        write!(result, "O{year:04}{month:02}{day:02}{hour:02}{minute:02}{second:02}{trader:03}{strategy:03}{count}")
476            .expect("writing to String should not fail");
477    }
478
479    result
480}
481
482fn pack_o_tags(id: &str) -> Option<u128> {
483    let mut parts = id.split('-');
484    if parts.next()? != "O" {
485        return None;
486    }
487
488    let date = parts.next()?.as_bytes();
489    let time = parts.next()?.as_bytes();
490    let trader = parts.next()?;
491    let strategy = parts.next()?;
492    let count = parts.next()?;
493    if parts.next().is_some() || date.len() != 8 || time.len() != 6 {
494        return None;
495    }
496
497    let epoch = civil_to_epoch(
498        parse_digits(&date[..4])?,
499        parse_digits(&date[4..6])?,
500        parse_digits(&date[6..])?,
501        parse_digits(&time[..2])?,
502        parse_digits(&time[2..4])?,
503        parse_digits(&time[4..])?,
504    )?;
505    let seconds = u32::try_from(epoch - O_FORMAT_EPOCH).ok()?;
506    let count = count.parse::<u32>().ok()?;
507    if count > O_TAGS_COUNT_MAX {
508        return None;
509    }
510
511    for swapped in [false, true] {
512        let (tag, numeric) = if swapped {
513            (strategy, trader)
514        } else {
515            (trader, strategy)
516        };
517
518        let Some(tag) = pack_tag(tag) else {
519            continue;
520        };
521
522        let Ok(numeric) = numeric.parse::<u32>() else {
523            continue;
524        };
525
526        if numeric > 1023 {
527            continue;
528        }
529
530        let packed = ((seconds as u128) << 45)
531            | ((swapped as u128) << 44)
532            | ((tag as u128) << 32)
533            | ((numeric as u128) << O_TAGS_COUNT_BITS)
534            | count as u128;
535
536        if unpack_o_tags(packed).ok()?.as_str() == id {
537            return Some(packed);
538        }
539    }
540
541    None
542}
543
544fn unpack_o_tags(packed: u128) -> anyhow::Result<String> {
545    anyhow::ensure!(
546        packed >> 77 == 0,
547        "tagged O-format payload exceeds its bit budget"
548    );
549    let count = (packed & O_TAGS_COUNT_MAX as u128) as u32;
550    let numeric = ((packed >> O_TAGS_COUNT_BITS) & 0x3FF) as u32;
551    let tag = unpack_tag(((packed >> 32) & 0xFFF) as u32)?;
552    let swapped = ((packed >> 44) & 1) != 0;
553    let (year, month, day, hour, minute, second) =
554        epoch_to_civil((packed >> 45) as i64 + O_FORMAT_EPOCH)
555            .context("invalid tagged O-format timestamp")?;
556    let mut result = String::with_capacity(MAX_CLIENT_ORDER_ID_LEN);
557    write!(
558        result,
559        "O-{year:04}{month:02}{day:02}-{hour:02}{minute:02}{second:02}-"
560    )
561    .expect("writing to String should not fail");
562
563    if swapped {
564        write!(result, "{numeric:03}-{tag}-{count}").expect("writing to String should not fail");
565    } else {
566        write!(result, "{tag}-{numeric:03}-{count}").expect("writing to String should not fail");
567    }
568
569    Ok(result)
570}
571
572fn pack_tag(tag: &str) -> Option<u32> {
573    if !(1..=2).contains(&tag.len()) {
574        return None;
575    }
576
577    let mut value = 0;
578
579    for byte in tag.bytes() {
580        let digit = *BASE62_DECODE.get(byte as usize)?;
581        if digit == 0xFF {
582            return None;
583        }
584
585        value = value * 62 + u32::from(digit);
586    }
587
588    match tag.len() {
589        1 => Some(value + 1),
590        2 => Some(value + 63),
591        _ => None,
592    }
593}
594
595fn unpack_tag(value: u32) -> anyhow::Result<String> {
596    anyhow::ensure!((1..=3906).contains(&value), "invalid tagged O-format tag");
597    let mut tag = String::with_capacity(2);
598
599    if value <= 62 {
600        tag.push(BASE62_CHARS[(value - 1) as usize] as char);
601    } else {
602        let value = value - 63;
603        tag.push(BASE62_CHARS[(value / 62) as usize] as char);
604        tag.push(BASE62_CHARS[(value % 62) as usize] as char);
605    }
606
607    Ok(tag)
608}
609
610fn parse_uuid_hex(id_str: &str) -> Option<(u128, bool)> {
611    let b = id_str.as_bytes();
612
613    if b.len() == 36 && b[8] == b'-' {
614        // UUID with hyphens: 8-4-4-4-12
615        if b[13] != b'-' || b[18] != b'-' || b[23] != b'-' {
616            return None;
617        }
618        let mut value: u128 = 0;
619
620        for &byte in b {
621            if byte == b'-' {
622                continue;
623            }
624            let nibble = hex_digit(byte)?;
625            value = (value << 4) | nibble as u128;
626        }
627        Some((value, true))
628    } else if b.len() == 32 {
629        let mut value: u128 = 0;
630
631        for &byte in b {
632            let nibble = hex_digit(byte)?;
633            value = (value << 4) | nibble as u128;
634        }
635        Some((value, false))
636    } else {
637        None
638    }
639}
640
641fn format_uuid(value: u128, has_hyphens: bool) -> String {
642    const HEX: &[u8; 16] = b"0123456789abcdef";
643    let bytes = value.to_be_bytes();
644
645    if has_hyphens {
646        let mut buf = [0u8; 36];
647        let mut pos = 0;
648
649        for (i, &b) in bytes.iter().enumerate() {
650            if i == 4 || i == 6 || i == 8 || i == 10 {
651                buf[pos] = b'-';
652                pos += 1;
653            }
654            buf[pos] = HEX[(b >> 4) as usize];
655            buf[pos + 1] = HEX[(b & 0x0F) as usize];
656            pos += 2;
657        }
658        std::str::from_utf8(&buf)
659            .expect("hex is valid UTF-8")
660            .to_string()
661    } else {
662        let mut buf = [0u8; 32];
663        for (i, &b) in bytes.iter().enumerate() {
664            buf[i * 2] = HEX[(b >> 4) as usize];
665            buf[i * 2 + 1] = HEX[(b & 0x0F) as usize];
666        }
667        std::str::from_utf8(&buf)
668            .expect("hex is valid UTF-8")
669            .to_string()
670    }
671}
672
673fn hex_digit(byte: u8) -> Option<u8> {
674    match byte {
675        b'0'..=b'9' => Some(byte - b'0'),
676        b'a'..=b'f' => Some(byte - b'a' + 10),
677        b'A'..=b'F' => Some(byte - b'A' + 10),
678        _ => None,
679    }
680}
681
682fn memchr_byte(needle: u8, haystack: &[u8]) -> Option<usize> {
683    haystack.iter().position(|&b| b == needle)
684}
685
686/// Converts civil date/time to Unix timestamp (seconds since 1970-01-01).
687fn civil_to_epoch(year: u32, month: u32, day: u32, hour: u32, min: u32, sec: u32) -> Option<i64> {
688    if !(1..=12).contains(&month) || !(1..=31).contains(&day) || hour > 23 || min > 59 || sec > 59 {
689        return None;
690    }
691    // Days from civil date using the algorithm from Howard Hinnant
692    let y = if month <= 2 {
693        year as i64 - 1
694    } else {
695        year as i64
696    };
697    let era = y.div_euclid(400);
698    let yoe = y.rem_euclid(400) as u64;
699    let m = if month > 2 { month - 3 } else { month + 9 } as u64;
700    let doy = (153 * m + 2) / 5 + day as u64 - 1;
701    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
702    let days = era * 146097 + doe as i64 - 719468;
703    Some(days * 86400 + hour as i64 * 3600 + min as i64 * 60 + sec as i64)
704}
705
706/// Converts Unix timestamp to civil date/time components.
707fn epoch_to_civil(timestamp: i64) -> Option<(u32, u32, u32, u32, u32, u32)> {
708    if timestamp < 0 {
709        return None;
710    }
711    let secs_of_day = (timestamp % 86400) as u32;
712    let days = timestamp / 86400;
713
714    let hour = secs_of_day / 3600;
715    let minute = (secs_of_day % 3600) / 60;
716    let second = secs_of_day % 60;
717
718    // Civil date from day count using Howard Hinnant's algorithm
719    let z = days + 719468;
720    let era = z.div_euclid(146097);
721    let doe = z.rem_euclid(146097) as u64;
722    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
723    let y = yoe as i64 + era * 400;
724    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
725    let mp = (5 * doy + 2) / 153;
726    let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
727    let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
728    let year = if month <= 2 { y + 1 } else { y } as u32;
729
730    Some((year, month, day, hour, minute, second))
731}
732
733#[cfg(test)]
734mod tests {
735    use std::hint::black_box;
736
737    use rstest::rstest;
738
739    use super::{super::consts::BINANCE_NAUTILUS_SPOT_BROKER_ID, *};
740
741    const TEST_BROKER_ID: &str = BINANCE_NAUTILUS_SPOT_BROKER_ID;
742
743    #[rstest]
744    #[case("O-20260922-160119-V2-000-8")]
745    #[case("O-20260922-200130-V2-001-24")]
746    #[case("O-20260923-000138-V2-001-1")]
747    #[case("O-20260923-000138-V2-001-4194303")]
748    #[case("O-20260923-000138-001-aZ-42")]
749    fn test_tagged_id_preserves_exact_identity(#[case] original: &str) {
750        let id = ClientOrderId::from(original);
751        let encoded = encode_broker_id(&id, TEST_BROKER_ID);
752        assert_eq!(encoded.len(), 24);
753        assert!(encoded.starts_with("x-TD67BGP9A"));
754        assert_eq!(
755            decode_client_order_id(&encoded, TEST_BROKER_ID).unwrap(),
756            id
757        );
758
759        // Historical custom IDs matching this format were R-wrapped
760        let custom = ClientOrderId::from(encoded.as_str());
761        let wrapped = encode_broker_id(&custom, TEST_BROKER_ID);
762        assert_eq!(wrapped, format!("x-TD67BGP9-R{encoded}"));
763        assert_eq!(
764            decode_client_order_id(&wrapped, TEST_BROKER_ID).unwrap(),
765            custom
766        );
767    }
768
769    #[rstest]
770    #[case("O-20260923-000138-V2-001-4194304")]
771    #[case("O-20260923-000138-LONG-001-1")]
772    #[case("O-20260923-000138-V2-001-01")]
773    #[case("O-20260230-000138-V2-001-1")]
774    fn test_unsupported_tagged_id_remains_unchanged(#[case] original: &str) {
775        assert_eq!(
776            encode_broker_id(&ClientOrderId::from(original), TEST_BROKER_ID),
777            original
778        );
779    }
780
781    #[rstest]
782    fn test_historical_raw_id_does_not_enter_short_namespace() {
783        let original = "x-TD67BGP9A00000000000000";
784        assert_eq!(original.len(), 25);
785        assert_eq!(
786            encode_broker_id(&ClientOrderId::from(original), TEST_BROKER_ID),
787            original
788        );
789        assert_eq!(
790            decode_client_order_id(original, TEST_BROKER_ID)
791                .unwrap()
792                .as_str(),
793            original
794        );
795    }
796
797    #[rstest]
798    #[case("O-20260305-120000-001-001-100", "x-TD67BGP9-T047IBdyLevrb2")]
799    #[case("O20260305120000001001100", "x-TD67BGP9-t047IBdyLevrb2")]
800    #[case(
801        "550e8400-e29b-41d4-a716-446655440000",
802        "x-TD67BGP9-U2aUyqjCzEIiEcYMKj7TZtw"
803    )]
804    #[case(
805        "550e8400e29b41d4a716446655440000",
806        "x-TD67BGP9-u2aUyqjCzEIiEcYMKj7TZtw"
807    )]
808    #[case("my-order-123", "x-TD67BGP9-Rmy-order-123")]
809    fn test_historical_wire_vectors(#[case] original: &str, #[case] encoded: &str) {
810        let id = ClientOrderId::from(original);
811        assert_eq!(encode_broker_id(&id, TEST_BROKER_ID), encoded);
812        assert_eq!(decode_client_order_id(encoded, TEST_BROKER_ID).unwrap(), id);
813    }
814
815    #[rstest]
816    fn test_base62_chunked_encoding_matches_digit_reference() {
817        let mut state = 0x1234_5678_90ab_cdef_2345_6789_abcd_ef01u128;
818
819        for value in [0, 1, 61, 62, 62u128.pow(10) - 1, 62u128.pow(10), u128::MAX]
820            .into_iter()
821            .chain((0..10_000).map(|_| {
822                state ^= state << 13;
823                state ^= state >> 7;
824                state ^= state << 17;
825                state
826            }))
827        {
828            let mut expected = [b'0'; 22];
829            let mut remaining = value;
830
831            for byte in expected.iter_mut().rev() {
832                *byte = BASE62_CHARS[(remaining % 62) as usize];
833                remaining /= 62;
834            }
835
836            assert_eq!(encode_base62::<22>(value), expected);
837            assert_eq!(encode_base62::<13>(value).as_slice(), &expected[9..]);
838            assert_eq!(decode_base62(&expected), Some(value));
839        }
840    }
841
842    #[rstest]
843    #[case("O-20200101-000000-0-000-0")]
844    #[case("O-21560207-062815-zz-1023-4194303")]
845    #[case("O-20260922-160119-000-00-1")]
846    fn test_tagged_packing_boundaries(#[case] original: &str) {
847        let packed = pack_o_tags(original).unwrap();
848        assert_eq!(unpack_o_tags(packed).unwrap(), original);
849    }
850
851    #[rstest]
852    fn test_base62_roundtrip_zero() {
853        let encoded = encode_base62::<13>(0);
854        let decoded = decode_base62(&encoded);
855        assert_eq!(decoded, Some(0));
856    }
857
858    #[rstest]
859    fn test_base62_roundtrip_max_72_bit() {
860        let value: u128 = (1u128 << 72) - 1;
861        let encoded = encode_base62::<13>(value);
862        let decoded = decode_base62(&encoded);
863        assert_eq!(decoded, Some(value));
864    }
865
866    #[rstest]
867    fn test_base62_roundtrip_max_128_bit() {
868        let value: u128 = u128::MAX;
869        let encoded = encode_base62::<22>(value);
870        let decoded = decode_base62(&encoded);
871        assert_eq!(decoded, Some(value));
872    }
873
874    #[rstest]
875    #[case("O-20200101-000000-000-000-0")]
876    #[case("O-20200101-000001-001-001-1")]
877    #[case("O-20260131-174827-001-001-1")]
878    #[case("O-20260131-235959-999-999-4095")]
879    #[case("O-20251215-123456-123-456-789")]
880    #[case("O-20260305-120000-001-001-100")]
881    #[case("O-20260305-120000-001-001-99999")]
882    #[case("O-20260305-120000-001-001-1048575")]
883    fn test_roundtrip_o_format_with_hyphens(#[case] id_str: &str) {
884        let coid = ClientOrderId::from(id_str);
885        let encoded = encode_broker_id(&coid, TEST_BROKER_ID);
886
887        assert!(encoded.starts_with("x-TD67BGP9-T"), "got: {encoded}");
888        assert!(encoded.len() <= 36, "len {} > 36: {encoded}", encoded.len());
889
890        let decoded = decode_broker_id(&encoded, TEST_BROKER_ID);
891        assert_eq!(decoded, id_str);
892    }
893
894    #[rstest]
895    #[case("O202001010000000000000")]
896    #[case("O202601311748270010011")]
897    #[case("O202601312359599999994095")]
898    fn test_roundtrip_o_format_without_hyphens(#[case] id_str: &str) {
899        let coid = ClientOrderId::from(id_str);
900        let encoded = encode_broker_id(&coid, TEST_BROKER_ID);
901
902        assert!(encoded.starts_with("x-TD67BGP9-t"), "got: {encoded}");
903        assert!(encoded.len() <= 36);
904
905        let decoded = decode_broker_id(&encoded, TEST_BROKER_ID);
906        assert_eq!(decoded, id_str);
907    }
908
909    #[rstest]
910    fn test_roundtrip_uuid_with_hyphens() {
911        let id_str = "550e8400-e29b-41d4-a716-446655440000";
912        let coid = ClientOrderId::from(id_str);
913        let encoded = encode_broker_id(&coid, TEST_BROKER_ID);
914
915        assert!(encoded.starts_with("x-TD67BGP9-U"), "got: {encoded}");
916        assert!(encoded.len() <= 36, "len {} > 36: {encoded}", encoded.len());
917
918        let decoded = decode_broker_id(&encoded, TEST_BROKER_ID);
919        assert_eq!(decoded, id_str);
920    }
921
922    #[rstest]
923    fn test_roundtrip_uuid_without_hyphens() {
924        let id_str = "550e8400e29b41d4a716446655440000";
925        let coid = ClientOrderId::from(id_str);
926        let encoded = encode_broker_id(&coid, TEST_BROKER_ID);
927
928        assert!(encoded.starts_with("x-TD67BGP9-u"), "got: {encoded}");
929        assert!(encoded.len() <= 36);
930
931        let decoded = decode_broker_id(&encoded, TEST_BROKER_ID);
932        assert_eq!(decoded, id_str);
933    }
934
935    #[rstest]
936    fn test_roundtrip_uuid_all_zeros() {
937        let id_str = "00000000-0000-0000-0000-000000000000";
938        let coid = ClientOrderId::from(id_str);
939
940        let decoded = decode_broker_id(&encode_broker_id(&coid, TEST_BROKER_ID), TEST_BROKER_ID);
941        assert_eq!(decoded, id_str);
942    }
943
944    #[rstest]
945    fn test_roundtrip_uuid_all_f() {
946        let id_str = "ffffffff-ffff-ffff-ffff-ffffffffffff";
947        let coid = ClientOrderId::from(id_str);
948
949        let decoded = decode_broker_id(&encode_broker_id(&coid, TEST_BROKER_ID), TEST_BROKER_ID);
950        assert_eq!(decoded, id_str);
951    }
952
953    #[rstest]
954    fn test_raw_passthrough_short_id() {
955        let id_str = "my-order-123";
956        let coid = ClientOrderId::from(id_str);
957        let encoded = encode_broker_id(&coid, TEST_BROKER_ID);
958
959        assert!(encoded.starts_with("x-TD67BGP9-R"), "got: {encoded}");
960        assert!(encoded.len() <= 36);
961
962        let decoded = decode_broker_id(&encoded, TEST_BROKER_ID);
963        assert_eq!(decoded, id_str);
964    }
965
966    #[rstest]
967    fn test_raw_passthrough_max_length() {
968        let id_str = "abcdefghijklmnopqrstuvwx"; // 24 chars = max raw budget
969        let coid = ClientOrderId::from(id_str);
970        let encoded = encode_broker_id(&coid, TEST_BROKER_ID);
971
972        assert_eq!(encoded.len(), 36);
973        assert!(encoded.starts_with("x-TD67BGP9-R"));
974
975        let decoded = decode_broker_id(&encoded, TEST_BROKER_ID);
976        assert_eq!(decoded, id_str);
977    }
978
979    #[rstest]
980    fn test_decode_non_prefixed_returns_as_is() {
981        let raw = "O-20260131-174827-001-001-1";
982        assert_eq!(decode_broker_id(raw, TEST_BROKER_ID), raw);
983    }
984
985    #[rstest]
986    fn test_decode_different_prefix_returns_as_is() {
987        let raw = "x-OTHERBROKER-T0000000000000";
988        assert_eq!(decode_broker_id(raw, TEST_BROKER_ID), raw);
989    }
990
991    #[rstest]
992    #[case::empty("", "invalid Binance client order ID ''")]
993    #[case::whitespace("   ", "invalid Binance client order ID '   '")]
994    #[case::non_ascii("client-é", "invalid Binance client order ID 'client-é'")]
995    #[case::missing_signal("x-TD67BGP9-", "missing broker client order ID signal")]
996    #[case::missing_raw_payload("x-TD67BGP9-R", "missing raw broker client order ID payload")]
997    #[case::invalid_o_payload(
998        "x-TD67BGP9-T000000000000!",
999        "invalid O-format broker client order ID"
1000    )]
1001    #[case::unknown_signal(
1002        "x-TD67BGP9-Xlegacy-order",
1003        "unknown broker client order ID signal byte 'X'"
1004    )]
1005    fn test_decode_client_order_id_rejects_invalid_input(
1006        #[case] encoded: &str,
1007        #[case] expected: &str,
1008    ) {
1009        let error = decode_client_order_id(encoded, TEST_BROKER_ID).unwrap_err();
1010
1011        assert_eq!(error.to_string(), expected);
1012    }
1013
1014    #[rstest]
1015    fn test_decode_client_order_id_preserves_valid_prefixed_id() {
1016        let original = ClientOrderId::from("O-20260305-120000-001-001-100");
1017        let encoded = encode_broker_id(&original, TEST_BROKER_ID);
1018
1019        let decoded = decode_client_order_id(&encoded, TEST_BROKER_ID).unwrap();
1020
1021        assert_eq!(decoded, original);
1022    }
1023
1024    #[rstest]
1025    fn test_decode_client_order_id_preserves_valid_legacy_id() {
1026        let decoded = decode_client_order_id("legacy-order-1", TEST_BROKER_ID).unwrap();
1027
1028        assert_eq!(decoded, ClientOrderId::from("legacy-order-1"));
1029    }
1030
1031    #[rstest]
1032    fn test_o_format_trader_overflow_sends_without_prefix() {
1033        // trader=1024 exceeds 10-bit limit, and hyphenated O-format (28 chars)
1034        // exceeds raw budget too, so the ID is sent without prefix
1035        let id_str = "O-20260131-174827-1024-001-1";
1036        let coid = ClientOrderId::from(id_str);
1037        let encoded = encode_broker_id(&coid, TEST_BROKER_ID);
1038        assert_eq!(encoded, id_str);
1039    }
1040
1041    #[rstest]
1042    fn test_o_format_count_overflow_sends_without_prefix() {
1043        // count=1048576 exceeds 20-bit limit, and hyphenated O-format (32 chars)
1044        // exceeds raw budget too, so the ID is sent without prefix
1045        let id_str = "O-20260131-174827-001-001-1048576";
1046        let coid = ClientOrderId::from(id_str);
1047        let encoded = encode_broker_id(&coid, TEST_BROKER_ID);
1048        assert_eq!(encoded, id_str);
1049    }
1050
1051    #[rstest]
1052    fn test_too_long_id_sends_without_prefix() {
1053        let id_str = "this-is-a-very-long-order-id-that-exceeds-everything";
1054        let coid = ClientOrderId::from(id_str);
1055        let encoded = encode_broker_id(&coid, TEST_BROKER_ID);
1056
1057        assert_eq!(encoded, id_str);
1058    }
1059
1060    #[rstest]
1061    fn test_o_format_always_25_chars() {
1062        let test_cases = [
1063            "O-20200101-000000-000-000-0",
1064            "O-20260131-235959-999-999-4095",
1065            "O-20260305-120000-001-001-1048575",
1066        ];
1067
1068        for id_str in test_cases {
1069            let coid = ClientOrderId::from(id_str);
1070            let encoded = encode_broker_id(&coid, TEST_BROKER_ID);
1071            assert_eq!(
1072                encoded.len(),
1073                25,
1074                "got {} for {id_str}: {encoded}",
1075                encoded.len()
1076            );
1077        }
1078    }
1079
1080    #[rstest]
1081    fn test_uuid_always_34_chars() {
1082        let id_str = "550e8400-e29b-41d4-a716-446655440000";
1083        let coid = ClientOrderId::from(id_str);
1084        let encoded = encode_broker_id(&coid, TEST_BROKER_ID);
1085        assert_eq!(encoded.len(), 34, "got {}", encoded.len());
1086    }
1087
1088    #[rstest]
1089    fn test_broker_prefix_format() {
1090        let encoded = encode_broker_id(&ClientOrderId::from("test"), TEST_BROKER_ID);
1091        assert_eq!(encoded, "x-TD67BGP9-Rtest");
1092    }
1093
1094    #[rstest]
1095    fn test_encoded_chars_are_binance_valid() {
1096        let valid = |c: char| {
1097            c.is_ascii_alphanumeric() || c == '.' || c == ':' || c == '/' || c == '_' || c == '-'
1098        };
1099
1100        let ids = [
1101            "O-20260131-174827-001-001-1",
1102            "550e8400-e29b-41d4-a716-446655440000",
1103            "short-id",
1104        ];
1105
1106        for id_str in ids {
1107            let coid = ClientOrderId::from(id_str);
1108            let encoded = encode_broker_id(&coid, TEST_BROKER_ID);
1109            assert!(
1110                encoded.chars().all(valid),
1111                "'{encoded}' contains invalid Binance characters"
1112            );
1113        }
1114    }
1115
1116    #[rstest]
1117    fn test_civil_time_roundtrip() {
1118        let epoch = civil_to_epoch(2020, 1, 1, 0, 0, 0).unwrap();
1119        assert_eq!(epoch, O_FORMAT_EPOCH);
1120        let (y, m, d, h, mi, s) = epoch_to_civil(epoch).unwrap();
1121        assert_eq!((y, m, d, h, mi, s), (2020, 1, 1, 0, 0, 0));
1122    }
1123
1124    #[rstest]
1125    #[case("O-20260305-120000-001-001-1")]
1126    #[case("O-20260131-174827-001-001-1")]
1127    #[case("O-20260305-120000-001-001-1048575")]
1128    #[case("550e8400-e29b-41d4-a716-446655440000")]
1129    #[case("550e8400e29b41d4a716446655440000")]
1130    #[case("my-order-42")]
1131    #[case("short")]
1132    fn test_end_to_end_submit_and_receive(#[case] original_id: &str) {
1133        let broker_id = TEST_BROKER_ID;
1134        let client_order_id = ClientOrderId::from(original_id);
1135
1136        // Simulate submit: encode the client order ID for Binance
1137        let encoded = encode_broker_id(&client_order_id, broker_id);
1138        assert!(encoded.len() <= 36, "encoded len {} > 36", encoded.len());
1139
1140        // Simulate receive: Binance echoes the encoded ID back in a response
1141        let decoded = decode_broker_id(&encoded, broker_id);
1142
1143        // Must recover the original ID exactly
1144        assert_eq!(decoded, original_id);
1145        assert_eq!(ClientOrderId::new(decoded), client_order_id);
1146    }
1147
1148    #[rstest]
1149    fn bench_encode_decode_timing() {
1150        let o_coid = ClientOrderId::from("O-20260305-120000-001-001-100");
1151        let uuid_coid = ClientOrderId::from("550e8400-e29b-41d4-a716-446655440000");
1152        let raw_coid = ClientOrderId::from("my-order-123");
1153
1154        let iterations = 100_000;
1155
1156        let start = std::time::Instant::now();
1157
1158        for _ in 0..iterations {
1159            black_box(encode_broker_id(black_box(&o_coid), TEST_BROKER_ID));
1160        }
1161        let encode_o = start.elapsed();
1162
1163        let o_encoded = encode_broker_id(&o_coid, TEST_BROKER_ID);
1164        let start = std::time::Instant::now();
1165
1166        for _ in 0..iterations {
1167            black_box(decode_broker_id(black_box(&o_encoded), TEST_BROKER_ID));
1168        }
1169        let decode_o = start.elapsed();
1170
1171        let start = std::time::Instant::now();
1172
1173        for _ in 0..iterations {
1174            black_box(encode_broker_id(black_box(&uuid_coid), TEST_BROKER_ID));
1175        }
1176        let encode_uuid = start.elapsed();
1177
1178        let uuid_encoded = encode_broker_id(&uuid_coid, TEST_BROKER_ID);
1179        let start = std::time::Instant::now();
1180
1181        for _ in 0..iterations {
1182            black_box(decode_broker_id(black_box(&uuid_encoded), TEST_BROKER_ID));
1183        }
1184        let decode_uuid = start.elapsed();
1185
1186        let start = std::time::Instant::now();
1187
1188        for _ in 0..iterations {
1189            black_box(encode_broker_id(black_box(&raw_coid), TEST_BROKER_ID));
1190        }
1191        let encode_raw = start.elapsed();
1192
1193        let raw_encoded = encode_broker_id(&raw_coid, TEST_BROKER_ID);
1194        let start = std::time::Instant::now();
1195
1196        for _ in 0..iterations {
1197            black_box(decode_broker_id(black_box(&raw_encoded), TEST_BROKER_ID));
1198        }
1199        let decode_raw = start.elapsed();
1200
1201        let passthrough = "O-20260305-120000-001-001-100";
1202        let start = std::time::Instant::now();
1203
1204        for _ in 0..iterations {
1205            black_box(decode_broker_id(black_box(passthrough), TEST_BROKER_ID));
1206        }
1207        let decode_pass = start.elapsed();
1208
1209        println!("\n--- Broker ID Encoder Performance ({iterations} iterations) ---");
1210        println!(
1211            "encode O-format:     {:>8.1} ns/op",
1212            encode_o.as_nanos() as f64 / iterations as f64
1213        );
1214        println!(
1215            "decode O-format:     {:>8.1} ns/op",
1216            decode_o.as_nanos() as f64 / iterations as f64
1217        );
1218        println!(
1219            "encode UUID:         {:>8.1} ns/op",
1220            encode_uuid.as_nanos() as f64 / iterations as f64
1221        );
1222        println!(
1223            "decode UUID:         {:>8.1} ns/op",
1224            decode_uuid.as_nanos() as f64 / iterations as f64
1225        );
1226        println!(
1227            "encode raw:          {:>8.1} ns/op",
1228            encode_raw.as_nanos() as f64 / iterations as f64
1229        );
1230        println!(
1231            "decode raw:          {:>8.1} ns/op",
1232            decode_raw.as_nanos() as f64 / iterations as f64
1233        );
1234        println!(
1235            "decode passthrough:  {:>8.1} ns/op",
1236            decode_pass.as_nanos() as f64 / iterations as f64
1237        );
1238    }
1239}