mabi-knx 1.4.0

Mabinogion - KNXnet/IP simulator
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
//! Bidirectional filter chain pipeline.
//!
//! The [`FilterChain`] orchestrates frame processing through a pipeline of
//! filters in both send (forward) and receive (reverse) directions.
//!
//! ```text
//! send():  Client → Filter[0] → Filter[1] → ... → Filter[N] → Bus
//! recv():  Client ← Filter[0] ← Filter[1] ← ... ← Filter[N] ← Bus
//! ```
//!
//! Each filter can:
//! - **Pass** the frame through (possibly with delay)
//! - **Queue** the frame for later delivery
//! - **Drop** the frame (e.g., circuit breaker open)
//! - **Error** with a specific reason

use std::fmt;
use std::net::SocketAddr;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};

use serde::{Deserialize, Serialize};
use tracing::{debug, trace};

use crate::cemi::CemiFrame;

use super::pace::{PaceFilter, PaceFilterConfig};
use super::queue::{QueueFilter, QueueFilterConfig, QueuePriority};
use super::retry::{RetryFilter, RetryFilterConfig};

// ============================================================================
// Frame Envelope — carries frame + metadata through the pipeline
// ============================================================================

/// Frame envelope carrying a cEMI frame with pipeline metadata.
///
/// The envelope tracks the frame's journey through the filter chain,
/// including original timestamps, priority, channel association, and
/// the number of pipeline stages it has passed through.
#[derive(Debug, Clone)]
pub struct FrameEnvelope {
    /// The cEMI frame payload.
    pub cemi: CemiFrame,
    /// Channel ID of the originating connection.
    pub channel_id: u8,
    /// Target client address for delivery.
    pub target_addr: SocketAddr,
    /// Frame priority (determined by QueueFilter classification).
    pub priority: QueuePriority,
    /// Timestamp when the frame entered the pipeline.
    pub enqueued_at: Instant,
    /// Accumulated delay from all filters in the chain.
    pub accumulated_delay: Duration,
    /// Number of retry attempts (managed by RetryFilter).
    pub retry_count: u8,
    /// Whether this frame requires an ACK from the client.
    pub requires_ack: bool,
    /// Original frame size in bytes (for PaceFilter timing calculation).
    pub frame_size_bytes: usize,
}

impl FrameEnvelope {
    /// Create a new frame envelope.
    pub fn new(cemi: CemiFrame, channel_id: u8, target_addr: SocketAddr) -> Self {
        let frame_size_bytes = cemi.encode().len();
        Self {
            cemi,
            channel_id,
            target_addr,
            priority: QueuePriority::Normal,
            enqueued_at: Instant::now(),
            accumulated_delay: Duration::ZERO,
            retry_count: 0,
            requires_ack: true,
            frame_size_bytes,
        }
    }

    /// Create with explicit priority.
    pub fn with_priority(mut self, priority: QueuePriority) -> Self {
        self.priority = priority;
        self
    }

    /// Create with ACK requirement flag.
    pub fn with_ack_required(mut self, requires_ack: bool) -> Self {
        self.requires_ack = requires_ack;
        self
    }

    /// Get total time in pipeline.
    pub fn pipeline_duration(&self) -> Duration {
        self.enqueued_at.elapsed()
    }
}

// ============================================================================
// Filter Result
// ============================================================================

/// Result of a filter processing a frame.
#[derive(Debug, Clone)]
pub enum FilterResult {
    /// Frame passed through, optionally with added delay.
    Pass {
        /// Additional delay to apply before actual transmission.
        delay: Duration,
    },
    /// Frame was queued internally — will be delivered later.
    /// The pipeline should not proceed; the filter owns the frame.
    Queued,
    /// Frame was dropped (e.g., circuit breaker open, queue full).
    Dropped {
        /// Human-readable reason for dropping.
        reason: String,
    },
    /// An error occurred during filtering.
    Error {
        /// Error description.
        message: String,
    },
}

impl FilterResult {
    /// Convenience for pass with no delay.
    pub fn pass() -> Self {
        Self::Pass {
            delay: Duration::ZERO,
        }
    }

    /// Convenience for pass with delay.
    pub fn pass_with_delay(delay: Duration) -> Self {
        Self::Pass { delay }
    }

    /// Whether the frame should continue through the pipeline.
    pub fn should_continue(&self) -> bool {
        matches!(self, Self::Pass { .. })
    }
}

// ============================================================================
// Filter Direction
// ============================================================================

/// Direction of frame flow through the filter chain.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FilterDirection {
    /// Client → Bus (outbound). Filters are applied in forward order.
    Send,
    /// Bus → Client (inbound). Filters are applied in reverse order.
    Recv,
}

impl fmt::Display for FilterDirection {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Send => write!(f, "send"),
            Self::Recv => write!(f, "recv"),
        }
    }
}

// ============================================================================
// Filter Chain Configuration
// ============================================================================

/// Configuration for the complete filter chain.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FilterChainConfig {
    /// Whether the filter chain is enabled at all.
    /// When disabled, frames pass through with zero overhead.
    #[serde(default)]
    pub enabled: bool,

    /// PaceFilter configuration (bus timing simulation).
    #[serde(default)]
    pub pace: PaceFilterConfig,

    /// QueueFilter configuration (priority queuing).
    #[serde(default)]
    pub queue: QueueFilterConfig,

    /// RetryFilter configuration (retry + circuit breaker).
    #[serde(default)]
    pub retry: RetryFilterConfig,
}

impl Default for FilterChainConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            pace: PaceFilterConfig::default(),
            queue: QueueFilterConfig::default(),
            retry: RetryFilterConfig::default(),
        }
    }
}

impl FilterChainConfig {
    /// Create an enabled filter chain with default sub-filter configs.
    pub fn enabled() -> Self {
        Self {
            enabled: true,
            ..Default::default()
        }
    }

    /// Validate the configuration.
    pub fn validate(&self) -> Result<(), String> {
        self.pace.validate()?;
        self.queue.validate()?;
        self.retry.validate()?;
        Ok(())
    }
}

// ============================================================================
// Filter Chain Statistics
// ============================================================================

/// Lock-free filter chain statistics.
#[derive(Debug, Default)]
pub struct FilterChainStats {
    /// Total frames processed in send direction.
    pub frames_sent: AtomicU64,
    /// Total frames processed in recv direction.
    pub frames_received: AtomicU64,
    /// Total frames dropped across all filters.
    pub frames_dropped: AtomicU64,
    /// Total frames queued across all filters.
    pub frames_queued: AtomicU64,
    /// Total accumulated delay applied (in microseconds).
    pub total_delay_us: AtomicU64,
    /// Total filter chain bypass (disabled) count.
    pub bypass_count: AtomicU64,
}

/// Snapshot of filter chain statistics.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FilterChainStatsSnapshot {
    pub frames_sent: u64,
    pub frames_received: u64,
    pub frames_dropped: u64,
    pub frames_queued: u64,
    pub total_delay_us: u64,
    pub bypass_count: u64,
}

// ============================================================================
// Filter Chain
// ============================================================================

/// Bidirectional filter chain for KNX bus flow control.
///
/// The chain processes frames through three stages:
/// 1. **QueueFilter**: Priority-based queuing with backpressure
/// 2. **PaceFilter**: Bus timing enforcement (inter-frame delay)
/// 3. **RetryFilter**: Retry logic with circuit breaker protection
///
/// In the send direction (Client → Bus), filters are applied in order:
///   Queue → Pace → Retry
///
/// In the recv direction (Bus → Client), filters are applied in reverse:
///   Retry → Pace → Queue
pub struct FilterChain {
    config: FilterChainConfig,
    queue_filter: QueueFilter,
    pace_filter: PaceFilter,
    retry_filter: RetryFilter,
    stats: Arc<FilterChainStats>,
}

impl FilterChain {
    /// Create a new filter chain with the given configuration.
    pub fn new(config: FilterChainConfig) -> Self {
        Self {
            queue_filter: QueueFilter::new(config.queue.clone()),
            pace_filter: PaceFilter::new(config.pace.clone()),
            retry_filter: RetryFilter::new(config.retry.clone()),
            config,
            stats: Arc::new(FilterChainStats::default()),
        }
    }

    /// Check if the filter chain is enabled.
    pub fn is_enabled(&self) -> bool {
        self.config.enabled
    }

    /// Process a frame through the send (forward) direction.
    ///
    /// Pipeline order: Queue → Pace → Retry
    ///
    /// Returns the total delay to apply before transmission, or an error
    /// if the frame was dropped/queued.
    pub fn send(&self, envelope: &mut FrameEnvelope) -> FilterResult {
        if !self.config.enabled {
            self.stats.bypass_count.fetch_add(1, Ordering::Relaxed);
            return FilterResult::pass();
        }

        self.stats.frames_sent.fetch_add(1, Ordering::Relaxed);

        // Stage 1: QueueFilter — priority classification + backpressure
        let queue_result = self.queue_filter.process_send(envelope);
        if !queue_result.should_continue() {
            match &queue_result {
                FilterResult::Queued => {
                    self.stats.frames_queued.fetch_add(1, Ordering::Relaxed);
                    trace!(
                        channel_id = envelope.channel_id,
                        priority = ?envelope.priority,
                        "Frame queued by QueueFilter"
                    );
                }
                FilterResult::Dropped { reason } => {
                    self.stats.frames_dropped.fetch_add(1, Ordering::Relaxed);
                    debug!(
                        channel_id = envelope.channel_id,
                        reason = %reason,
                        "Frame dropped by QueueFilter"
                    );
                }
                _ => {}
            }
            return queue_result;
        }

        // Stage 2: PaceFilter — bus timing enforcement
        let pace_result = self.pace_filter.process_send(envelope);
        if !pace_result.should_continue() {
            match &pace_result {
                FilterResult::Dropped { reason } => {
                    self.stats.frames_dropped.fetch_add(1, Ordering::Relaxed);
                    debug!(
                        channel_id = envelope.channel_id,
                        reason = %reason,
                        "Frame dropped by PaceFilter"
                    );
                }
                _ => {}
            }
            return pace_result;
        }
        if let FilterResult::Pass { delay } = &pace_result {
            envelope.accumulated_delay += *delay;
        }

        // Stage 3: RetryFilter — circuit breaker check
        let retry_result = self.retry_filter.process_send(envelope);
        if !retry_result.should_continue() {
            match &retry_result {
                FilterResult::Dropped { reason } => {
                    self.stats.frames_dropped.fetch_add(1, Ordering::Relaxed);
                    debug!(
                        channel_id = envelope.channel_id,
                        reason = %reason,
                        "Frame dropped by RetryFilter (circuit breaker)"
                    );
                }
                _ => {}
            }
            return retry_result;
        }
        if let FilterResult::Pass { delay } = &retry_result {
            envelope.accumulated_delay += *delay;
        }

        // Record total accumulated delay
        let total_delay = envelope.accumulated_delay;
        if total_delay > Duration::ZERO {
            self.stats
                .total_delay_us
                .fetch_add(total_delay.as_micros() as u64, Ordering::Relaxed);
        }

        trace!(
            channel_id = envelope.channel_id,
            delay_ms = total_delay.as_millis(),
            priority = ?envelope.priority,
            "Frame passed through filter chain (send)"
        );

        FilterResult::pass_with_delay(total_delay)
    }

    /// Process a frame through the recv (reverse) direction.
    ///
    /// Pipeline order: Retry → Pace → Queue
    ///
    /// For the receive path, we apply filters in reverse to maintain
    /// the bidirectional pipeline semantics.
    pub fn recv(&self, envelope: &mut FrameEnvelope) -> FilterResult {
        if !self.config.enabled {
            self.stats.bypass_count.fetch_add(1, Ordering::Relaxed);
            return FilterResult::pass();
        }

        self.stats.frames_received.fetch_add(1, Ordering::Relaxed);

        // Stage 1 (reverse): RetryFilter — record successful delivery
        let retry_result = self.retry_filter.process_recv(envelope);
        if !retry_result.should_continue() {
            return retry_result;
        }

        // Stage 2 (reverse): PaceFilter — update timing state
        let pace_result = self.pace_filter.process_recv(envelope);
        if !pace_result.should_continue() {
            return pace_result;
        }

        // Stage 3 (reverse): QueueFilter — dequeue acknowledgment
        let queue_result = self.queue_filter.process_recv(envelope);
        if !queue_result.should_continue() {
            return queue_result;
        }

        trace!(
            channel_id = envelope.channel_id,
            "Frame passed through filter chain (recv)"
        );

        FilterResult::pass()
    }

    /// Notify the filter chain that a frame transmission succeeded.
    ///
    /// This feeds back into the RetryFilter's circuit breaker and
    /// the PaceFilter's state machine.
    pub fn on_send_success(&self, channel_id: u8) {
        if !self.config.enabled {
            return;
        }
        self.retry_filter.on_success();
        self.pace_filter.on_frame_completed();
        self.queue_filter.on_ack_received(channel_id);

        trace!(channel_id, "Filter chain: send success");
    }

    /// Notify the filter chain that a frame transmission failed.
    ///
    /// This feeds into the RetryFilter's circuit breaker to potentially
    /// trip it open.
    pub fn on_send_failure(&self, channel_id: u8, error: &str) {
        if !self.config.enabled {
            return;
        }
        self.retry_filter.on_failure();
        self.queue_filter.on_send_error(channel_id);

        debug!(channel_id, error, "Filter chain: send failure");
    }

    /// Drain pending frames from the QueueFilter for a specific channel.
    ///
    /// Returns frames in priority order (High → Normal → Low).
    /// Used by the server to poll for queued frames when the connection
    /// transitions from WaitingForAck back to Idle.
    pub fn drain_pending(&self, channel_id: u8, max_count: usize) -> Vec<FrameEnvelope> {
        if !self.config.enabled {
            return Vec::new();
        }
        self.queue_filter.drain(channel_id, max_count)
    }

    /// Check if the chain has pending frames for a channel.
    pub fn has_pending(&self, channel_id: u8) -> bool {
        if !self.config.enabled {
            return false;
        }
        self.queue_filter.has_pending(channel_id)
    }

    /// Get the total pending frame count across all channels.
    pub fn pending_count(&self) -> usize {
        if !self.config.enabled {
            return 0;
        }
        self.queue_filter.total_pending()
    }

    /// Get the current PaceFilter state.
    pub fn pace_state(&self) -> super::pace::PaceState {
        self.pace_filter.state()
    }

    /// Get the current CircuitBreaker state.
    pub fn circuit_breaker_state(&self) -> super::retry::CircuitBreakerState {
        self.retry_filter.circuit_state()
    }

    /// Get a reference to the QueueFilter for inspection.
    pub fn queue_filter(&self) -> &QueueFilter {
        &self.queue_filter
    }

    /// Get a reference to the PaceFilter for inspection.
    pub fn pace_filter(&self) -> &PaceFilter {
        &self.pace_filter
    }

    /// Get a reference to the RetryFilter for inspection.
    pub fn retry_filter(&self) -> &RetryFilter {
        &self.retry_filter
    }

    /// Get a snapshot of the filter chain statistics.
    pub fn stats_snapshot(&self) -> FilterChainStatsSnapshot {
        FilterChainStatsSnapshot {
            frames_sent: self.stats.frames_sent.load(Ordering::Relaxed),
            frames_received: self.stats.frames_received.load(Ordering::Relaxed),
            frames_dropped: self.stats.frames_dropped.load(Ordering::Relaxed),
            frames_queued: self.stats.frames_queued.load(Ordering::Relaxed),
            total_delay_us: self.stats.total_delay_us.load(Ordering::Relaxed),
            bypass_count: self.stats.bypass_count.load(Ordering::Relaxed),
        }
    }
}

impl fmt::Debug for FilterChain {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("FilterChain")
            .field("enabled", &self.config.enabled)
            .field("pace_state", &self.pace_filter.state())
            .field("circuit_breaker", &self.retry_filter.circuit_state())
            .field("pending_frames", &self.queue_filter.total_pending())
            .finish()
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::address::{GroupAddress, IndividualAddress};
    use crate::cemi::CemiFrame;

    fn make_envelope() -> FrameEnvelope {
        let cemi = CemiFrame::group_value_write(
            IndividualAddress::new(1, 1, 1),
            GroupAddress::three_level(1, 0, 1),
            vec![0x01],
        );
        FrameEnvelope::new(cemi, 1, "192.168.1.100:3671".parse().unwrap())
    }

    #[test]
    fn test_filter_chain_disabled() {
        let chain = FilterChain::new(FilterChainConfig::default());
        assert!(!chain.is_enabled());

        let mut envelope = make_envelope();
        let result = chain.send(&mut envelope);

        assert!(matches!(result, FilterResult::Pass { delay } if delay == Duration::ZERO));

        let stats = chain.stats_snapshot();
        assert_eq!(stats.bypass_count, 1);
        assert_eq!(stats.frames_sent, 0);
    }

    #[test]
    fn test_filter_chain_enabled_passthrough() {
        let chain = FilterChain::new(FilterChainConfig::enabled());
        assert!(chain.is_enabled());

        let mut envelope = make_envelope();
        let result = chain.send(&mut envelope);

        assert!(result.should_continue());

        let stats = chain.stats_snapshot();
        assert_eq!(stats.frames_sent, 1);
        assert_eq!(stats.bypass_count, 0);
    }

    #[test]
    fn test_filter_chain_send_recv_cycle() {
        let chain = FilterChain::new(FilterChainConfig::enabled());

        // Send
        let mut send_env = make_envelope();
        let send_result = chain.send(&mut send_env);
        assert!(send_result.should_continue());

        // Recv
        let mut recv_env = make_envelope();
        let recv_result = chain.recv(&mut recv_env);
        assert!(recv_result.should_continue());

        let stats = chain.stats_snapshot();
        assert_eq!(stats.frames_sent, 1);
        assert_eq!(stats.frames_received, 1);
    }

    #[test]
    fn test_filter_chain_success_callback() {
        let chain = FilterChain::new(FilterChainConfig::enabled());

        let mut envelope = make_envelope();
        chain.send(&mut envelope);
        chain.on_send_success(1);

        // No assertion needed — just ensure no panic
    }

    #[test]
    fn test_filter_chain_failure_callback() {
        let chain = FilterChain::new(FilterChainConfig::enabled());

        let mut envelope = make_envelope();
        chain.send(&mut envelope);
        chain.on_send_failure(1, "test error");

        // No assertion needed — just ensure no panic
    }

    #[test]
    fn test_filter_chain_debug() {
        let chain = FilterChain::new(FilterChainConfig::enabled());
        let debug_str = format!("{:?}", chain);
        assert!(debug_str.contains("FilterChain"));
        assert!(debug_str.contains("enabled"));
    }

    #[test]
    fn test_filter_chain_config_validate() {
        let config = FilterChainConfig::enabled();
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_frame_envelope_creation() {
        let envelope = make_envelope();
        assert_eq!(envelope.channel_id, 1);
        assert_eq!(envelope.priority, QueuePriority::Normal);
        assert!(envelope.requires_ack);
        assert!(envelope.frame_size_bytes > 0);
        assert_eq!(envelope.retry_count, 0);
        assert_eq!(envelope.accumulated_delay, Duration::ZERO);
    }

    #[test]
    fn test_frame_envelope_builders() {
        let envelope = make_envelope()
            .with_priority(QueuePriority::High)
            .with_ack_required(false);

        assert_eq!(envelope.priority, QueuePriority::High);
        assert!(!envelope.requires_ack);
    }

    #[test]
    fn test_filter_result_variants() {
        let pass = FilterResult::pass();
        assert!(pass.should_continue());

        let delayed = FilterResult::pass_with_delay(Duration::from_millis(50));
        assert!(delayed.should_continue());

        let queued = FilterResult::Queued;
        assert!(!queued.should_continue());

        let dropped = FilterResult::Dropped {
            reason: "test".to_string(),
        };
        assert!(!dropped.should_continue());

        let error = FilterResult::Error {
            message: "test error".to_string(),
        };
        assert!(!error.should_continue());
    }

    #[test]
    fn test_filter_direction_display() {
        assert_eq!(FilterDirection::Send.to_string(), "send");
        assert_eq!(FilterDirection::Recv.to_string(), "recv");
    }

    #[test]
    fn test_drain_pending_disabled() {
        let chain = FilterChain::new(FilterChainConfig::default());
        let drained = chain.drain_pending(1, 10);
        assert!(drained.is_empty());
    }

    #[test]
    fn test_has_pending_disabled() {
        let chain = FilterChain::new(FilterChainConfig::default());
        assert!(!chain.has_pending(1));
    }

    #[test]
    fn test_pending_count_disabled() {
        let chain = FilterChain::new(FilterChainConfig::default());
        assert_eq!(chain.pending_count(), 0);
    }
}