Skip to content

Commit 826aafb

Browse files
chore(trace): nth_back (#104)
1 parent bc695c3 commit 826aafb

File tree

1 file changed

+16
-14
lines changed

1 file changed

+16
-14
lines changed

packages/utils/src/trace/trace.cairo

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -41,25 +41,13 @@ pub impl TraceImpl of TraceTrait {
4141
/// This will return the last inserted checkpoint that maintains the structure's
4242
/// invariant of non-decreasing keys.
4343
fn latest(self: StoragePath<Trace>) -> Result<(u64, u128), TraceErrors> {
44-
let checkpoints = self.checkpoints;
45-
let len = checkpoints.len();
46-
if len == 0 {
47-
return Result::Err(TraceErrors::EMPTY_TRACE);
48-
}
49-
let checkpoint = checkpoints[len - 1].read();
50-
Result::Ok(checkpoint.into())
44+
self._nth_back(0).map_err(|_e| TraceErrors::EMPTY_TRACE)
5145
}
5246

5347
/// Retrieves the penultimate checkpoint from the trace structure.
5448
/// Penultimate checkpoint is the second last checkpoint in the trace.
5549
fn penultimate(self: StoragePath<Trace>) -> Result<(u64, u128), TraceErrors> {
56-
let checkpoints = self.checkpoints;
57-
let len = checkpoints.len();
58-
if len <= 1 {
59-
return Result::Err(TraceErrors::PENULTIMATE_NOT_EXIST);
60-
}
61-
let checkpoint = checkpoints[len - 2].read();
62-
Result::Ok(checkpoint.into())
50+
self._nth_back(1).map_err(|_e| TraceErrors::PENULTIMATE_NOT_EXIST)
6351
}
6452

6553
/// Returns the total number of checkpoints.
@@ -158,3 +146,17 @@ pub impl MutableTraceImpl of MutableTraceTrait {
158146
self.as_non_mut().is_empty()
159147
}
160148
}
149+
150+
#[generate_trait]
151+
impl TraceHelperImpl of TraceHelperTrait {
152+
/// Returns the `n`th element from the end of the trace.
153+
fn _nth_back(self: StoragePath<Trace>, n: u64) -> Result<(u64, u128), TraceErrors> {
154+
let checkpoints = self.checkpoints;
155+
let len = checkpoints.len();
156+
if len <= n {
157+
return Result::Err(TraceErrors::INDEX_OUT_OF_BOUNDS);
158+
}
159+
let checkpoint = checkpoints[len - n - 1].read();
160+
Result::Ok(checkpoint.into())
161+
}
162+
}

0 commit comments

Comments
 (0)