Skip to main content

rustduck_core/memory/endpoint/
input.rs

1//! Public bounded memory-input endpoint API.
2
3use std::num::NonZeroUsize;
4use std::sync::Arc;
5
6use crate::{MemoryPushOutcome, MemoryQueuePolicy, Result};
7
8use super::binding::MemoryInputBinding;
9use super::inner::MemoryInputInner;
10use super::state::{acquire, take};
11use super::validation::{capacity, packets};
12use super::{CallbackError, PacketQueue};
13
14/// Thread-safe bounded input endpoint for a TSDuck `memory` plugin.
15///
16/// Every payload must contain complete 188-byte TS packets. `close` causes a
17/// bound input callback to report EOF after draining queued data; `abort`
18/// wakes blocked producers/callbacks and fails the transfer.
19pub struct MemoryInput {
20    pub(crate) inner: Arc<MemoryInputInner>,
21}
22
23impl MemoryInput {
24    /// Creates a bounded input endpoint with a capacity in complete TS packets.
25    pub fn new(capacity_bytes: NonZeroUsize, policy: MemoryQueuePolicy) -> Result<Arc<Self>> {
26        Ok(Arc::new(Self {
27            inner: MemoryInputInner::new(PacketQueue::new(capacity(capacity_bytes)?, policy)),
28        }))
29    }
30
31    /// Copies a packet-aligned input slice into queue-owned storage.
32    pub fn push(&self, data: &[u8]) -> Result<MemoryPushOutcome> {
33        packets(data)?;
34        self.inner.queue().push_owned(data.to_vec(), "MemoryInput")
35    }
36
37    /// Moves packet-aligned input storage into the queue.
38    ///
39    /// A complete owned queue head can move directly into the next native input
40    /// callback response, avoiding a Rust-side reassembly allocation.
41    pub fn push_owned(&self, data: Vec<u8>) -> Result<MemoryPushOutcome> {
42        packets(&data)?;
43        self.inner.queue().push_owned(data, "MemoryInput")
44    }
45
46    /// Shares immutable packet-aligned storage with the queue.
47    pub fn push_shared(&self, data: Arc<[u8]>) -> Result<MemoryPushOutcome> {
48        packets(&data)?;
49        self.inner.queue().push_shared(data, "MemoryInput")
50    }
51
52    /// Closes the input after currently queued packets are consumed.
53    pub fn close(&self) {
54        self.inner.queue().close();
55    }
56    /// Aborts the input and wakes all blocked operations.
57    pub fn abort(&self) {
58        self.inner.queue().abort();
59    }
60    /// Returns queued input bytes.
61    pub fn queued_bytes(&self) -> usize {
62        self.inner.queue().queued_bytes()
63    }
64    /// Returns bytes rejected by the drop policy.
65    pub fn dropped_bytes(&self) -> usize {
66        self.inner.queue().dropped_bytes()
67    }
68    /// Takes the latest private callback error.
69    pub fn take_callback_error(&self) -> Option<CallbackError> {
70        take(self.inner.state())
71    }
72
73    pub(crate) fn bind(&self) -> Result<MemoryInputBinding> {
74        acquire(self.inner.state(), "MemoryInput")?;
75        Ok(MemoryInputBinding::new(Arc::clone(&self.inner)))
76    }
77}