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
use crate::{DataReader, DdsEntity, DdsResult, DdsType, WaitSet};
use cyclonedds_rust_sys::*;
#[cfg(feature = "async")]
impl WaitSet {
pub async fn wait_async(&self, timeout_ns: i64) -> DdsResult<Vec<i64>> {
let entity = self.entity();
tokio::task::spawn_blocking(move || {
let max_results: usize = 64;
let mut xs: Vec<dds_attach_t> = vec![0; max_results];
let n = unsafe { dds_waitset_wait(entity, xs.as_mut_ptr(), max_results, timeout_ns) };
if n < 0 {
return Err(crate::DdsError::from(n));
}
let n = n as usize;
xs.truncate(n);
Ok(xs.into_iter().map(|x| x as i64).collect())
})
.await
.map_err(|e| crate::DdsError::Other(e.to_string()))?
}
}
#[cfg(feature = "async")]
impl<T: DdsType> DataReader<T> {
pub async fn take_async(&self) -> DdsResult<Vec<T>> {
let entity = self.entity();
tokio::task::spawn_blocking(move || unsafe {
let max_samples: usize = 256;
let mut samples: Vec<*mut std::ffi::c_void> = vec![std::ptr::null_mut(); max_samples];
let mut infos: Vec<dds_sample_info> = vec![std::mem::zeroed(); max_samples];
let n = dds_take(
entity,
samples.as_mut_ptr(),
infos.as_mut_ptr() as *mut dds_sample_info_t,
max_samples,
max_samples as u32,
);
if n < 0 {
return Err(crate::DdsError::from(n));
}
let n = n as usize;
let mut result = Vec::with_capacity(n);
for i in 0..n {
if infos[i].valid_data && !samples[i].is_null() {
let data = std::ptr::read(samples[i] as *const T);
result.push(data);
}
}
let _ = dds_return_loan(entity, samples.as_mut_ptr(), n as i32);
Ok(result)
})
.await
.map_err(|e| crate::DdsError::Other(e.to_string()))?
}
/// Async iterator that yields batches of samples via `read`.
///
/// The stream waits for new data using a [`WaitSet`] and then reads
/// all available samples. It yields `Vec<T>` (possibly empty on timeout)
/// and continues until the stream is dropped.
///
/// # Example
///
/// ```no_run
/// use cyclonedds::DataReader;
/// use futures_util::StreamExt;
/// # async fn example<T: cyclonedds::DdsType>(reader: &DataReader<T>) {
/// let mut stream = Box::pin(reader.read_aiter());
/// while let Some(batch) = stream.next().await {
/// match batch {
/// Ok(samples) => println!("got {} samples", samples.len()),
/// Err(e) => eprintln!("read error: {}", e),
/// }
/// }
/// # }
/// ```
pub fn read_aiter(&self) -> impl futures_core::Stream<Item = DdsResult<Vec<T>>> + '_ {
let entity = self.entity();
async_stream::try_stream! {
let participant = tokio::task::spawn_blocking(move || unsafe {
dds_get_participant(entity)
}).await.map_err(|e| crate::DdsError::Other(e.to_string()))?;
let waitset = WaitSet::new(participant)?;
waitset.attach(entity, 0)?;
loop {
let triggered = waitset.wait_async(dds_duration_t::MAX).await?;
if triggered.is_empty() {
// timeout with no data — yield empty batch so caller
// can still make progress / apply back-pressure.
yield Vec::new();
continue;
}
let batch = tokio::task::spawn_blocking(move || unsafe {
let max_samples: usize = 256;
let mut samples: Vec<*mut std::ffi::c_void> = vec![std::ptr::null_mut(); max_samples];
let mut infos: Vec<dds_sample_info> = vec![std::mem::zeroed(); max_samples];
let n = dds_read(
entity,
samples.as_mut_ptr(),
infos.as_mut_ptr() as *mut dds_sample_info_t,
max_samples,
max_samples as u32,
);
if n < 0 {
return Err::<Vec<T>, crate::DdsError>(crate::DdsError::from(n));
}
let n = n as usize;
let mut result = Vec::with_capacity(n);
for i in 0..n {
if infos[i].valid_data && !samples[i].is_null() {
let data = std::ptr::read(samples[i] as *const T);
result.push(data);
}
}
let _ = dds_return_loan(entity, samples.as_mut_ptr(), n as i32);
Ok(result)
})
.await
.map_err(|e| crate::DdsError::Other(e.to_string()))?;
yield batch?;
}
}
}
/// Async iterator that yields batches of samples via `read`, with a
/// configurable maximum number of samples per batch.
///
/// This is useful when you expect large bursts of data and want to
/// process them in fixed-size chunks to apply back-pressure.
///
/// # Example
///
/// ```no_run
/// use cyclonedds::DataReader;
/// use futures_util::StreamExt;
/// # async fn example<T: cyclonedds::DdsType>(reader: &DataReader<T>) {
/// let mut stream = Box::pin(reader.read_aiter_batch(64));
/// while let Some(batch) = stream.next().await {
/// match batch {
/// Ok(samples) => println!("got {} samples", samples.len()),
/// Err(e) => eprintln!("read error: {}", e),
/// }
/// }
/// # }
/// ```
pub fn read_aiter_batch(
&self,
max_samples: usize,
) -> impl futures_core::Stream<Item = DdsResult<Vec<T>>> + '_ {
let entity = self.entity();
async_stream::try_stream! {
let participant = tokio::task::spawn_blocking(move || unsafe {
dds_get_participant(entity)
}).await.map_err(|e| crate::DdsError::Other(e.to_string()))?;
let waitset = WaitSet::new(participant)?;
waitset.attach(entity, 0)?;
loop {
let triggered = waitset.wait_async(dds_duration_t::MAX).await?;
if triggered.is_empty() {
yield Vec::new();
continue;
}
let batch = tokio::task::spawn_blocking(move || unsafe {
let mut samples: Vec<*mut std::ffi::c_void> = vec![std::ptr::null_mut(); max_samples];
let mut infos: Vec<dds_sample_info> = vec![std::mem::zeroed(); max_samples];
let n = dds_read(
entity,
samples.as_mut_ptr(),
infos.as_mut_ptr() as *mut dds_sample_info_t,
max_samples,
max_samples as u32,
);
if n < 0 {
return Err::<Vec<T>, crate::DdsError>(crate::DdsError::from(n));
}
let n = n as usize;
let mut result = Vec::with_capacity(n);
for i in 0..n {
if infos[i].valid_data && !samples[i].is_null() {
let data = std::ptr::read(samples[i] as *const T);
result.push(data);
}
}
let _ = dds_return_loan(entity, samples.as_mut_ptr(), n as i32);
Ok(result)
})
.await
.map_err(|e| crate::DdsError::Other(e.to_string()))?;
yield batch?;
}
}
}
/// Async iterator that yields batches of samples via `take`.
///
/// Like [`read_aiter`](Self::read_aiter) but removes samples from the
/// reader history cache.
pub fn take_aiter(&self) -> impl futures_core::Stream<Item = DdsResult<Vec<T>>> + '_ {
let entity = self.entity();
async_stream::try_stream! {
let participant = tokio::task::spawn_blocking(move || unsafe {
dds_get_participant(entity)
}).await.map_err(|e| crate::DdsError::Other(e.to_string()))?;
let waitset = WaitSet::new(participant)?;
waitset.attach(entity, 0)?;
loop {
let triggered = waitset.wait_async(dds_duration_t::MAX).await?;
if triggered.is_empty() {
yield Vec::new();
continue;
}
let batch = tokio::task::spawn_blocking(move || unsafe {
let max_samples: usize = 256;
let mut samples: Vec<*mut std::ffi::c_void> = vec![std::ptr::null_mut(); max_samples];
let mut infos: Vec<dds_sample_info> = vec![std::mem::zeroed(); max_samples];
let n = dds_take(
entity,
samples.as_mut_ptr(),
infos.as_mut_ptr() as *mut dds_sample_info_t,
max_samples,
max_samples as u32,
);
if n < 0 {
return Err::<Vec<T>, crate::DdsError>(crate::DdsError::from(n));
}
let n = n as usize;
let mut result = Vec::with_capacity(n);
for i in 0..n {
if infos[i].valid_data && !samples[i].is_null() {
let data = std::ptr::read(samples[i] as *const T);
result.push(data);
}
}
let _ = dds_return_loan(entity, samples.as_mut_ptr(), n as i32);
Ok(result)
})
.await
.map_err(|e| crate::DdsError::Other(e.to_string()))?;
yield batch?;
}
}
}
/// Async iterator that yields batches of samples via `take`, with a
/// configurable maximum number of samples per batch.
///
/// Like [`take_aiter`](Self::take_aiter) but allows limiting the batch
/// size for back-pressure control.
pub fn take_aiter_batch(
&self,
max_samples: usize,
) -> impl futures_core::Stream<Item = DdsResult<Vec<T>>> + '_ {
let entity = self.entity();
async_stream::try_stream! {
let participant = tokio::task::spawn_blocking(move || unsafe {
dds_get_participant(entity)
}).await.map_err(|e| crate::DdsError::Other(e.to_string()))?;
let waitset = WaitSet::new(participant)?;
waitset.attach(entity, 0)?;
loop {
let triggered = waitset.wait_async(dds_duration_t::MAX).await?;
if triggered.is_empty() {
yield Vec::new();
continue;
}
let batch = tokio::task::spawn_blocking(move || unsafe {
let mut samples: Vec<*mut std::ffi::c_void> = vec![std::ptr::null_mut(); max_samples];
let mut infos: Vec<dds_sample_info> = vec![std::mem::zeroed(); max_samples];
let n = dds_take(
entity,
samples.as_mut_ptr(),
infos.as_mut_ptr() as *mut dds_sample_info_t,
max_samples,
max_samples as u32,
);
if n < 0 {
return Err::<Vec<T>, crate::DdsError>(crate::DdsError::from(n));
}
let n = n as usize;
let mut result = Vec::with_capacity(n);
for i in 0..n {
if infos[i].valid_data && !samples[i].is_null() {
let data = std::ptr::read(samples[i] as *const T);
result.push(data);
}
}
let _ = dds_return_loan(entity, samples.as_mut_ptr(), n as i32);
Ok(result)
})
.await
.map_err(|e| crate::DdsError::Other(e.to_string()))?;
yield batch?;
}
}
}
}