Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Module 0x7::order_id_generation

use 0x1::transaction_context;
use 0x5::order_book_types;

Function next_order_id

public fun next_order_id(): order_book_types::OrderId
Implementation
public fun next_order_id(): OrderId {
    // reverse bits to make order ids random, so indices on top of them are shuffled.
    new_order_id_type(reverse_bits(
        transaction_context::monotonically_increasing_counter()
    ))
}

Function reverse_bits

Reverse the bits in a u128 value using divide and conquer approach This is more efficient than the bit-by-bit approach, reducing from O(n) to O(log n)

fun reverse_bits(value: u128): u128
Implementation
fun reverse_bits(value: u128): u128 {
    let v = value;

    // Swap odd and even bits
    v =
        ((v & 0x55555555555555555555555555555555) << 1)
            | ((v >> 1) & 0x55555555555555555555555555555555);

    // Swap consecutive pairs
    v =
        ((v & 0x33333333333333333333333333333333) << 2)
            | ((v >> 2) & 0x33333333333333333333333333333333);

    // Swap nibbles
    v =
        ((v & 0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f) << 4)
            | ((v >> 4) & 0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f);

    // Swap bytes
    v =
        ((v & 0x00ff00ff00ff00ff00ff00ff00ff00ff) << 8)
            | ((v >> 8) & 0x00ff00ff00ff00ff00ff00ff00ff00ff);

    // Swap 2-byte chunks
    v =
        ((v & 0x0000ffff0000ffff0000ffff0000ffff) << 16)
            | ((v >> 16) & 0x0000ffff0000ffff0000ffff0000ffff);

    // Swap 4-byte chunks
    v =
        ((v & 0x00000000ffffffff00000000ffffffff) << 32)
            | ((v >> 32) & 0x00000000ffffffff00000000ffffffff);

    // Swap 8-byte chunks
    v = (v << 64) | (v >> 64);

    v
}