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        let inner = MemoryInputInner::new(PacketQueue::new(capacity(capacity_bytes)?, policy))?;
27        Ok(Arc::new(Self { inner }))
28    }
29
30    /// Copies a packet-aligned input slice into queue-owned storage.
31    pub fn push(&self, data: &[u8]) -> Result<MemoryPushOutcome> {
32        packets(data)?;
33        self.inner.queue().push_owned(data.to_vec(), "MemoryInput")
34    }
35
36    /// Moves packet-aligned input storage into the queue.
37    ///
38    /// A complete owned queue head can move directly into the next native input
39    /// callback response, avoiding a Rust-side reassembly allocation.
40    pub fn push_owned(&self, data: Vec<u8>) -> Result<MemoryPushOutcome> {
41        packets(&data)?;
42        self.inner.queue().push_owned(data, "MemoryInput")
43    }
44
45    /// Shares immutable packet-aligned storage with the queue.
46    pub fn push_shared(&self, data: Arc<[u8]>) -> Result<MemoryPushOutcome> {
47        packets(&data)?;
48        self.inner.queue().push_shared(data, "MemoryInput")
49    }
50
51    /// Closes the input after currently queued packets are consumed.
52    pub fn close(&self) {
53        self.inner.queue().close();
54    }
55    /// Aborts the input and wakes all blocked operations.
56    pub fn abort(&self) {
57        self.inner.queue().abort();
58    }
59    /// Returns queued input bytes.
60    pub fn queued_bytes(&self) -> usize {
61        self.inner.queue().queued_bytes()
62    }
63    /// Returns bytes rejected by the drop policy.
64    pub fn dropped_bytes(&self) -> usize {
65        self.inner.queue().dropped_bytes()
66    }
67    /// Takes the latest private callback error.
68    pub fn take_callback_error(&self) -> Option<CallbackError> {
69        take(self.inner.state())
70    }
71
72    pub(crate) fn bind(&self) -> Result<MemoryInputBinding> {
73        acquire(self.inner.state(), "MemoryInput")?;
74        Ok(MemoryInputBinding::new(Arc::clone(&self.inner)))
75    }
76}