xll-utils 0.1.0

PE/COFF parsing and export verification utilities for Excel XLL development
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
708
//! Windows registry integration for Excel XLL management.
//!
//! This module provides functions for finding registered XLLs,
//! querying the Excel installation path, and managing XLL registration
//! via the Windows registry.
//!
//! # Registry layout
//!
//! Excel stores XLL auto-open registrations under:
//!
//! ```text
//! HKCU\Software\Microsoft\Office\<version>\Excel\Options
//!   OPEN    = "/R \"C:\path\to\first.xll\""
//!   OPEN1   = "/R \"C:\path\to\second.xll\""
//!   OPEN2   = "/R \"C:\path\to\third.xll\""
//! ```
//!
//! The first entry uses the bare name `OPEN`, subsequent entries use
//! `OPEN1`, `OPEN2`, etc.  The value data is a `REG_SZ` string of the
//! form `/R "path"`.
//!
//! # Supported Office versions
//!
//! | Version string | Product                        |
//! |----------------|--------------------------------|
//! | `16.0`         | Office 2016 / 2019 / 2021 / 365 |
//! | `15.0`         | Office 2013                    |
//! | `14.0`         | Office 2010                    |

use std::path::PathBuf;

use windows::core::HSTRING;
use windows::core::PWSTR;
use windows::Win32::Foundation::{
    ERROR_FILE_NOT_FOUND, ERROR_MORE_DATA, ERROR_NO_MORE_ITEMS, ERROR_SUCCESS, WIN32_ERROR,
};
use windows::Win32::System::Registry::{
    RegCloseKey, RegDeleteValueW, RegEnumValueW, RegOpenKeyExW, RegQueryValueExW, RegSetValueExW,
    HKEY, HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, KEY_QUERY_VALUE, KEY_READ, KEY_WRITE, REG_SZ,
    REG_SAM_FLAGS, REG_VALUE_TYPE,
};

use crate::error::{Error, Result};

// ---------------------------------------------------------------------------
// Office version constants
// ---------------------------------------------------------------------------

/// Known Office version strings, ordered newest-first.
pub const OFFICE_VERSIONS: &[&str] = &["16.0", "15.0", "14.0"];

/// Registry sub-path template.  `{}` is replaced with the version string.
const OPTIONS_SUBKEY_TEMPLATE: &str = r"Software\Microsoft\Office\{}\Excel\Options";

/// Registry sub-path template for the Excel install root.
const INSTALL_ROOT_TEMPLATE: &str = r"Software\Microsoft\Office\{}\Excel\InstallRoot";

// ---------------------------------------------------------------------------
// RAII wrapper for HKEY
// ---------------------------------------------------------------------------

/// A thin RAII wrapper around an open `HKEY` that calls `RegCloseKey` on drop.
struct RegKey(HKEY);

impl Drop for RegKey {
    fn drop(&mut self) {
        if !self.0.is_invalid() {
            unsafe {
                let _ = RegCloseKey(self.0);
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------

/// Build the `Software\Microsoft\Office\<ver>\Excel\Options` path.
fn options_subkey(version: &str) -> String {
    OPTIONS_SUBKEY_TEMPLATE.replace("{}", version)
}

/// Build the `Software\Microsoft\Office\<ver>\Excel\InstallRoot` path.
fn install_root_subkey(version: &str) -> String {
    INSTALL_ROOT_TEMPLATE.replace("{}", version)
}

/// Convert a `WIN32_ERROR` into our crate `Error`.
fn win_err(code: WIN32_ERROR, context: &str) -> Error {
    Error::Registry(format!("{context} (error code {0})", code.0))
}

/// Open a registry key under the given root with the requested access rights.
///
/// Returns `Ok(None)` when the key does not exist (`ERROR_FILE_NOT_FOUND`).
fn open_key(root: HKEY, subkey: &str, access: u32) -> Result<Option<RegKey>> {
    let subkey_h = HSTRING::from(subkey);
    let mut result_key = HKEY::default();

    let status = unsafe {
        RegOpenKeyExW(
            root,
            &subkey_h,
            0, // reserved / options
            REG_SAM_FLAGS(access),
            &mut result_key,
        )
    };

    if status == ERROR_SUCCESS {
        Ok(Some(RegKey(result_key)))
    } else if status == ERROR_FILE_NOT_FOUND {
        Ok(None)
    } else {
        Err(win_err(status, &format!("RegOpenKeyExW({subkey})")))
    }
}

/// Query a `REG_SZ` string value from an open key.
///
/// Returns `Ok(None)` when the value does not exist.
fn query_string(key: HKEY, value_name: &str) -> Result<Option<String>> {
    let name_h = HSTRING::from(value_name);
    let mut value_type = REG_VALUE_TYPE::default();
    let mut size_bytes: u32 = 0;

    // First call: determine required buffer size.
    let status = unsafe {
        RegQueryValueExW(
            key,
            &name_h,
            None,
            Some(&mut value_type),
            None,
            Some(&mut size_bytes),
        )
    };

    if status == ERROR_FILE_NOT_FOUND {
        return Ok(None);
    }
    if status != ERROR_SUCCESS && status != ERROR_MORE_DATA {
        return Err(win_err(status, &format!("RegQueryValueExW({value_name}) size")));
    }
    if value_type != REG_SZ {
        return Err(Error::Registry(format!(
            "Expected REG_SZ for '{value_name}', got type {}",
            value_type.0
        )));
    }

    // Allocate a u16 buffer (size_bytes includes the null terminator in bytes).
    let len_u16 = (size_bytes as usize) / 2;
    let mut buf: Vec<u16> = vec![0u16; len_u16];

    let status = unsafe {
        RegQueryValueExW(
            key,
            &name_h,
            None,
            Some(&mut value_type),
            Some(buf.as_mut_ptr().cast()),
            Some(&mut size_bytes),
        )
    };

    if status != ERROR_SUCCESS {
        return Err(win_err(status, &format!("RegQueryValueExW({value_name}) data")));
    }

    // Trim the trailing null(s).
    let end = buf.iter().position(|&c| c == 0).unwrap_or(buf.len());
    Ok(Some(String::from_utf16_lossy(&buf[..end])))
}

/// Set a `REG_SZ` string value on an open key.
fn set_string(key: HKEY, value_name: &str, data: &str) -> Result<()> {
    let name_h = HSTRING::from(value_name);
    let data_h = HSTRING::from(data);

    // Build the byte slice expected by RegSetValueExW.
    // The data must include the null terminator.  HSTRING is always
    // null-terminated, so we can include the trailing null in the slice.
    let wide: &[u16] = data_h.as_wide();
    // We need to include the null terminator -- build a Vec with it.
    let mut wide_with_null: Vec<u16> = wide.to_vec();
    wide_with_null.push(0);
    let byte_len = wide_with_null.len() * 2;
    let bytes: &[u8] =
        unsafe { std::slice::from_raw_parts(wide_with_null.as_ptr().cast(), byte_len) };

    let status = unsafe { RegSetValueExW(key, &name_h, 0, REG_SZ, Some(bytes)) };

    if status != ERROR_SUCCESS {
        return Err(win_err(status, &format!("RegSetValueExW({value_name})")));
    }
    Ok(())
}

/// Delete a value from an open key.  Returns `Ok(false)` if the value did not
/// exist.
fn delete_value(key: HKEY, value_name: &str) -> Result<bool> {
    let name_h = HSTRING::from(value_name);

    let status = unsafe { RegDeleteValueW(key, &name_h) };

    if status == ERROR_SUCCESS {
        Ok(true)
    } else if status == ERROR_FILE_NOT_FOUND {
        Ok(false)
    } else {
        Err(win_err(status, &format!("RegDeleteValueW({value_name})")))
    }
}

/// Enumerate all values of an open key, returning `(name, data)` pairs for
/// `REG_SZ` values only.
fn enumerate_string_values(key: HKEY) -> Result<Vec<(String, String)>> {
    let mut results = Vec::new();
    let mut index: u32 = 0;

    // Buffers reused across iterations.
    let mut name_buf: Vec<u16> = vec![0u16; 256];
    // Use Vec<u16> for data to avoid alignment issues when casting u8 -> u16.
    let mut data_buf: Vec<u16> = vec![0u16; 512];

    loop {
        let mut name_len = name_buf.len() as u32; // in u16 characters
        let mut data_len = (data_buf.len() * 2) as u32; // in bytes
        let mut value_type: u32 = 0;

        let status = unsafe {
            RegEnumValueW(
                key,
                index,
                PWSTR(name_buf.as_mut_ptr()),
                &mut name_len,
                None,
                Some(&mut value_type),
                Some(data_buf.as_mut_ptr().cast()),
                Some(&mut data_len),
            )
        };

        if status == ERROR_NO_MORE_ITEMS {
            break;
        }

        if status == ERROR_MORE_DATA {
            // Grow buffers and retry the same index.
            name_buf.resize(name_buf.len() * 2, 0);
            data_buf.resize(data_buf.len() * 2, 0);
            continue;
        }

        if status != ERROR_SUCCESS {
            return Err(win_err(status, "RegEnumValueW"));
        }

        // Only collect REG_SZ values.
        if REG_VALUE_TYPE(value_type) == REG_SZ {
            let name = String::from_utf16_lossy(&name_buf[..name_len as usize]);

            // data_len is in bytes; convert to u16 count and trim null.
            let data_u16_len = (data_len as usize) / 2;
            let end = data_buf[..data_u16_len]
                .iter()
                .position(|&c| c == 0)
                .unwrap_or(data_u16_len);
            let data = String::from_utf16_lossy(&data_buf[..end]);

            results.push((name, data));
        }

        index += 1;
    }

    Ok(results)
}

// ---------------------------------------------------------------------------
// XLL path extraction helpers
// ---------------------------------------------------------------------------

/// Parse the XLL path from an OPEN value such as `/R "C:\path\to\my.xll"`.
fn parse_open_value(value: &str) -> Option<PathBuf> {
    let trimmed = value.trim();
    // The canonical form is:  /R "path"
    let path_str = if let Some(rest) = trimmed.strip_prefix("/R") {
        rest.trim().trim_matches('"')
    } else {
        // Some entries may just be the bare path (with or without quotes).
        trimmed.trim_matches('"')
    };

    if path_str.is_empty() {
        None
    } else {
        Some(PathBuf::from(path_str))
    }
}

/// Check if a registry value name is an OPEN entry (OPEN, OPEN1, OPEN2, ...).
fn is_open_value_name(name: &str) -> bool {
    let upper = name.to_uppercase();
    upper == "OPEN" || (upper.starts_with("OPEN") && upper[4..].parse::<u32>().is_ok())
}

/// Generate the OPEN value name for a given zero-based index.
///
/// Index 0 -> "OPEN", 1 -> "OPEN1", 2 -> "OPEN2", ...
fn open_value_name(index: usize) -> String {
    if index == 0 {
        "OPEN".to_string()
    } else {
        format!("OPEN{index}")
    }
}

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// A registered XLL entry found in the Windows registry.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RegisteredXll {
    /// The registry root (HKCU or HKLM).
    pub hive: RegistryHive,
    /// The Office version key (e.g., "16.0").
    pub office_version: String,
    /// The OPEN value name (e.g., "OPEN", "OPEN1").
    pub value_name: String,
    /// The raw value data (e.g., `/R "C:\path\to\xll"`).
    pub raw_value: String,
    /// The extracted XLL file path.
    pub xll_path: PathBuf,
}

/// Which registry hive the entry was found in.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum RegistryHive {
    CurrentUser,
    LocalMachine,
}

impl std::fmt::Display for RegistryHive {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            RegistryHive::CurrentUser => write!(f, "HKCU"),
            RegistryHive::LocalMachine => write!(f, "HKLM"),
        }
    }
}

impl RegistryHive {
    fn hkey(self) -> HKEY {
        match self {
            RegistryHive::CurrentUser => HKEY_CURRENT_USER,
            RegistryHive::LocalMachine => HKEY_LOCAL_MACHINE,
        }
    }
}

/// Detect which Office versions have an `Excel\Options` key present in the
/// registry.
///
/// Checks both HKCU and HKLM for every version in [`OFFICE_VERSIONS`].
/// Returns the list of `(hive, version)` pairs found.
pub fn detect_office_versions() -> Result<Vec<(RegistryHive, String)>> {
    let mut found = Vec::new();

    for &version in OFFICE_VERSIONS {
        let subkey = options_subkey(version);
        for &hive in &[RegistryHive::CurrentUser, RegistryHive::LocalMachine] {
            if let Some(_key) = open_key(hive.hkey(), &subkey, KEY_QUERY_VALUE.0)? {
                found.push((hive, version.to_string()));
            }
        }
    }

    Ok(found)
}

/// Find all registered XLLs across all known Office versions in HKCU.
///
/// This scans the `OPEN`, `OPEN1`, `OPEN2`, ... values under each version's
/// `Excel\Options` key.
pub fn find_registered_xlls() -> Result<Vec<RegisteredXll>> {
    find_registered_xlls_in_hive(RegistryHive::CurrentUser)
}

/// Find all registered XLLs in a specific registry hive.
pub fn find_registered_xlls_in_hive(hive: RegistryHive) -> Result<Vec<RegisteredXll>> {
    let mut results = Vec::new();

    for &version in OFFICE_VERSIONS {
        let subkey = options_subkey(version);
        let key = match open_key(hive.hkey(), &subkey, KEY_READ.0)? {
            Some(k) => k,
            None => continue,
        };

        // Enumerate all values; filter to OPEN* names.
        let values = enumerate_string_values(key.0)?;
        for (name, data) in values {
            if is_open_value_name(&name) {
                if let Some(path) = parse_open_value(&data) {
                    results.push(RegisteredXll {
                        hive,
                        office_version: version.to_string(),
                        value_name: name,
                        raw_value: data,
                        xll_path: path,
                    });
                }
            }
        }
    }

    Ok(results)
}

/// Find registered XLLs for a specific Office version.
pub fn find_registered_xlls_for_version(
    hive: RegistryHive,
    version: &str,
) -> Result<Vec<RegisteredXll>> {
    let subkey = options_subkey(version);
    let key = match open_key(hive.hkey(), &subkey, KEY_READ.0)? {
        Some(k) => k,
        None => return Ok(Vec::new()),
    };

    let values = enumerate_string_values(key.0)?;
    let mut results = Vec::new();
    for (name, data) in values {
        let upper = name.to_uppercase();
        if upper == "OPEN" || (upper.starts_with("OPEN") && upper[4..].parse::<u32>().is_ok()) {
            if let Some(path) = parse_open_value(&data) {
                results.push(RegisteredXll {
                    hive,
                    office_version: version.to_string(),
                    value_name: name,
                    raw_value: data,
                    xll_path: path,
                });
            }
        }
    }
    Ok(results)
}

/// Register an XLL for a specific Office version.
///
/// Creates the appropriate `OPEN` / `OPEN<n>` value under the version's
/// `Excel\Options` key in HKCU.  The function automatically picks the next
/// available OPEN index.
///
/// The `xll_path` should be an absolute path to the XLL file.
pub fn register_xll(version: &str, xll_path: &std::path::Path) -> Result<String> {
    let subkey = options_subkey(version);
    let key = open_key(HKEY_CURRENT_USER, &subkey, KEY_READ.0 | KEY_WRITE.0)?
        .ok_or_else(|| {
            Error::Registry(format!(
                "Office {version} Options key not found: {subkey}"
            ))
        })?;

    // Check if this XLL is already registered.
    let existing = enumerate_string_values(key.0)?;
    let target_lower = xll_path.to_string_lossy().to_lowercase();
    for (name, data) in &existing {
        if is_open_value_name(name) {
            if let Some(path) = parse_open_value(data) {
                if path.to_string_lossy().to_lowercase() == target_lower {
                    // Already registered under this value name.
                    return Ok(name.clone());
                }
            }
        }
    }

    // Determine the next free OPEN index.
    let mut used_indices: Vec<usize> = Vec::new();
    for (name, _) in &existing {
        let upper = name.to_uppercase();
        if upper == "OPEN" {
            used_indices.push(0);
        } else if let Some(suffix) = upper.strip_prefix("OPEN") {
            if let Ok(n) = suffix.parse::<usize>() {
                used_indices.push(n);
            }
        }
    }

    let next_index = if used_indices.is_empty() {
        0
    } else {
        // Find the first gap, or use max+1.
        used_indices.sort_unstable();
        let mut idx = 0usize;
        for &used in &used_indices {
            if used != idx {
                break;
            }
            idx = used + 1;
        }
        idx
    };

    let value_name = open_value_name(next_index);
    let path_str = xll_path.to_string_lossy();
    let value_data = format!("/R \"{path_str}\"");

    set_string(key.0, &value_name, &value_data)?;

    Ok(value_name)
}

/// Unregister an XLL by removing its OPEN value.
///
/// Searches for a value whose path matches `xll_path` (case-insensitive) and
/// removes it.  After removal, the remaining OPEN values are compacted to
/// maintain contiguous numbering (OPEN, OPEN1, OPEN2, ...) as Excel expects.
///
/// Returns `Ok(true)` if a matching registration was found and removed,
/// `Ok(false)` otherwise.
pub fn unregister_xll(version: &str, xll_path: &std::path::Path) -> Result<bool> {
    let subkey = options_subkey(version);
    let key = match open_key(HKEY_CURRENT_USER, &subkey, KEY_READ.0 | KEY_WRITE.0)? {
        Some(k) => k,
        None => return Ok(false),
    };

    let values = enumerate_string_values(key.0)?;
    let target = xll_path.to_string_lossy().to_lowercase();

    // Collect all OPEN entries, noting which one to remove.
    let mut open_entries: Vec<(String, String)> = Vec::new();
    let mut found_index: Option<usize> = None;

    for (name, data) in &values {
        if is_open_value_name(name) {
            if found_index.is_none() {
                if let Some(path) = parse_open_value(data) {
                    if path.to_string_lossy().to_lowercase() == target {
                        found_index = Some(open_entries.len());
                    }
                }
            }
            open_entries.push((name.clone(), data.clone()));
        }
    }

    let remove_idx = match found_index {
        Some(idx) => idx,
        None => return Ok(false),
    };

    // Delete all existing OPEN values, then rewrite without the removed entry
    // using contiguous naming.
    for (name, _) in &open_entries {
        delete_value(key.0, name)?;
    }

    open_entries.remove(remove_idx);

    for (i, (_, data)) in open_entries.iter().enumerate() {
        set_string(key.0, &open_value_name(i), data)?;
    }

    Ok(true)
}

/// Query the Excel installation path from the registry.
///
/// Looks under `HKLM\Software\Microsoft\Office\<version>\Excel\InstallRoot`
/// for the `Path` value.
pub fn query_excel_install_path(version: &str) -> Result<Option<PathBuf>> {
    let subkey = install_root_subkey(version);

    // Try HKLM first (typical for machine-wide installs).
    if let Some(key) = open_key(HKEY_LOCAL_MACHINE, &subkey, KEY_QUERY_VALUE.0)? {
        if let Some(path_str) = query_string(key.0, "Path")? {
            return Ok(Some(PathBuf::from(path_str)));
        }
    }

    // Fall back to HKCU (per-user / Click-to-Run installs).
    if let Some(key) = open_key(HKEY_CURRENT_USER, &subkey, KEY_QUERY_VALUE.0)? {
        if let Some(path_str) = query_string(key.0, "Path")? {
            return Ok(Some(PathBuf::from(path_str)));
        }
    }

    Ok(None)
}

/// Detect the Excel installation path, trying all known Office versions.
///
/// Returns the first match found (newest version first).
pub fn detect_excel_path() -> Result<Option<(String, PathBuf)>> {
    for &version in OFFICE_VERSIONS {
        if let Some(path) = query_excel_install_path(version)? {
            return Ok(Some((version.to_string(), path)));
        }
    }
    Ok(None)
}

/// Check whether a specific XLL path is registered under the given version.
pub fn is_xll_registered(
    hive: RegistryHive,
    version: &str,
    xll_path: &std::path::Path,
) -> Result<bool> {
    let entries = find_registered_xlls_for_version(hive, version)?;
    let target = xll_path.to_string_lossy().to_lowercase();

    Ok(entries
        .iter()
        .any(|e| e.xll_path.to_string_lossy().to_lowercase() == target))
}

// ---------------------------------------------------------------------------
// Unit tests (non-registry, pure logic tests)
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_options_subkey() {
        assert_eq!(
            options_subkey("16.0"),
            r"Software\Microsoft\Office\16.0\Excel\Options"
        );
        assert_eq!(
            options_subkey("14.0"),
            r"Software\Microsoft\Office\14.0\Excel\Options"
        );
    }

    #[test]
    fn test_install_root_subkey() {
        assert_eq!(
            install_root_subkey("16.0"),
            r"Software\Microsoft\Office\16.0\Excel\InstallRoot"
        );
    }

    #[test]
    fn test_parse_open_value_standard() {
        let v = parse_open_value(r#"/R "C:\addins\my.xll""#);
        assert_eq!(v, Some(PathBuf::from(r"C:\addins\my.xll")));
    }

    #[test]
    fn test_parse_open_value_no_quotes() {
        let v = parse_open_value(r"/R C:\addins\my.xll");
        assert_eq!(v, Some(PathBuf::from(r"C:\addins\my.xll")));
    }

    #[test]
    fn test_parse_open_value_bare_path() {
        let v = parse_open_value(r#""C:\addins\my.xll""#);
        assert_eq!(v, Some(PathBuf::from(r"C:\addins\my.xll")));
    }

    #[test]
    fn test_parse_open_value_empty() {
        assert_eq!(parse_open_value(""), None);
        assert_eq!(parse_open_value("/R "), None);
        assert_eq!(parse_open_value(r#"/R """#), None);
    }

    #[test]
    fn test_open_value_name() {
        assert_eq!(open_value_name(0), "OPEN");
        assert_eq!(open_value_name(1), "OPEN1");
        assert_eq!(open_value_name(2), "OPEN2");
        assert_eq!(open_value_name(10), "OPEN10");
    }

    #[test]
    fn test_registry_hive_display() {
        assert_eq!(format!("{}", RegistryHive::CurrentUser), "HKCU");
        assert_eq!(format!("{}", RegistryHive::LocalMachine), "HKLM");
    }

    #[test]
    fn test_is_open_value_name() {
        assert!(is_open_value_name("OPEN"));
        assert!(is_open_value_name("OPEN1"));
        assert!(is_open_value_name("OPEN2"));
        assert!(is_open_value_name("OPEN10"));
        assert!(is_open_value_name("open")); // case-insensitive
        assert!(is_open_value_name("Open1"));
        assert!(!is_open_value_name("OPENED"));
        assert!(!is_open_value_name("OPENx"));
        assert!(!is_open_value_name(""));
        assert!(!is_open_value_name("CLOSE"));
    }
}