opc-da-client 0.1.3

Backend-agnostic OPC DA client library for Rust — async, trait-based, with RAII COM guard
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
use crate::opc_da::{
    def::ItemAttributes,
    utils::{RemoteArray, RemotePointer, TryToLocal as _},
};

const MAX_CACHE_SIZE: usize = 16;
const STRING_CACHE_SIZE: usize = 256;

/// Iterator over COM GUIDs from IEnumGUID.  
///
/// # Safety  
/// This struct wraps a COM interface and must be used according to COM rules.  
pub struct GuidIterator {
    inner: windows::Win32::System::Com::IEnumGUID,
    cache: Box<[windows::core::GUID; MAX_CACHE_SIZE]>,
    index: u32,
    count: u32,
    done: bool,
}

impl GuidIterator {
    /// Creates a new iterator from a COM interface.  
    pub fn new(inner: windows::Win32::System::Com::IEnumGUID) -> Self {
        Self {
            inner,
            cache: Box::from([windows::core::GUID::zeroed(); MAX_CACHE_SIZE]),
            index: MAX_CACHE_SIZE as u32,
            count: 0,
            done: false,
        }
    }
}

impl Iterator for GuidIterator {
    type Item = windows::core::Result<windows::core::GUID>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.done {
            return None;
        }

        if self.index >= self.count {
            let code = unsafe {
                self.inner
                    .Next(self.cache.as_mut_slice(), Some(&mut self.count))
            };

            if code.is_ok() {
                if self.count == 0 {
                    self.done = true;
                    return None;
                }

                self.index = 0;
            } else {
                self.done = true;
                return Some(Err(windows::core::Error::new(
                    code,
                    "Failed to get next GUID",
                )));
            }
        }

        let current = self.cache[self.index as usize];
        self.index += 1;
        Some(Ok(current))
    }
}

pub struct StringIterator {
    inner: windows::Win32::System::Com::IEnumString,
    cache: Box<[windows::core::PWSTR; STRING_CACHE_SIZE]>,
    index: u32,
    count: u32,
    done: bool,
}

impl StringIterator {
    pub fn new(inner: windows::Win32::System::Com::IEnumString) -> Self {
        Self {
            inner,
            cache: Box::new([windows::core::PWSTR::null(); STRING_CACHE_SIZE]),
            index: STRING_CACHE_SIZE as u32,
            count: 0,
            done: false,
        }
    }
}

impl Iterator for StringIterator {
    type Item = windows::core::Result<String>;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            if self.done {
                return None;
            }

            if self.index >= self.count {
                // Zero the cache to prevent stale freed pointers (OPC-BUG-001)
                self.cache.fill(windows::core::PWSTR::null());

                let code = unsafe {
                    self.inner
                        .Next(self.cache.as_mut_slice(), Some(&mut self.count))
                };

                tracing::debug!(
                    hresult = format_args!("{:#010X}", code.0),
                    celt = self.cache.len(),
                    fetched = self.count,
                    "StringIterator::Next completed"
                );

                if code.is_ok() {
                    if self.count == 0 {
                        self.done = true;
                        return None;
                    }

                    // Detect null entries in the fetched range
                    let null_count = self.cache[..self.count as usize]
                        .iter()
                        .filter(|p| p.is_null())
                        .count();
                    if null_count > 0 {
                        tracing::warn!(
                            null_count,
                            fetched = self.count,
                            "StringIterator: null PWSTR entries in fetched range"
                        );
                    }

                    self.index = 0;
                } else {
                    self.done = true;
                    return Some(Err(windows::core::Error::new(
                        code,
                        "Failed to get next string",
                    )));
                }
            }

            // Skip null PWSTR entries instead of producing E_POINTER (OPC-BUG-001)
            let pwstr = self.cache[self.index as usize];
            self.index += 1;

            if pwstr.is_null() {
                tracing::debug!(
                    index = self.index - 1,
                    count = self.count,
                    "StringIterator: skipping null PWSTR entry"
                );
                continue; // Loop back to try the next entry
            }

            let current = RemotePointer::from(pwstr);
            return Some(current.try_into());
        }
    }
}

pub struct GroupIterator<Group: TryFrom<windows::core::IUnknown, Error = windows::core::Error>> {
    inner: windows::Win32::System::Com::IEnumUnknown,
    cache: Box<[Option<windows::core::IUnknown>; MAX_CACHE_SIZE]>,
    index: u32,
    count: u32,
    done: bool,
    _mark: std::marker::PhantomData<Group>,
}

impl<Group: TryFrom<windows::core::IUnknown, Error = windows::core::Error>> GroupIterator<Group> {
    pub fn new(inner: windows::Win32::System::Com::IEnumUnknown) -> Self {
        Self {
            inner,
            cache: Box::from([const { None }; MAX_CACHE_SIZE]),
            index: MAX_CACHE_SIZE as u32,
            count: 0,
            done: false,
            _mark: std::marker::PhantomData,
        }
    }
}

impl<Group: TryFrom<windows::core::IUnknown, Error = windows::core::Error>> Iterator
    for GroupIterator<Group>
{
    type Item = windows::core::Result<Group>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.done {
            return None;
        }

        if self.index >= self.count {
            let code = unsafe {
                self.inner
                    .Next(self.cache.as_mut_slice(), Some(&mut self.count))
            };

            if code.is_ok() {
                if self.count == 0 {
                    self.done = true;
                    return None;
                }

                self.index = 0;
            } else {
                self.done = true;
                return Some(Err(windows::core::Error::new(
                    code,
                    "Failed to get next group",
                )));
            }
        }

        let current = self.cache[self.index as usize].take();
        self.index += 1;
        Some(match current {
            Some(group) => group.try_into(),
            None => Err(windows::core::Error::new(
                windows::Win32::Foundation::E_POINTER,
                "Failed to get group, returned null",
            )),
        })
    }
}

// for crate::bindings::da::IEnumOPCItemAttributes
pub struct ItemAttributeIterator {
    inner: crate::bindings::da::IEnumOPCItemAttributes,
    cache: RemoteArray<crate::bindings::da::tagOPCITEMATTRIBUTES>,
    index: u32,
    done: bool,
}

impl ItemAttributeIterator {
    pub fn new(inner: crate::bindings::da::IEnumOPCItemAttributes) -> Self {
        Self {
            inner,
            cache: RemoteArray::empty(),
            index: 0,
            done: false,
        }
    }
}

impl Iterator for ItemAttributeIterator {
    type Item = windows::core::Result<ItemAttributes>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.done {
            return None;
        }

        if self.index >= self.cache.len() {
            let mut attrs = RemoteArray::new(MAX_CACHE_SIZE as u32);

            let result = unsafe {
                self.inner.Next(
                    MAX_CACHE_SIZE as u32,
                    attrs.as_mut_ptr(),
                    attrs.as_mut_len_ptr(),
                )
            };

            match result {
                Ok(_) => {
                    if attrs.is_empty() {
                        self.done = true;
                        return None;
                    }

                    self.cache = attrs;
                    self.index = 0;
                }
                Err(err) => {
                    self.done = true;
                    return Some(Err(err));
                }
            }
        }

        let current = self.cache.as_slice()[self.index as usize].try_to_local();
        self.index += 1;
        Some(current)
    }
}

#[cfg(test)]
mod tests {
    #![allow(
        clippy::ref_as_ptr,
        clippy::inline_always,
        clippy::useless_conversion,
        clippy::needless_range_loop
    )]
    use super::*;
    use windows::Win32::System::Com::{IEnumString, IEnumString_Impl};
    use windows::core::{PWSTR, implement};

    #[allow(clippy::ref_as_ptr, clippy::inline_always)]
    #[implement(IEnumString)]
    struct MockEnumString {
        items: Vec<String>,
        index: std::sync::atomic::AtomicUsize,
    }

    impl IEnumString_Impl for MockEnumString_Impl {
        fn Next(
            &self,
            celt: u32,
            rgelt: *mut PWSTR,
            pceltfetched: *mut u32,
        ) -> windows::core::HRESULT {
            let mut fetched = 0;
            let index = self.index.load(std::sync::atomic::Ordering::Relaxed);
            let rgelt = unsafe { std::slice::from_raw_parts_mut(rgelt, celt as usize) };

            for i in 0..celt as usize {
                if index + i < self.items.len() {
                    let s = &self.items[index + i];
                    let mut w: Vec<u16> = s.encode_utf16().chain(std::iter::once(0)).collect();
                    let ptr = unsafe { windows::Win32::System::Com::CoTaskMemAlloc(w.len() * 2) };
                    unsafe { std::ptr::copy_nonoverlapping(w.as_ptr(), ptr as *mut u16, w.len()) };
                    rgelt[i] = PWSTR(ptr as *mut u16);
                    fetched += 1;
                } else {
                    break;
                }
            }

            self.index
                .store(index + fetched, std::sync::atomic::Ordering::Relaxed);

            if !pceltfetched.is_null() {
                unsafe { *pceltfetched = fetched as u32 };
            }

            if fetched == celt as usize {
                windows::Win32::Foundation::S_OK.into()
            } else {
                windows::Win32::Foundation::S_FALSE.into()
            }
        }
        fn Skip(&self, _celt: u32) -> windows::core::HRESULT {
            windows::Win32::Foundation::E_NOTIMPL.into()
        }
        fn Reset(&self) -> windows::core::Result<()> {
            self.index.store(0, std::sync::atomic::Ordering::Relaxed);
            Ok(())
        }
        fn Clone(&self) -> windows::core::Result<IEnumString> {
            Err(windows::core::Error::from_hresult(
                windows::Win32::Foundation::E_NOTIMPL,
            ))
        }
    }

    #[test]
    fn test_string_iterator_no_phantom_errors() {
        let items = vec![
            "Item1".to_string(),
            "Item2".to_string(),
            "Item3".to_string(),
        ];

        let mock_enum: IEnumString = MockEnumString {
            items: items.clone(),
            index: std::sync::atomic::AtomicUsize::new(0),
        }
        .into();

        let iter = StringIterator::new(mock_enum);

        let mut results = Vec::new();
        for item in iter {
            // Verify no E_POINTER error is yielded
            let value = item.expect("Expected OK value, got phantom error");
            results.push(value);
        }

        assert_eq!(results, items);
    }

    /// Mock that writes only `valid_count` items but claims `pceltFetched = claimed_count`,
    /// leaving the remaining slots as null pointers. Simulates OPC-BUG-001.
    #[allow(clippy::ref_as_ptr, clippy::inline_always)]
    #[implement(IEnumString)]
    struct MockEnumStringWithNulls {
        items: Vec<String>,
        index: std::sync::atomic::AtomicUsize,
        /// How many *extra* null entries to claim beyond actual items
        extra_nulls: u32,
    }

    impl IEnumString_Impl for MockEnumStringWithNulls_Impl {
        fn Next(
            &self,
            celt: u32,
            rgelt: *mut PWSTR,
            pceltfetched: *mut u32,
        ) -> windows::core::HRESULT {
            let mut fetched = 0;
            let index = self.index.load(std::sync::atomic::Ordering::Relaxed);
            let rgelt = unsafe { std::slice::from_raw_parts_mut(rgelt, celt as usize) };

            for i in 0..celt as usize {
                if index + i < self.items.len() {
                    let s = &self.items[index + i];
                    let w: Vec<u16> = s.encode_utf16().chain(std::iter::once(0)).collect();
                    let ptr = unsafe { windows::Win32::System::Com::CoTaskMemAlloc(w.len() * 2) };
                    unsafe { std::ptr::copy_nonoverlapping(w.as_ptr(), ptr as *mut u16, w.len()) };
                    rgelt[i] = PWSTR(ptr as *mut u16);
                    fetched += 1;
                } else {
                    break;
                }
            }

            self.index
                .store(index + fetched, std::sync::atomic::Ordering::Relaxed);

            // Lie about the count: claim extra null entries (only on non-empty batches)
            let reported = if fetched > 0 {
                (fetched as u32) + self.extra_nulls
            } else {
                0
            };
            if !pceltfetched.is_null() {
                unsafe { *pceltfetched = reported.min(celt) };
            }

            if fetched == 0 {
                // Enumeration exhausted
                windows::Win32::Foundation::S_FALSE
            } else if reported >= celt {
                windows::Win32::Foundation::S_OK
            } else {
                windows::Win32::Foundation::S_FALSE
            }
        }
        fn Skip(&self, _celt: u32) -> windows::core::HRESULT {
            windows::Win32::Foundation::E_NOTIMPL
        }
        fn Reset(&self) -> windows::core::Result<()> {
            self.index.store(0, std::sync::atomic::Ordering::Relaxed);
            Ok(())
        }
        fn Clone(&self) -> windows::core::Result<IEnumString> {
            Err(windows::core::Error::from_hresult(
                windows::Win32::Foundation::E_NOTIMPL,
            ))
        }
    }

    /// OPC-BUG-001 regression: null PWSTR entries within the fetched range
    /// must be silently skipped, not yield E_POINTER.
    #[test]
    fn test_string_iterator_null_entries_skipped() {
        let items = vec!["Alpha".to_string(), "Beta".to_string(), "Gamma".to_string()];

        let mock_enum: IEnumString = MockEnumStringWithNulls {
            items: items.clone(),
            index: std::sync::atomic::AtomicUsize::new(0),
            extra_nulls: 5, // Claim 5 extra items that are actually null
        }
        .into();

        let iter = StringIterator::new(mock_enum);

        let mut results = Vec::new();
        for item in iter {
            // No E_POINTER should leak through
            let value = item.expect("Expected OK value, got phantom error from null entry");
            results.push(value);
        }

        assert_eq!(
            results, items,
            "Only valid items should be yielded, nulls skipped"
        );
    }

    /// Verify iterator handles a fully empty enumeration (0 items, immediate S_FALSE).
    #[test]
    fn test_string_iterator_empty() {
        let mock_enum: IEnumString = MockEnumString {
            items: Vec::new(),
            index: std::sync::atomic::AtomicUsize::new(0),
        }
        .into();

        let iter = StringIterator::new(mock_enum);
        let results: Vec<_> = iter.collect::<Result<Vec<_>, _>>().unwrap();
        assert!(results.is_empty(), "Empty iterator should yield no items");
    }
}