jupyter_protocol/execution_count.rs
1//! Provides utilities for managing execution counts in Jupyter sessions.
2//!
3//! This module defines the `ExecutionCount` type, which represents a monotonically
4//! increasing counter for tracking the number of code executions in a Jupyter session.
5//! This count is not tied to individual cells but represents the overall execution history
6//! of the session, including code run via `execute_request` in terminals.
7//!
8//! # Examples
9//!
10//! ```
11//! use jupyter_protocol::ExecutionCount;
12//!
13//! // Start a new session
14//! let mut count = ExecutionCount::new(1);
15//! assert_eq!(count.value(), 1);
16//!
17//! // After executing some code
18//! count.increment();
19//! assert_eq!(count.value(), 2);
20//!
21//! // Creating from a known execution count
22//! let count_from_usize: ExecutionCount = 3.into();
23//! assert_eq!(count_from_usize.value(), 3);
24//!
25//! // Converting back to usize
26//! let usize_from_count: usize = count.into();
27//! assert_eq!(usize_from_count, 2);
28//! ```
29
30use serde::{Deserialize, Serialize};
31use serde_json::Value;
32
33/// Represents a monotonically increasing counter for tracking the number of code executions
34/// in a Jupyter session. This count is maintained across all executions, including those in
35/// notebook cells and via terminal `execute_request`s.
36#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
37pub struct ExecutionCount(pub usize);
38
39impl ExecutionCount {
40 /// Creates a new `ExecutionCount` with the given count.
41 ///
42 /// # Arguments
43 ///
44 /// * `count` - The initial execution count value.
45 pub fn new(count: usize) -> Self {
46 Self(count)
47 }
48}
49
50impl From<usize> for ExecutionCount {
51 fn from(count: usize) -> Self {
52 Self(count)
53 }
54}
55
56impl From<ExecutionCount> for usize {
57 fn from(count: ExecutionCount) -> Self {
58 count.0
59 }
60}
61
62impl From<ExecutionCount> for Value {
63 fn from(count: ExecutionCount) -> Self {
64 Value::Number(count.0.into())
65 }
66}
67
68impl ExecutionCount {
69 /// Increments the execution count by 1.
70 ///
71 /// Primarily for use by kernel authors.
72 ///
73 /// This should be called after each successful code execution in the session.
74 pub fn increment(&mut self) {
75 self.0 += 1;
76 }
77
78 /// Returns the current value of the execution count.
79 ///
80 /// The current execution count for the session as a `usize`.
81 pub fn value(&self) -> usize {
82 self.0
83 }
84}
85
86impl std::fmt::Display for ExecutionCount {
87 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88 write!(f, "{}", self.0)
89 }
90}