threads_table.rs
Overview
This file defines a data structure and associated operations for managing a mapping between account routing keys and thread identifiers, encapsulated in a ThreadsTable. It provides functionality to merge thread tables, list threads, and perform bit-level operations on routing keys. The core concept revolves around the AccountRouting struct, which combines a decentralized application identifier (DAppIdentifier) and an account address (AccountAddress) to serve as a key in the thread table. The ThreadsTable itself is a specialized instance of a generic bitmask table keyed by AccountRouting and indexed by ThreadIdentifier.
Key Components
AccountRouting
pub struct AccountRouting(pub DAppIdentifier, pub AccountAddress);
A composite key type used for routing accounts to threads. It consists of:
DAppIdentifier: Identifies the decentralized application related to the account.AccountAddress: Represents the specific account address.
Traits and Implementations
Clone,Default,Eq,PartialEq,Serialize,Deserialize,Hash: Supports cloning, comparisons, serialization, and hashing.Debug: Custom debug output in the format"DAppIdentifier:AccountAddress".From<(Option<DAppIdentifier>, AccountAddress)>: Allows creating anAccountRoutingfrom an optionalDAppIdentifierand anAccountAddress. Defaults to wrapping the account address as theDAppIdentifierif none is provided.BitAnd: Defines bitwise AND operation forAccountRouting, applied component-wise on theDAppIdentifierandAccountAddress.DirectBitAccess: Provides direct bit-level access to the combined bitmask representation of the routing key:get_bit_value(index): Returns the bit at the given index (first 256 bits correspond toDAppIdentifier, next 256 toAccountAddress).set_bit_value(index, value): Sets the bit at the given index accordingly.
From<AccountRouting> for [[bool; 256]; 2]: Converts the routing key into a two-dimensional boolean array representing the bits of theDAppIdentifierandAccountAddress.
Usage Example
let dapp_id = DAppIdentifier::default();
let account_addr = AccountAddress::default();
let routing = AccountRouting(dapp_id.clone(), account_addr.clone());
// Access bits
let bit = routing.get_bit_value(10);
routing.set_bit_value(10, true);
// Debug output
println!("{:?}", routing);
ThreadsTable
pub type ThreadsTable = crate::bitmask::table::BitmasksTable<AccountRouting, ThreadIdentifier>;
An alias for a bitmask table mapping AccountRouting keys to ThreadIdentifier values.
Methods
merge(&mut self, another_table: &ThreadsTable) -> anyhow::Result<()>Merges another
ThreadsTableinto the current one. It ensures that rows with matching thread identifiers have identical bitmasks and inserts rows from both tables in a combined, ordered manner. The method performs validation usinganyhow::ensure!to verify assumptions about default rows and consistency.Algorithm details:
Both tables' rows are cloned into vectors.
The default rows (empty bitmask and default thread ID) are popped off and validated.
Rows are iterated from the end, comparing thread IDs:
If thread IDs match, bitmasks must be equal; row is inserted once.
If a thread ID exists only in one table, the corresponding row is inserted.
If the merged table differs from the original, it is assigned to
self.Tracing logs changes at the trace level.
list_threads(&self) -> impl Iterator<Item = &'_ ThreadIdentifier>Returns an iterator over unique thread identifiers present in the table.
length(&self) -> usizeReturns the number of rows in the
ThreadsTable.
Usage Example
let mut table1 = ThreadsTable::new();
let mut table2 = ThreadsTable::new();
// Insert rows into table1 and table2...
table1.merge(&table2)?; // Merge tables
for thread in table1.list_threads() {
println!("Thread: {:?}", thread);
}
println!("Number of rows: {}", table1.length());
Implementation Details and Algorithms
Bitmask Representation: The
AccountRoutingstruct uses bit-level representations of its components (DAppIdentifierandAccountAddress), enabling efficient bitmask operations and direct bit access.Merge Algorithm: The
mergemethod is designed to combine two sorted lists of rows fromThreadsTables. It performs a reverse iteration to efficiently merge, handling duplicates and ensuring consistency of bitmasks for matching thread IDs, akin to a merge operation in merge sort algorithms but with additional validation steps.Bitwise AND Operation: Implemented for references to
AccountRouting, enabling component-wise bitwise AND, which is used internally for bitmask computations.Serialization: The file includes serialization and deserialization support via
serde, facilitating persistence and transmission ofThreadsTabledata.
Interactions with Other Components
bitmask::mask::Bitmaskandbitmask::table::BitmasksTable: The core table and mask types underpin theThreadsTable. These provide generic bitmask functionality that is specialized here for account routing and thread identification.types::AccountAddress,DAppIdentifier,ThreadIdentifier: Fundamental types used for keys and values in the table. The file relies on their bit-level operations, serialization, and default values.bitmask::mask::Bitmask::builder(): Used in test code to build bitmasks with meaningful bits, indicating that this file's use of bitmasks depends on building and manipulating these objects.Tracing: The
mergemethod usestracing::trace!to log updates, indicating integration with a logging or telemetry system.
Test Module
The file contains a comprehensive test module verifying serialization, merging behavior, and duplicate handling in ThreadsTable.
Serialization Test: Verifies that a
ThreadsTablecan be serialized to JSON and deserialized back without loss.Merge Test: Constructs two
ThreadsTables with overlapping and distinct rows, merges them, and asserts correct merging behavior.Duplicate Test: Inserts duplicate bitmask rows into a
ThreadsTableand verifies that duplicates exist, ensuring behavior can be inspected.
Helper function add_mask facilitates creating and inserting Bitmask rows into the table for testing.
Mermaid Diagram
classDiagram
class AccountRouting {
+DAppIdentifier
+AccountAddress
+bitand()
+get_bit_value()
+set_bit_value()
}
class ThreadsTable {
+merge()
+list_threads()
+length()
}
AccountRouting <|-- ThreadsTable : uses as key
ThreadsTable ..> ThreadIdentifier : maps to
This diagram shows the relationship where ThreadsTable is a bitmask table keyed by AccountRouting and mapping to ThreadIdentifier. The AccountRouting class provides bitwise and bit-level operations used by the table.