summaryrefslogtreecommitdiffstats
path: root/third_party/rust/winreg/examples
diff options
context:
space:
mode:
Diffstat (limited to 'third_party/rust/winreg/examples')
-rw-r--r--third_party/rust/winreg/examples/basic_usage.rs69
-rw-r--r--third_party/rust/winreg/examples/enum.rs27
-rw-r--r--third_party/rust/winreg/examples/installed_apps.rs50
-rw-r--r--third_party/rust/winreg/examples/load_app_key.rs26
-rw-r--r--third_party/rust/winreg/examples/map_key_serialization.rs57
-rw-r--r--third_party/rust/winreg/examples/serialization.rs93
-rw-r--r--third_party/rust/winreg/examples/transactions.rs35
7 files changed, 357 insertions, 0 deletions
diff --git a/third_party/rust/winreg/examples/basic_usage.rs b/third_party/rust/winreg/examples/basic_usage.rs
new file mode 100644
index 0000000000..6422e9eeb2
--- /dev/null
+++ b/third_party/rust/winreg/examples/basic_usage.rs
@@ -0,0 +1,69 @@
+// Copyright 2015, Igor Shaula
+// Licensed under the MIT License <LICENSE or
+// http://opensource.org/licenses/MIT>. This file
+// may not be copied, modified, or distributed
+// except according to those terms.
+extern crate winreg;
+use std::io;
+use std::path::Path;
+use winreg::enums::*;
+use winreg::RegKey;
+
+fn main() -> io::Result<()> {
+ println!("Reading some system info...");
+ let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
+ let cur_ver = hklm.open_subkey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion")?;
+ let pf: String = cur_ver.get_value("ProgramFilesDir")?;
+ let dp: String = cur_ver.get_value("DevicePath")?;
+ println!("ProgramFiles = {}\nDevicePath = {}", pf, dp);
+ let info = cur_ver.query_info()?;
+ println!("info = {:?}", info);
+ let mt = info.get_last_write_time_system();
+ println!(
+ "last_write_time as winapi::um::minwinbase::SYSTEMTIME = {}-{:02}-{:02} {:02}:{:02}:{:02}",
+ mt.wYear, mt.wMonth, mt.wDay, mt.wHour, mt.wMinute, mt.wSecond
+ );
+ println!(
+ "last_write_time as chrono::NaiveDateTime = {}",
+ info.get_last_write_time_chrono()
+ );
+
+ println!("And now lets write something...");
+ let hkcu = RegKey::predef(HKEY_CURRENT_USER);
+ let path = Path::new("Software").join("WinregRsExample1");
+ let (key, disp) = hkcu.create_subkey(&path)?;
+
+ match disp {
+ REG_CREATED_NEW_KEY => println!("A new key has been created"),
+ REG_OPENED_EXISTING_KEY => println!("An existing key has been opened"),
+ }
+
+ key.set_value("TestSZ", &"written by Rust")?;
+ let sz_val: String = key.get_value("TestSZ")?;
+ key.delete_value("TestSZ")?;
+ println!("TestSZ = {}", sz_val);
+
+ key.set_value("TestMultiSZ", &vec!["written", "by", "Rust"])?;
+ let multi_sz_val: Vec<String> = key.get_value("TestMultiSZ")?;
+ key.delete_value("TestMultiSZ")?;
+ println!("TestMultiSZ = {:?}", multi_sz_val);
+
+ key.set_value("TestDWORD", &1_234_567_890u32)?;
+ let dword_val: u32 = key.get_value("TestDWORD")?;
+ println!("TestDWORD = {}", dword_val);
+
+ key.set_value("TestQWORD", &1_234_567_891_011_121_314u64)?;
+ let qword_val: u64 = key.get_value("TestQWORD")?;
+ println!("TestQWORD = {}", qword_val);
+
+ key.create_subkey("sub\\key")?;
+ hkcu.delete_subkey_all(&path)?;
+
+ println!("Trying to open nonexistent key...");
+ hkcu.open_subkey(&path).unwrap_or_else(|e| match e.kind() {
+ io::ErrorKind::NotFound => panic!("Key doesn't exist"),
+ io::ErrorKind::PermissionDenied => panic!("Access denied"),
+ _ => panic!("{:?}", e),
+ });
+ Ok(())
+}
diff --git a/third_party/rust/winreg/examples/enum.rs b/third_party/rust/winreg/examples/enum.rs
new file mode 100644
index 0000000000..dd1a78d870
--- /dev/null
+++ b/third_party/rust/winreg/examples/enum.rs
@@ -0,0 +1,27 @@
+// Copyright 2015, Igor Shaula
+// Licensed under the MIT License <LICENSE or
+// http://opensource.org/licenses/MIT>. This file
+// may not be copied, modified, or distributed
+// except according to those terms.
+extern crate winreg;
+use std::io;
+use winreg::enums::*;
+use winreg::RegKey;
+
+fn main() -> io::Result<()> {
+ println!("File extensions, registered in system:");
+ for i in RegKey::predef(HKEY_CLASSES_ROOT)
+ .enum_keys()
+ .map(|x| x.unwrap())
+ .filter(|x| x.starts_with('.'))
+ {
+ println!("{}", i);
+ }
+
+ let system = RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey("HARDWARE\\DESCRIPTION\\System")?;
+ for (name, value) in system.enum_values().map(|x| x.unwrap()) {
+ println!("{} = {:?}", name, value);
+ }
+
+ Ok(())
+}
diff --git a/third_party/rust/winreg/examples/installed_apps.rs b/third_party/rust/winreg/examples/installed_apps.rs
new file mode 100644
index 0000000000..a7546847db
--- /dev/null
+++ b/third_party/rust/winreg/examples/installed_apps.rs
@@ -0,0 +1,50 @@
+// Copyright 2017, Igor Shaula
+// Licensed under the MIT License <LICENSE or
+// http://opensource.org/licenses/MIT>. This file
+// may not be copied, modified, or distributed
+// except according to those terms.
+#[macro_use]
+extern crate serde_derive;
+extern crate winreg;
+use std::collections::HashMap;
+use std::fmt;
+use winreg::enums::*;
+
+#[allow(non_snake_case)]
+#[derive(Debug, Serialize, Deserialize)]
+struct InstalledApp {
+ DisplayName: Option<String>,
+ DisplayVersion: Option<String>,
+ UninstallString: Option<String>,
+}
+
+macro_rules! str_from_opt {
+ ($s:expr) => {
+ $s.as_ref().map(|x| &**x).unwrap_or("")
+ };
+}
+
+impl fmt::Display for InstalledApp {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ write!(
+ f,
+ "{}-{}",
+ str_from_opt!(self.DisplayName),
+ str_from_opt!(self.DisplayVersion)
+ )
+ }
+}
+
+fn main() {
+ let hklm = winreg::RegKey::predef(HKEY_LOCAL_MACHINE);
+ let uninstall_key = hklm
+ .open_subkey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall")
+ .expect("key is missing");
+
+ let apps: HashMap<String, InstalledApp> =
+ uninstall_key.decode().expect("deserialization failed");
+
+ for v in apps.values() {
+ println!("{}", v);
+ }
+}
diff --git a/third_party/rust/winreg/examples/load_app_key.rs b/third_party/rust/winreg/examples/load_app_key.rs
new file mode 100644
index 0000000000..2340c82b59
--- /dev/null
+++ b/third_party/rust/winreg/examples/load_app_key.rs
@@ -0,0 +1,26 @@
+// Copyright 2021, Igor Shaula
+// Licensed under the MIT License <LICENSE or
+// http://opensource.org/licenses/MIT>. This file
+// may not be copied, modified, or distributed
+// except according to those terms.
+extern crate winreg;
+use std::io;
+use winreg::enums::*;
+use winreg::RegKey;
+
+fn main() -> io::Result<()> {
+ {
+ // put this in a block so app_key_1 gets out of scope and doesn't prevent us
+ // from loading the key again later
+ let app_key_1 = RegKey::load_app_key("myhive.dat", true)?;
+ app_key_1.set_value("answer", &42u32)?;
+ }
+ let answer: u32 = {
+ // NOTE: on Windows 7 this fails with ERROR_ALREADY_EXISTS
+ let app_key_2 =
+ RegKey::load_app_key_with_flags("myhive.dat", KEY_READ, REG_PROCESS_APPKEY)?;
+ app_key_2.get_value("answer")?
+ };
+ println!("The Answer is {}", answer);
+ Ok(())
+}
diff --git a/third_party/rust/winreg/examples/map_key_serialization.rs b/third_party/rust/winreg/examples/map_key_serialization.rs
new file mode 100644
index 0000000000..c0be704913
--- /dev/null
+++ b/third_party/rust/winreg/examples/map_key_serialization.rs
@@ -0,0 +1,57 @@
+// Copyright 2020, Igor Shaula
+// Licensed under the MIT License <LICENSE or
+// http://opensource.org/licenses/MIT>. This file
+// may not be copied, modified, or distributed
+// except according to those terms.
+#[macro_use]
+extern crate serde_derive;
+extern crate winreg;
+use std::collections::HashMap;
+use std::error::Error;
+use winreg::enums::*;
+
+#[derive(Debug, Serialize, Deserialize, PartialEq)]
+struct Coords {
+ x: u32,
+ y: u32,
+}
+
+#[derive(Debug, Serialize, Deserialize, PartialEq)]
+struct Size {
+ w: u32,
+ h: u32,
+}
+
+#[derive(Debug, Serialize, Deserialize, PartialEq)]
+struct Rectangle {
+ coords: Coords,
+ size: Size,
+}
+
+fn main() -> Result<(), Box<dyn Error>> {
+ let hkcu = winreg::RegKey::predef(HKEY_CURRENT_USER);
+ let (key, _disp) = hkcu.create_subkey("Software\\RustEncodeMapKey")?;
+ let mut v1 = HashMap::new();
+ v1.insert(
+ "first".to_owned(),
+ Rectangle {
+ coords: Coords { x: 55, y: 77 },
+ size: Size { w: 500, h: 300 },
+ },
+ );
+ v1.insert(
+ "second".to_owned(),
+ Rectangle {
+ coords: Coords { x: 11, y: 22 },
+ size: Size { w: 1000, h: 600 },
+ },
+ );
+
+ key.encode(&v1)?;
+
+ let v2: HashMap<String, Rectangle> = key.decode()?;
+ println!("Decoded {:?}", v2);
+
+ println!("Equal to encoded: {:?}", v1 == v2);
+ Ok(())
+}
diff --git a/third_party/rust/winreg/examples/serialization.rs b/third_party/rust/winreg/examples/serialization.rs
new file mode 100644
index 0000000000..462813291a
--- /dev/null
+++ b/third_party/rust/winreg/examples/serialization.rs
@@ -0,0 +1,93 @@
+// Copyright 2015, Igor Shaula
+// Licensed under the MIT License <LICENSE or
+// http://opensource.org/licenses/MIT>. This file
+// may not be copied, modified, or distributed
+// except according to those terms.
+#[macro_use]
+extern crate serde_derive;
+extern crate winreg;
+use std::collections::HashMap;
+use std::error::Error;
+use winreg::enums::*;
+
+#[derive(Debug, Serialize, Deserialize, PartialEq)]
+struct Coords {
+ x: u32,
+ y: u32,
+}
+
+#[derive(Debug, Serialize, Deserialize, PartialEq)]
+struct Size {
+ w: u32,
+ h: u32,
+}
+
+#[derive(Debug, Serialize, Deserialize, PartialEq)]
+struct Rectangle {
+ coords: Coords,
+ size: Size,
+}
+
+#[derive(Debug, Serialize, Deserialize, PartialEq)]
+struct Test {
+ t_bool: bool,
+ t_u8: u8,
+ t_u16: u16,
+ t_u32: u32,
+ t_u64: u64,
+ t_usize: usize,
+ t_struct: Rectangle,
+ t_map: HashMap<String, u32>,
+ t_string: String,
+ #[serde(rename = "")] // empty name becomes the (Default) value in the registry
+ t_char: char,
+ t_i8: i8,
+ t_i16: i16,
+ t_i32: i32,
+ t_i64: i64,
+ t_isize: isize,
+ t_f64: f64,
+ t_f32: f32,
+}
+
+fn main() -> Result<(), Box<dyn Error>> {
+ let hkcu = winreg::RegKey::predef(HKEY_CURRENT_USER);
+ let (key, _disp) = hkcu.create_subkey("Software\\RustEncode")?;
+
+ let mut map = HashMap::new();
+ map.insert("".to_owned(), 0); // empty name becomes the (Default) value in the registry
+ map.insert("v1".to_owned(), 1);
+ map.insert("v2".to_owned(), 2);
+ map.insert("v3".to_owned(), 3);
+
+ let v1 = Test {
+ t_bool: false,
+ t_u8: 127,
+ t_u16: 32768,
+ t_u32: 123_456_789,
+ t_u64: 123_456_789_101_112,
+ t_usize: 1_234_567_891,
+ t_struct: Rectangle {
+ coords: Coords { x: 55, y: 77 },
+ size: Size { w: 500, h: 300 },
+ },
+ t_map: map,
+ t_string: "test 123!".to_owned(),
+ t_char: 'a',
+ t_i8: -123,
+ t_i16: -2049,
+ t_i32: 20100,
+ t_i64: -12_345_678_910,
+ t_isize: -1_234_567_890,
+ t_f64: -0.01,
+ t_f32: 3.15,
+ };
+
+ key.encode(&v1)?;
+
+ let v2: Test = key.decode()?;
+ println!("Decoded {:?}", v2);
+
+ println!("Equal to encoded: {:?}", v1 == v2);
+ Ok(())
+}
diff --git a/third_party/rust/winreg/examples/transactions.rs b/third_party/rust/winreg/examples/transactions.rs
new file mode 100644
index 0000000000..4cc91b7c9f
--- /dev/null
+++ b/third_party/rust/winreg/examples/transactions.rs
@@ -0,0 +1,35 @@
+// Copyright 2015, Igor Shaula
+// Licensed under the MIT License <LICENSE or
+// http://opensource.org/licenses/MIT>. This file
+// may not be copied, modified, or distributed
+// except according to those terms.
+extern crate winreg;
+use std::io;
+use winreg::enums::*;
+use winreg::transaction::Transaction;
+use winreg::RegKey;
+
+fn main() -> io::Result<()> {
+ let t = Transaction::new()?;
+ let hkcu = RegKey::predef(HKEY_CURRENT_USER);
+ let (key, _disp) = hkcu.create_subkey_transacted("Software\\RustTransaction", &t)?;
+ key.set_value("TestQWORD", &1_234_567_891_011_121_314u64)?;
+ key.set_value("TestDWORD", &1_234_567_890u32)?;
+
+ println!("Commit transaction? [y/N]:");
+ let mut input = String::new();
+ io::stdin().read_line(&mut input)?;
+ input = input.trim_end().to_owned();
+ if input == "y" || input == "Y" {
+ t.commit()?;
+ println!("Transaction committed.");
+ } else {
+ // this is optional, if transaction wasn't committed,
+ // it will be rolled back on disposal
+ t.rollback()?;
+
+ println!("Transaction wasn't committed, it will be rolled back.");
+ }
+
+ Ok(())
+}