direct_bit_access_operations.rs

Overview

This file provides functionality for direct bit-level access and manipulation on the AccountAddress type. It defines the DirectBitAccess trait, which exposes methods to get and set individual bits by index within a 256-bit address space. This capability is essential for low-level operations where bit-level control is necessary, such as encoding flags or performing bitmask operations on addresses.

The implementation ensures bounds checking for valid bit indices (0 to 255) and panics if an invalid index is accessed, reflecting strict enforcement of address size constraints.

Trait: DirectBitAccess

The DirectBitAccess trait declares two primary methods for bit manipulation:

Methods

get_bit_value(&self, index: usize) -> bool

let bit = account_address.get_bit_value(5);
if bit {
    // bit 5 is set
}

set_bit_value(&mut self, index: usize, value: bool)

account_address.set_bit_value(10, true);

Implementation Details for AccountAddress

Algorithm for Bit Access

  1. Calculate byte index (hi): index / 8

  2. Calculate bit position (lo): index % 8

  3. For getting the bit:

    • Retrieve byte at hi.

    • Shift right by (7 - lo).

    • Mask with 0x1 to isolate the bit.

  4. For setting the bit:

    • Retrieve mutable copy of internal byte array.

    • Use bitwise OR with 1 << (7 - lo) to set the bit.

    • Update the internal array.

Interaction with Other Components

Testing

Mermaid Diagram: Function Flowchart

flowchart TD
A[DirectBitAccess Trait]
A --> B[get_bit_value]
A --> C[set_bit_value]
B --> D[Check index < 256]
D -->|valid| E[Calculate hi = index / 8]
E --> F[Calculate lo = index % 8]
F --> G[Extract bit from byte array]
D -->|invalid| H[panic "index out of bounds"]
C --> I[Assert value == true]
I --> J[Check index < 256]
J -->|valid| K[Calculate hi = index / 8]
K --> L["Calculate lo = 7 - (index % 8)"]
L --> M[Set bit in byte array]
J -->|invalid| N[panic "index out of bounds"]

This flowchart illustrates the decision points and key steps in the get_bit_value and set_bit_value methods of the DirectBitAccess trait implementation for AccountAddress. It highlights index validation, bit position calculation, and bit retrieval or setting processes.