Skip to content

Sorting of Abstract Data Tree

Jerry.Wang edited this page Apr 28, 2021 · 1 revision

The Problem

The rholang code is internally represented as ADT(Abstract Data Tree). And it has to be total-order. Scala edition implements Sortable interface for all abstract date types.

The scala edition rchain/models/rholang/sorter creates a score-tree for ADT, and then sorting ADTs by comparing score-trees in depth-first order. The score-tree gets a similar size as ADT. If the rholang code is long and complicated, the ADT gets big, so does score tree. But in real world, we don't need traverse the entire tree to determine their order. In most cases, the order can be determined with just a few comparison.

Sorting is in the frequent execution path of every reduction. Building an entire score-tree for ADT is a big waste on CPU and memory.

The Solution

In Rust edition model/src/ordering source code, two traits are defined there.

trait Scorable<'a> {
    fn score_tree_iter(self) -> ScoreTreeIter<'a>;
}
pub trait Sortable{
    fn sort(&mut self);
}

Type implementing Scorable trait will build the score-tree. Rather than building the entire score tree at once, it returns a ScoreTreeIter whose next() function returns the next node in score tree. The node of score tree is built when it is required.

Type implementing Sortable trait sorts its internal data members by leverage of ScoreTreeIter. To compare two score trees, compare the next nodes returned by either tree. In real world, it is usually very soon to get an non-equal comparison result, then the order is determined and no need to complete traverse. Thus, a lot of CPU and memory are saved.

Clone this wiki locally