hojicha-core 0.2.2

Core Elm Architecture abstractions for terminal UIs in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
//! Zero-cost Event optimizations with inline storage
//!
//! This module provides performance-optimized event types that minimize allocations
//! and provide zero-cost abstractions for common event patterns.

use crate::event::{KeyEvent, MouseEvent};
use smallvec::SmallVec;
use std::mem;

/// Size threshold for inline message storage (in bytes)
const INLINE_SIZE: usize = 24;

/// Zero-cost event wrapper with inline storage for small messages
#[derive(Debug, Clone)]
pub enum OptimizedEvent<M> {
    /// A keyboard event - stored inline, no allocation
    Key(KeyEvent),
    /// A mouse event - stored inline, no allocation
    Mouse(MouseEvent),
    /// Terminal was resized - stored inline, no allocation
    Resize {
        /// Terminal width in columns
        width: u16,
        /// Terminal height in rows
        height: u16,
    },
    /// A tick event - stored inline, no allocation
    Tick,
    /// User-defined message with inline storage optimization
    User(InlineMessage<M>),
    /// Request to quit the program - stored inline, no allocation
    Quit,
    /// Terminal gained focus - stored inline, no allocation
    Focus,
    /// Terminal lost focus - stored inline, no allocation
    Blur,
    /// Program suspend request (Ctrl+Z) - stored inline, no allocation
    Suspend,
    /// Program resumed from suspend - stored inline, no allocation
    Resume,
    /// Bracketed paste event with COW string for efficiency
    Paste(std::borrow::Cow<'static, str>),
    /// Internal event to trigger external process execution - stored inline, no allocation
    #[doc(hidden)]
    ExecProcess,
}

/// Message storage that inlines small messages to avoid allocations
#[derive(Debug, Clone)]
pub enum InlineMessage<M> {
    /// Small message stored inline (no heap allocation)
    Inline(M),
    /// Large message stored on heap (only when necessary)
    Boxed(Box<M>),
}

impl<M> InlineMessage<M> {
    /// Create a new inline message, automatically choosing storage type
    #[inline(always)]
    pub fn new(msg: M) -> Self {
        if mem::size_of::<M>() <= INLINE_SIZE {
            Self::Inline(msg)
        } else {
            Self::Boxed(Box::new(msg))
        }
    }

    /// Get reference to the message
    #[inline(always)]
    pub fn get(&self) -> &M {
        match self {
            Self::Inline(msg) => msg,
            Self::Boxed(msg) => msg.as_ref(),
        }
    }

    /// Take the message out of storage
    #[inline(always)]
    pub fn into_inner(self) -> M {
        match self {
            Self::Inline(msg) => msg,
            Self::Boxed(msg) => *msg,
        }
    }

    /// Check if message is stored inline (zero allocation)
    #[inline(always)]
    pub fn is_inline(&self) -> bool {
        matches!(self, Self::Inline(_))
    }
}

impl<M> OptimizedEvent<M> {
    /// Create a new user event with automatic storage optimization
    #[inline(always)]
    pub fn user(msg: M) -> Self {
        Self::User(InlineMessage::new(msg))
    }

    /// Check if this is a key event
    #[inline(always)]
    pub const fn is_key(&self) -> bool {
        matches!(self, Self::Key(_))
    }

    /// Check if this is a specific key press
    #[inline(always)]
    pub fn is_key_press(&self, key: crate::event::Key) -> bool {
        matches!(self, Self::Key(k) if k.key == key)
    }

    /// Get the key event if this is a key event
    #[inline(always)]
    pub const fn as_key(&self) -> Option<&KeyEvent> {
        match self {
            Self::Key(k) => Some(k),
            _ => None,
        }
    }

    /// Check if this is a mouse event
    #[inline(always)]
    pub const fn is_mouse(&self) -> bool {
        matches!(self, Self::Mouse(_))
    }

    /// Get the mouse event if this is a mouse event
    #[inline(always)]
    pub const fn as_mouse(&self) -> Option<&MouseEvent> {
        match self {
            Self::Mouse(m) => Some(m),
            _ => None,
        }
    }

    /// Check if this is a user message
    #[inline(always)]
    pub const fn is_user(&self) -> bool {
        matches!(self, Self::User(_))
    }

    /// Get the user message if this is a user event
    #[inline(always)]
    pub fn as_user(&self) -> Option<&M> {
        match self {
            Self::User(msg) => Some(msg.get()),
            _ => None,
        }
    }

    /// Take the user message if this is a user event
    #[inline(always)]
    pub fn into_user(self) -> Option<M> {
        match self {
            Self::User(msg) => Some(msg.into_inner()),
            _ => None,
        }
    }

    /// Check if this is a quit event
    #[inline(always)]
    pub const fn is_quit(&self) -> bool {
        matches!(self, Self::Quit)
    }

    /// Check if this is a tick event
    #[inline(always)]
    pub const fn is_tick(&self) -> bool {
        matches!(self, Self::Tick)
    }

    /// Check if this is a resize event
    #[inline(always)]
    pub const fn is_resize(&self) -> bool {
        matches!(self, Self::Resize { .. })
    }

    /// Get resize dimensions if this is a resize event
    #[inline(always)]
    pub const fn as_resize(&self) -> Option<(u16, u16)> {
        match self {
            Self::Resize { width, height } => Some((*width, *height)),
            _ => None,
        }
    }
}

/// Event batch for efficient processing of multiple events
#[derive(Debug, Clone)]
pub struct EventBatch<M> {
    /// Events stored in a small vector to avoid allocations for small batches
    events: SmallVec<[OptimizedEvent<M>; 8]>,
}

impl<M> EventBatch<M> {
    /// Create a new empty event batch
    #[inline]
    pub fn new() -> Self {
        Self {
            events: SmallVec::new(),
        }
    }

    /// Create a new event batch with capacity
    #[inline]
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            events: SmallVec::with_capacity(capacity),
        }
    }

    /// Add an event to the batch
    #[inline]
    pub fn push(&mut self, event: OptimizedEvent<M>) {
        self.events.push(event);
    }

    /// Get the number of events in the batch
    #[inline]
    pub fn len(&self) -> usize {
        self.events.len()
    }

    /// Check if the batch is empty
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.events.is_empty()
    }

    /// Iterate over events in the batch
    #[inline]
    pub fn iter(&self) -> std::slice::Iter<'_, OptimizedEvent<M>> {
        self.events.iter()
    }

    /// Drain all events from the batch
    #[inline]
    pub fn drain(&mut self) -> smallvec::Drain<'_, [OptimizedEvent<M>; 8]> {
        self.events.drain(..)
    }

    /// Clear the batch
    #[inline]
    pub fn clear(&mut self) {
        self.events.clear();
    }

    /// Check if batch is using inline storage (no heap allocations)
    #[inline]
    pub fn is_inline(&self) -> bool {
        !self.events.spilled()
    }
}

impl<M> Default for EventBatch<M> {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl<M> IntoIterator for EventBatch<M> {
    type Item = OptimizedEvent<M>;
    type IntoIter = smallvec::IntoIter<[OptimizedEvent<M>; 8]>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.events.into_iter()
    }
}

/// Event coalescing for reducing redundant events
pub struct EventCoalescer<M> {
    /// Buffer for coalescing events
    buffer: SmallVec<[OptimizedEvent<M>; 16]>,
    /// Track last resize event to coalesce multiple resize events
    last_resize: Option<(u16, u16)>,
}

impl<M> EventCoalescer<M> {
    /// Create a new event coalescer
    #[inline]
    pub fn new() -> Self {
        Self {
            buffer: SmallVec::new(),
            last_resize: None,
        }
    }

    /// Add an event, coalescing with existing events where possible
    pub fn push(&mut self, event: OptimizedEvent<M>) {
        match event {
            // Coalesce resize events - only keep the latest
            OptimizedEvent::Resize { width, height } => {
                self.last_resize = Some((width, height));
            }
            // Coalesce tick events - only keep one tick per batch
            OptimizedEvent::Tick => {
                if !self.buffer.iter().any(|e| e.is_tick()) {
                    self.buffer.push(event);
                }
            }
            // Don't coalesce other events
            _ => {
                self.buffer.push(event);
            }
        }
    }

    /// Finish coalescing and return the batch
    pub fn finish(&mut self) -> EventBatch<M> {
        // Add the final resize event if any
        if let Some((width, height)) = self.last_resize.take() {
            self.buffer.push(OptimizedEvent::Resize { width, height });
        }

        let mut batch = EventBatch::with_capacity(self.buffer.len());
        batch.events.extend(self.buffer.drain(..));
        batch
    }

    /// Clear the coalescer
    #[inline]
    pub fn clear(&mut self) {
        self.buffer.clear();
        self.last_resize = None;
    }
}

impl<M> Default for EventCoalescer<M> {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

/// Convert from the standard Event to OptimizedEvent
impl<M> From<crate::event::Event<M>> for OptimizedEvent<M> {
    #[inline]
    fn from(event: crate::event::Event<M>) -> Self {
        match event {
            crate::event::Event::Key(k) => Self::Key(k),
            crate::event::Event::Mouse(m) => Self::Mouse(m),
            crate::event::Event::Resize { width, height } => Self::Resize { width, height },
            crate::event::Event::Tick => Self::Tick,
            crate::event::Event::User(m) => Self::user(m),
            crate::event::Event::Quit => Self::Quit,
            crate::event::Event::Focus => Self::Focus,
            crate::event::Event::Blur => Self::Blur,
            crate::event::Event::Suspend => Self::Suspend,
            crate::event::Event::Resume => Self::Resume,
            crate::event::Event::Paste(text) => Self::Paste(text.into()),
            crate::event::Event::ExecProcess => Self::ExecProcess,
        }
    }
}

/// Convert from OptimizedEvent back to standard Event
impl<M> From<OptimizedEvent<M>> for crate::event::Event<M> {
    #[inline]
    fn from(event: OptimizedEvent<M>) -> Self {
        match event {
            OptimizedEvent::Key(k) => Self::Key(k),
            OptimizedEvent::Mouse(m) => Self::Mouse(m),
            OptimizedEvent::Resize { width, height } => Self::Resize { width, height },
            OptimizedEvent::Tick => Self::Tick,
            OptimizedEvent::User(m) => Self::User(m.into_inner()),
            OptimizedEvent::Quit => Self::Quit,
            OptimizedEvent::Focus => Self::Focus,
            OptimizedEvent::Blur => Self::Blur,
            OptimizedEvent::Suspend => Self::Suspend,
            OptimizedEvent::Resume => Self::Resume,
            OptimizedEvent::Paste(text) => Self::Paste(text.into_owned()),
            OptimizedEvent::ExecProcess => Self::ExecProcess,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_inline_message_small() {
        let msg = 42u32;
        let inline_msg = InlineMessage::new(msg);
        assert!(inline_msg.is_inline());
        assert_eq!(*inline_msg.get(), 42);
    }

    #[test]
    fn test_inline_message_large() {
        // Create a large struct that exceeds INLINE_SIZE
        #[derive(Debug, PartialEq, Clone)]
        struct LargeStruct([u8; 32]); // This exceeds INLINE_SIZE of 24

        let msg = LargeStruct([0u8; 32]);
        let inline_msg = InlineMessage::new(msg.clone());
        // Large messages should be boxed
        assert!(!inline_msg.is_inline());
        assert_eq!(*inline_msg.get(), msg);
    }

    #[test]
    fn test_event_coalescing() {
        let mut coalescer: EventCoalescer<()> = EventCoalescer::new();

        // Add multiple resize events
        coalescer.push(OptimizedEvent::Resize {
            width: 80,
            height: 24,
        });
        coalescer.push(OptimizedEvent::Resize {
            width: 100,
            height: 30,
        });
        coalescer.push(OptimizedEvent::Resize {
            width: 120,
            height: 40,
        });

        // Add multiple ticks
        coalescer.push(OptimizedEvent::Tick);
        coalescer.push(OptimizedEvent::Tick);

        let batch = coalescer.finish();

        // Should have only one resize (the last one) and one tick
        assert_eq!(batch.len(), 2);

        let events: Vec<_> = batch.into_iter().collect();
        assert!(events.iter().any(|e| matches!(e, OptimizedEvent::Tick)));
        assert!(events.iter().any(|e| matches!(
            e,
            OptimizedEvent::Resize {
                width: 120,
                height: 40
            }
        )));
    }

    #[test]
    fn test_event_batch_inline_storage() {
        let mut batch = EventBatch::new();

        // Add a few events - should stay inline
        batch.push(OptimizedEvent::Tick);
        batch.push(OptimizedEvent::user(42u32));
        batch.push(OptimizedEvent::Quit);

        assert!(batch.is_inline()); // No heap allocation
        assert_eq!(batch.len(), 3);
    }

    #[test]
    fn test_zero_cost_event_checks() {
        let event = OptimizedEvent::user(String::from("test"));

        // These should all be constant time, no allocations
        assert!(event.is_user());
        assert!(!event.is_key());
        assert!(!event.is_mouse());
        assert_eq!(event.as_user().unwrap(), "test");
    }
}