Skip to main content

oa/core/
callback.rs

1//! Callback trait and iterator context for training and inference sessions.
2//!
3//! Port provenance: `oa/core/callback.h`, `oa/core/iterator.h`.
4//!
5//! [`Callback`] is the Keras-style hook interface used by `Training` and
6//! any future `ItBatch` / `ItInference` session types. All three methods have
7//! default no-op implementations so callers only override what they need.
8//!
9//! [`IteratorContext`] is a thin object-safe view of the current iterator
10//! state that callbacks receive. Decoupled from the concrete session type so
11//! that callback code does not need to name it.
12//!
13//! # Usage
14//!
15//! ```rust,ignore
16//! use oa::{Callback, IteratorContext};
17//!
18//! struct PrintProgress;
19//!
20//! impl Callback for PrintProgress {
21//!     fn on_step(&mut self, ctx: &dyn IteratorContext) {
22//!         if ctx.index() % 100 == 0 {
23//!             println!("step {}/{}", ctx.index(), ctx.total().unwrap_or(0));
24//!         }
25//!     }
26//! }
27//! ```
28
29// ─── IteratorContext ──────────────────────────────────────────────────────────
30
31/// Object-safe view of an iterator's current state, passed to every [`Callback`]
32/// hook.
33///
34/// The concrete iterator (e.g. `Training`) implements this privately; the
35/// callback only needs the interface.
36pub trait IteratorContext {
37	/// Step index, zero-based. Matches the C++ `Iterator::index()`.
38	fn index(&self) -> i64;
39
40	/// `true` when the iterator has finished all steps.
41	fn is_done(&self) -> bool;
42
43	/// Total planned steps, if known. `None` for open-ended iterators.
44	fn total(&self) -> Option<i64>;
45}
46
47// ─── Callback ─────────────────────────────────────────────────────────────────
48
49/// Keras-style hook interface for OA iterator sessions.
50///
51/// Attach one or more callbacks to a session via its `add_callback` method.
52/// All hooks receive a `&dyn IteratorContext` so callbacks stay decoupled from
53/// the concrete session type.
54///
55/// # Mapping from C++
56///
57/// | C++                       | Rust                       |
58/// |---------------------------|----------------------------|
59/// | `onBegin(Iterator&)`      | `on_begin(&mut self, ctx)` |
60/// | `onStep(Iterator&)`       | `on_step(&mut self, ctx)`  |
61/// | `onEnd(Iterator&)`        | `on_end(&mut self, ctx)`   |
62///
63/// C++ used virtual inheritance; Rust uses dynamic dispatch through `Box<dyn Callback>`.
64/// The C++ move-constructor convention maps to Rust's normal ownership — place
65/// `Box<dyn Callback>` values in a `Vec` rather than raw pointers.
66pub trait Callback: Send {
67	/// Fired once before the first step.
68	fn on_begin(&mut self, _ctx: &dyn IteratorContext) {}
69
70	/// Fired after each step. The iterator has already advanced to `ctx.index()`.
71	fn on_step(&mut self, _ctx: &dyn IteratorContext) {}
72
73	/// Fired once after the last step or when the session is explicitly finished.
74	fn on_end(&mut self, _ctx: &dyn IteratorContext) {}
75}
76
77// ─── CallbackSet ─────────────────────────────────────────────────────────────
78
79/// Ordered list of [`Callback`] objects attached to a session.
80///
81/// Callbacks fire in insertion order. This mirrors `oa::Iterator::addCallback`
82/// but is an explicit value rather than a virtual base member so the concrete
83/// session type can own it directly.
84pub struct CallbackSet {
85	callbacks: Vec<Box<dyn Callback>>,
86}
87
88impl CallbackSet {
89	/// Create an empty callback set.
90	pub fn new() -> Self {
91		Self {
92			callbacks: Vec::new(),
93		}
94	}
95
96	/// Append a callback. Callbacks fire in insertion order.
97	pub fn add(&mut self, cb: Box<dyn Callback>) {
98		self.callbacks.push(cb);
99	}
100
101	/// Fire `on_begin` on all callbacks in order.
102	pub fn fire_begin(&mut self, ctx: &dyn IteratorContext) {
103		for cb in &mut self.callbacks {
104			cb.on_begin(ctx);
105		}
106	}
107
108	/// Fire `on_step` on all callbacks in order.
109	pub fn fire_step(&mut self, ctx: &dyn IteratorContext) {
110		for cb in &mut self.callbacks {
111			cb.on_step(ctx);
112		}
113	}
114
115	/// Fire `on_end` on all callbacks in order.
116	pub fn fire_end(&mut self, ctx: &dyn IteratorContext) {
117		for cb in &mut self.callbacks {
118			cb.on_end(ctx);
119		}
120	}
121
122	/// Number of registered callbacks.
123	pub fn len(&self) -> usize {
124		self.callbacks.len()
125	}
126
127	/// True when no callbacks are registered.
128	pub fn is_empty(&self) -> bool {
129		self.callbacks.is_empty()
130	}
131}
132
133impl Default for CallbackSet {
134	fn default() -> Self {
135		Self::new()
136	}
137}