### Configuring a LiveFilter Source: https://docs.rs/sdjournal/0.1.21/sdjournal/struct.LiveFilter.html Example demonstrating how to build a filter with presence checks and OR-groups before subscribing to a LiveJournal. ```rust let mut live = LiveJournal::open_default()?; let mut filter = live.filter(); filter .match_present("MESSAGE") .or_group(|g| { g.match_exact("_SYSTEMD_UNIT", b"sshd.service"); }) .or_group(|g| { g.match_exact("_SYSTEMD_UNIT", b"systemd.service"); }); let _subscription = live.subscribe(filter)?; ``` -------------------------------- ### Result FromIterator Implementation Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Examples demonstrating how FromIterator collects Results, short-circuiting on the first Err encountered. ```rust let v = vec![1, 2]; let res: Result, &'static str> = v.iter().map(|x: &u32| x.checked_add(1).ok_or("Overflow!") ).collect(); assert_eq!(res, Ok(vec![2, 3])); ``` ```rust let v = vec![1, 2, 0]; let res: Result, &'static str> = v.iter().map(|x: &u32| x.checked_sub(1).ok_or("Underflow!") ).collect(); assert_eq!(res, Err("Underflow!")); ``` ```rust let v = vec![3, 2, 1, 10]; let mut shared = 0; let res: Result, &'static str> = v.iter().map(|x: &u32| { shared += x; x.checked_sub(2).ok_or("Underflow!") }).collect(); assert_eq!(res, Err("Underflow!")); assert_eq!(shared, 6); ``` -------------------------------- ### Tailing systemd journal entries with LiveJournal Source: https://docs.rs/sdjournal/0.1.21/sdjournal/struct.LiveJournal.html Demonstrates how to initialize a LiveJournal engine, apply filters for specific services, and process incoming entries in a background thread. ```rust use sdjournal::LiveJournal; use std::thread; let mut live = LiveJournal::open_default()?; let mut sshd_filter = live.filter(); sshd_filter.match_unit("sshd.service"); let sshd = live.subscribe(sshd_filter)?; let mut systemd_filter = live.filter(); systemd_filter.match_unit("systemd.service"); let systemd = live.subscribe(systemd_filter)?; let engine = thread::spawn(move || live.run()); let _entry = sshd.recv().expect("engine stopped")?; let _entry = systemd.recv().expect("engine stopped")?; drop(sshd); drop(systemd); engine.join().expect("live engine thread panicked")?; ``` -------------------------------- ### Querying Journal Entries Source: https://docs.rs/sdjournal/0.1.21/sdjournal/struct.JournalQuery.html Demonstrates building a query with presence matching, OR-grouped exact matches, and a result limit. ```rust use sdjournal::Journal; let journal = Journal::open_default()?; let mut query = journal.query(); query .match_present("MESSAGE") .or_group(|g| { g.match_exact("_SYSTEMD_UNIT", b"sshd.service"); }) .or_group(|g| { g.match_exact("_SYSTEMD_UNIT", b"systemd.service"); }) .limit(10); for item in query.iter()? { let entry = item?; println!("{}", entry.realtime_usec()); } ``` -------------------------------- ### Query systemd journal entries Source: https://docs.rs/sdjournal/0.1.21/sdjournal/index.html Demonstrates opening the default journal, filtering by systemd unit, and iterating through entries to print the message field. ```rust use sdjournal::Journal; let journal = Journal::open_default()?; let mut query = journal.query(); query.match_exact("_SYSTEMD_UNIT", b"sshd.service"); query.since_realtime(0); for item in query.iter()? { let entry = item?; if let Some(message) = entry.get("MESSAGE") { println!("{}", String::from_utf8_lossy(message)); } } ``` -------------------------------- ### LiveJournal Initialization Source: https://docs.rs/sdjournal/0.1.21/sdjournal/struct.LiveJournal.html Methods for creating a LiveJournal engine instance from various sources. ```APIDOC ## pub fn open_default() -> Result ### Description Creates a live engine from the default system journal roots on Linux. This is the preferred constructor for applications that only need live tailing. ## pub fn open_default_with_config(config: JournalConfig) -> Result ### Description Creates a live engine from the default system journal roots with a custom configuration. ## pub fn open_dir(path: impl AsRef) -> Result ### Description Creates a live engine from journal files discovered under one root directory. ## pub fn open_dirs(paths: &[PathBuf]) -> Result ### Description Creates a live engine from journal files discovered under multiple root directories. ``` -------------------------------- ### Engine Execution Source: https://docs.rs/sdjournal/0.1.21/sdjournal/struct.LiveJournal.html Methods for driving the live journal engine and processing entries. ```APIDOC ## pub fn poll_once(&mut self) -> Result ### Description Polls for live changes once and dispatches newly appended entries. Returns the total number of subscription deliveries performed. ## pub fn run(self) -> Result<()> ### Description Runs the live engine until every subscription has been dropped. This is the standard way to drive live delivery from a background thread. ``` -------------------------------- ### Unwrap with expect Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Returns the Ok value or panics with a provided message if the Result is Err. ```rust let x: Result = Err("emergency failure"); x.expect("Testing expect"); // panics with `Testing expect: emergency failure` ``` ```rust let path = std::env::var("IMPORTANT_PATH") .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`"); ``` -------------------------------- ### Defining OR Groups in Queries Source: https://docs.rs/sdjournal/0.1.21/sdjournal/struct.JournalQuery.html Shows how to structure complex queries using multiple OR-groups to combine specific field matches. ```rust let mut query = journal.query(); query .match_exact("_SYSTEMD_UNIT", b"sshd.service") .or_group(|g| { g.match_exact("_PID", b"1"); g.match_exact("_UID", b"0"); }) .or_group(|g| { g.match_exact("PRIORITY", b"3"); }); ``` -------------------------------- ### Copying Result Contents Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Methods to copy or clone the contents of an Ok variant from a reference. ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` ```rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); assert_eq!(x, Ok(&mut 12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` ```rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); assert_eq!(x, Ok(&mut 12)); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` -------------------------------- ### Unwrap Result or Default Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Returns the Ok value or the default value of the type if the result is Err. ```rust let good_year_from_input = "1909"; let bad_year_from_input = "190blarg"; let good_year = good_year_from_input.parse().unwrap_or_default(); let bad_year = bad_year_from_input.parse().unwrap_or_default(); assert_eq!(1909, good_year); assert_eq!(0, bad_year); ``` -------------------------------- ### And Then Operation Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Chains a function to a result, executing it only if the result is Ok. ```rust fn sq_then_to_string(x: u32) -> Result { x.checked_mul(x).map(|sq| sq.to_string()).ok_or("overflowed") } ``` -------------------------------- ### Calculate Product of Result Iterator Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Demonstrates using the product method on an iterator of Results, which returns the product of all elements or the first encountered Err. ```rust let nums = vec!["5", "10", "1", "2"]; let total: Result = nums.iter().map(|w| w.parse::()).product(); assert_eq!(total, Ok(100)); let nums = vec!["5", "10", "one", "2"]; let total: Result = nums.iter().map(|w| w.parse::()).product(); assert!(total.is_err()); ``` -------------------------------- ### recv() Source: https://docs.rs/sdjournal/0.1.21/sdjournal/struct.LiveSubscription.html Receive the next entry, blocking until the subscription closes or a value arrives. ```APIDOC ## pub fn recv(&self) -> Result, RecvError> ### Description Receive the next entry, blocking until the subscription closes or a value arrives. The outer Result reports channel closure, while the inner Result reports journal decoding or I/O errors. ``` -------------------------------- ### Provide a default value with unwrap_or Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Returns the contained Ok value or a provided default value if the Result is an Err. ```rust let default = 2; let x: Result = Ok(9); assert_eq!(x.unwrap_or(default), 9); let x: Result = Err("error"); assert_eq!(x.unwrap_or(default), default); ``` -------------------------------- ### Subscription Management Source: https://docs.rs/sdjournal/0.1.21/sdjournal/struct.LiveJournal.html Methods for filtering and subscribing to live journal entries. ```APIDOC ## pub fn filter(&self) -> LiveFilter ### Description Creates a new live filter builder. Filters are used to define criteria for journal subscriptions. ## pub fn subscribe(&mut self, filter: LiveFilter) -> Result ### Description Registers a live-only subscription that receives entries appended after the engine's current tail checkpoint. ## pub fn subscribe_with_options(&mut self, options: SubscriptionOptions) -> Result ### Description Registers a subscription with explicit replay or resume bounds, allowing for historical backlog processing. ``` -------------------------------- ### try_recv() Source: https://docs.rs/sdjournal/0.1.21/sdjournal/struct.LiveSubscription.html Try to receive the next queued entry without blocking. ```APIDOC ## pub fn try_recv(&self) -> Result, TryRecvError> ### Description Try to receive the next queued entry without blocking. This is useful when integrating into an existing event loop. ``` -------------------------------- ### And Operation Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Chains two results, returning the second if the first is Ok, otherwise returning the Err of the first. ```rust let x: Result = Ok(2); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("late error")); let x: Result = Err("early error"); let y: Result<&str, &str> = Ok("foo"); assert_eq!(x.and(y), Err("early error")); let x: Result = Err("not a 2"); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("not a 2")); let x: Result = Ok(2); let y: Result<&str, &str> = Ok("different result type"); assert_eq!(x.and(y), Ok("different result type")); ``` -------------------------------- ### LiveQueueFullPolicy Source: https://docs.rs/sdjournal/0.1.21/sdjournal/enum.LiveQueueFullPolicy.html The LiveQueueFullPolicy enum defines how a live subscription handles a full queue. It is a non-exhaustive enum, meaning users should include a wildcard arm when matching. ```APIDOC ## Enum: LiveQueueFullPolicy ### Description Defines the behavior when a live subscription queue is full. ### Variants - **Block**: Wait until the subscriber receives enough entries to make room. This preserves entries but may block the engine if consumers are slow. - **DropNewest**: Drop the newest delivery for that subscriber and keep the subscription alive. Use this when occasional loss is acceptable. - **Disconnect**: Close the slow subscription when its queue is full. This avoids blocking the engine and prevents silent entry loss. ``` -------------------------------- ### LiveEntry Structure Definition Source: https://docs.rs/sdjournal/0.1.21/sdjournal/struct.LiveEntry.html The internal structure definition for LiveEntry. ```rust pub struct LiveEntry(/* private fields */); ``` -------------------------------- ### Fallback to another Result with or Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Returns the provided Result if the current one is an Err, otherwise returns the Ok value. ```rust let x: Result = Ok(2); let y: Result = Err("late error"); assert_eq!(x.or(y), Ok(2)); let x: Result = Err("early error"); let y: Result = Ok(2); assert_eq!(x.or(y), Ok(2)); let x: Result = Err("not a 2"); let y: Result = Err("late error"); assert_eq!(x.or(y), Err("late error")); let x: Result = Ok(2); let y: Result = Ok(100); assert_eq!(x.or(y), Ok(2)); ``` -------------------------------- ### Reference Conversion with as_ref and as_mut Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Converts a Result reference into a Result containing references to the inner values. ```rust let x: Result = Ok(2); assert_eq!(x.as_ref(), Ok(&2)); let x: Result = Err("Error"); assert_eq!(x.as_ref(), Err(&"Error")); ``` ```rust fn mutate(r: &mut Result) { match r.as_mut() { Ok(v) => *v = 42, Err(e) => *e = 0, } } let mut x: Result = Ok(2); mutate(&mut x); assert_eq!(x.unwrap(), 42); let mut x: Result = Err(13); mutate(&mut x); assert_eq!(x.unwrap_err(), 0); ``` -------------------------------- ### recv_timeout() Source: https://docs.rs/sdjournal/0.1.21/sdjournal/struct.LiveSubscription.html Receive the next entry, waiting at most the specified duration. ```APIDOC ## pub fn recv_timeout(&self, timeout: Duration) -> Result, RecvTimeoutError> ### Description Receive the next entry, waiting at most `timeout`. The outer Result distinguishes timeout or channel closure from a delivered value. ``` -------------------------------- ### Convert Result to Option Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Methods to convert Result into Option, either keeping the Ok value or the Err value. ```rust let x: Result = Ok(2); assert_eq!(x.ok(), Some(2)); let x: Result = Err("Nothing here"); assert_eq!(x.ok(), None); ``` ```rust let x: Result = Ok(2); assert_eq!(x.err(), None); let x: Result = Err("Nothing here"); assert_eq!(x.err(), Some("Nothing here")); ``` -------------------------------- ### LiveJournal Struct Definition Source: https://docs.rs/sdjournal/0.1.21/sdjournal/struct.LiveJournal.html The primary structure for the live journal engine. ```rust pub struct LiveJournal { /* private fields */ } ``` -------------------------------- ### Unwrap Error Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Returns the Err value or panics if the result is Ok. ```rust let x: Result = Ok(2); x.unwrap_err(); // panics with `2` ``` ```rust let x: Result = Err("emergency failure"); assert_eq!(x.unwrap_err(), "emergency failure"); ``` -------------------------------- ### Map Result to Default or Fallback Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Methods to handle Result by providing a default value or a fallback function when an Err is encountered. ```rust let x: Result<_, &str> = Ok("foo"); assert_eq!(x.map_or(42, |v| v.len()), 3); let x: Result<&str, _> = Err("bar"); assert_eq!(x.map_or(42, |v| v.len()), 42); ``` ```rust let k = 21; let x : Result<_, &str> = Ok("foo"); assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3); let x : Result<&str, _> = Err("bar"); assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42); ``` ```rust let x: Result<_, &str> = Ok("foo"); let y: Result<&str, _> = Err("bar"); assert_eq!(x.map_or_default(|x| x.len()), 3); assert_eq!(y.map_or_default(|y| y.len()), 0); ``` -------------------------------- ### Inspect Ok Value with inspect Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Executes a closure with a reference to the Ok value without consuming the Result. ```rust let x: u8 = "4" .parse::() .inspect(|x| println!("original: {x}")) .map(|x| x.pow(3)) .expect("failed to parse number"); ``` -------------------------------- ### LiveFilter Definition Source: https://docs.rs/sdjournal/0.1.21/sdjournal/struct.LiveFilter.html The structure definition for LiveFilter. ```rust pub struct LiveFilter { /* private fields */ } ``` -------------------------------- ### Define JournalConfig struct Source: https://docs.rs/sdjournal/0.1.21/sdjournal/struct.JournalConfig.html The structure definition for JournalConfig, containing 16 fields that govern resource usage and file processing limits. ```rust pub struct JournalConfig {Show 16 fields pub max_object_size_bytes: u64, pub max_decompressed_bytes: usize, pub max_field_name_len: usize, pub max_fields_per_entry: usize, pub max_journal_files: usize, pub max_open_files: usize, pub mmap_policy: MmapPolicy, pub max_object_chain_steps: usize, pub max_query_terms: usize, pub allow_mmap_online: bool, pub include_journal_tilde: bool, pub poll_interval: Duration, pub live_channel_capacity: usize, pub max_live_batch_entries: usize, pub max_live_replay_entries: Option, pub live_queue_full_policy: LiveQueueFullPolicy, } ``` -------------------------------- ### Expect Error Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Returns the Err value or panics with a custom message if the result is Ok. ```rust let x: Result = Ok(10); x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10` ``` -------------------------------- ### Calculate Sum of Result Iterator Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Demonstrates using the sum method on an iterator of Results, which returns the sum of all elements or the first encountered Err. ```rust let f = |&x: &i32| if x < 0 { Err("Negative element found") } else { Ok(x) }; let v = vec![1, 2]; let res: Result = v.iter().map(f).sum(); assert_eq!(res, Ok(3)); let v = vec![1, -2]; let res: Result = v.iter().map(f).sum(); assert_eq!(res, Err("Negative element found")); ``` -------------------------------- ### Into Ok Value Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Extracts the Ok value from a Result that is guaranteed not to contain an error. ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` -------------------------------- ### Cursor::parse Source: https://docs.rs/sdjournal/0.1.21/sdjournal/struct.Cursor.html Parses a cursor from a string representation. This method accepts both sdjournal versioned formats and native systemd cursor strings. ```APIDOC ## pub fn parse(s: &str) -> Result ### Description Parses a cursor from a string. This accepts both the `sdjournal` versioned format (`SJ1:...`) and native systemd cursor strings. ### Parameters - **s** (&str) - Required - The string representation of the cursor. ### Returns - **Result** - A Result containing the parsed Cursor or an error if the string is invalid. ``` -------------------------------- ### Transposing Result and Option Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Convert a Result of an Option into an Option of a Result. ```rust #[derive(Debug, Eq, PartialEq)] struct SomeErr; let x: Result, SomeErr> = Ok(Some(5)); let y: Option> = Some(Ok(5)); assert_eq!(x.transpose(), y); ``` -------------------------------- ### Checking Result Status Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Methods to verify if a Result is Ok or Err. ```rust let x: Result = Ok(-3); assert_eq!(x.is_ok(), true); let x: Result = Err("Some error message"); assert_eq!(x.is_ok(), false); ``` ```rust let x: Result = Ok(2); assert_eq!(x.is_ok_and(|x| x > 1), true); let x: Result = Ok(0); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result = Err("hey"); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result = Ok("ownership".to_string()); assert_eq!(x.as_ref().is_ok_and(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` ```rust let x: Result = Ok(-3); assert_eq!(x.is_err(), false); let x: Result = Err("Some error message"); assert_eq!(x.is_err(), true); ``` -------------------------------- ### Compute a default value with unwrap_or_else Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Returns the contained Ok value or computes a default value using a closure if the Result is an Err. ```rust fn count(x: &str) -> usize { x.len() } ``` -------------------------------- ### Unwrap Result Value Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Extracts the Ok value or panics if the result is Err. Use with caution as it may abort the program. ```rust let x: Result = Ok(2); assert_eq!(x.unwrap(), 2); ``` ```rust let x: Result = Err("emergency failure"); x.unwrap(); // panics with `emergency failure` ``` -------------------------------- ### match_present Source: https://docs.rs/sdjournal/0.1.21/sdjournal/struct.LiveOrGroupBuilder.html Adds a field-presence match to the current OR-group. ```APIDOC ## pub fn match_present(&mut self, field: &str) -> &mut Self ### Description Add a field-presence match to this OR-group. Multiple terms added to the same builder are AND-ed together. ### Parameters - **field** (&str) - The field name that must be present. ``` -------------------------------- ### Define CompressionAlgo Enum Source: https://docs.rs/sdjournal/0.1.21/sdjournal/enum.CompressionAlgo.html The definition of the CompressionAlgo enum, which is marked as non-exhaustive. ```rust #[non_exhaustive] pub enum CompressionAlgo { Xz, Lz4, Zstd, } ``` -------------------------------- ### Journal Struct Definition Source: https://docs.rs/sdjournal/0.1.21/sdjournal/struct.Journal.html The primary structure representing an opened set of journal files. ```rust pub struct Journal { /* private fields */ } ``` -------------------------------- ### Check Result with is_err_and Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Returns true if the result is Err and the contained value matches the provided predicate. ```rust use std::io::{Error, ErrorKind}; let x: Result = Err(Error::new(ErrorKind::NotFound, "!")); assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true); let x: Result = Err(Error::new(ErrorKind::PermissionDenied, "!")); assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false); let x: Result = Ok(123); assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false); let x: Result = Err("ownership".to_string()); assert_eq!(x.as_ref().is_err_and(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` -------------------------------- ### Map Result Values Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Transform the Ok value of a Result while leaving Err untouched. ```rust let line = "1\n2\n3\n4\n"; for num in line.lines() { match num.parse::().map(|i| i * 2) { Ok(n) => println!("{n}"), Err(..) => {} } } ``` -------------------------------- ### LiveQueueFullPolicy Enum Definition Source: https://docs.rs/sdjournal/0.1.21/sdjournal/enum.LiveQueueFullPolicy.html The definition of the LiveQueueFullPolicy enum, which is marked as non-exhaustive. ```rust #[non_exhaustive] pub enum LiveQueueFullPolicy { Block, DropNewest, Disconnect, } ``` -------------------------------- ### match_exact Source: https://docs.rs/sdjournal/0.1.21/sdjournal/struct.LiveOrGroupBuilder.html Adds an exact field match to the current OR-group. ```APIDOC ## pub fn match_exact(&mut self, field: &str, value: &[u8]) -> &mut Self ### Description Adds an exact field match to this OR-group. Multiple terms added to the same builder are AND-ed together. ### Parameters - **field** (&str) - The field name to match. - **value** (&[u8]) - The byte slice value to match against the field. ``` -------------------------------- ### Result IntoIterator Implementation Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Consuming iterator implementation for Result, yielding the contained value if Ok, or nothing if Err. ```rust let x: Result = Ok(5); let v: Vec = x.into_iter().collect(); assert_eq!(v, [5]); let x: Result = Err("nothing!"); let v: Vec = x.into_iter().collect(); assert_eq!(v, []); ``` -------------------------------- ### pub unsafe fn unwrap_unchecked(self) -> T Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Returns the contained Ok value, consuming the self value, without checking that the value is not an Err. Calling this method on an Err is undefined behavior. ```APIDOC ## pub unsafe fn unwrap_unchecked(self) -> T ### Description Returns the contained `Ok` value, consuming the `self` value, without checking that the value is not an `Err`. ### Safety Calling this method on an `Err` is _undefined behavior_. ``` -------------------------------- ### Chain fallible operations with and_then Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Chains operations that return a Result, where the next operation is only executed if the previous one succeeded. ```rust assert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string())); assert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err("overflowed")); assert_eq!(Err("not a number").and_then(sq_then_to_string), Err("not a number")); ``` ```rust use std::{io::ErrorKind, path::Path}; // Note: on Windows "/" maps to "C:\" let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified()); assert!(root_modified_time.is_ok()); let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified()); assert!(should_fail.is_err()); assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound); ``` -------------------------------- ### Into Error Value Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Extracts the Err value from a Result that is guaranteed not to contain an Ok value. ```rust fn only_bad_news() -> Result { Err("Oops, it failed".into()) } let error: String = only_bad_news().into_err(); println!("{error}"); ``` -------------------------------- ### Unchecked Result Extraction Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Methods for extracting values from Result without runtime checks. These are unsafe and cause undefined behavior if called on the wrong variant. ```rust let x: Result = Ok(2); assert_eq!(unsafe { x.unwrap_unchecked() }, 2); ``` ```rust let x: Result = Err("emergency failure"); unsafe { x.unwrap_unchecked() }; // Undefined behavior! ``` ```rust let x: Result = Ok(2); unsafe { x.unwrap_err_unchecked() }; // Undefined behavior! ``` ```rust let x: Result = Err("emergency failure"); assert_eq!(unsafe { x.unwrap_err_unchecked() }, "emergency failure"); ``` -------------------------------- ### pub unsafe fn unwrap_err_unchecked(self) -> E Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Returns the contained Err value, consuming the self value, without checking that the value is not an Ok. Calling this method on an Ok is undefined behavior. ```APIDOC ## pub unsafe fn unwrap_err_unchecked(self) -> E ### Description Returns the contained `Err` value, consuming the `self` value, without checking that the value is not an `Ok`. ### Safety Calling this method on an `Ok` is _undefined behavior_. ``` -------------------------------- ### Result Type Definition Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html The primary type alias and its enum structure. ```rust pub type Result = Result; ``` ```rust pub enum Result { Ok(T), Err(SdJournalError), } ``` -------------------------------- ### Fallback to a closure result with or_else Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Lazily executes a closure to provide a fallback Result if the current one is an Err. ```rust fn sq(x: u32) -> Result { Ok(x * x) } fn err(x: u32) -> Result { Err(x) } assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2)); assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2)); assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9)); assert_eq!(Err(3).or_else(err).or_else(err), Err(3)); ``` -------------------------------- ### Iterate Result with iter Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Returns an iterator that yields the contained value if the Result is Ok, or nothing if it is Err. ```rust let x: Result = Ok(7); assert_eq!(x.iter().next(), Some(&7)); let x: Result = Err("nothing!"); assert_eq!(x.iter().next(), None); ``` -------------------------------- ### Define LimitKind Enum Source: https://docs.rs/sdjournal/0.1.21/sdjournal/enum.LimitKind.html The structure of the LimitKind enum, which represents various constraints within the journal system. ```rust #[non_exhaustive] pub enum LimitKind { ObjectSizeBytes, DecompressedBytes, FieldNameLen, FieldsPerEntry, ObjectChainSteps, JournalFiles, QueryTerms, LiveReplayEntries, } ``` -------------------------------- ### Deref Result with as_deref Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Converts a Result containing a type that implements Deref into a Result containing a reference to the target type. ```rust let x: Result = Ok("hello".to_string()); let y: Result<&str, &u32> = Ok("hello"); assert_eq!(x.as_deref(), y); let x: Result = Err(42); let y: Result<&str, &u32> = Err(&42); assert_eq!(x.as_deref(), y); ``` -------------------------------- ### Inspect Err Value with inspect_err Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Executes a closure with a reference to the Err value without consuming the Result. ```rust use std::{fs, io}; fn read() -> io::Result { fs::read_to_string("address.txt") .inspect_err(|e| eprintln!("failed to read file: {e}")) } ``` -------------------------------- ### MmapPolicy Enum Definition Source: https://docs.rs/sdjournal/0.1.21/sdjournal/enum.MmapPolicy.html The definition of the MmapPolicy enum, which is marked as non-exhaustive to allow for future expansion. ```rust #[non_exhaustive] pub enum MmapPolicy { Auto, Never, } ``` -------------------------------- ### Map Error with map_err Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Transforms the error variant of a Result while keeping the Ok variant unchanged. ```rust fn stringify(x: u32) -> String { format!("error code: {x}") } let x: Result = Ok(2); assert_eq!(x.map_err(stringify), Ok(2)); let x: Result = Err(13); assert_eq!(x.map_err(stringify), Err("error code: 13".to_string())); ``` -------------------------------- ### Deref Mutably with as_deref_mut Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Converts a Result containing a type that implements DerefMut into a Result containing a mutable reference to the target type. ```rust let mut s = "HELLO".to_string(); let mut x: Result = Ok("hello".to_string()); let y: Result<&mut str, &mut u32> = Ok(&mut s); assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y); let mut i = 42; let mut x: Result = Err(42); let y: Result<&mut str, &mut u32> = Err(&mut i); assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y); ``` -------------------------------- ### SdJournalError Enum Definition Source: https://docs.rs/sdjournal/0.1.21/sdjournal/enum.SdJournalError.html The structure of the SdJournalError enum, which is marked as non-exhaustive to allow for future expansion. ```rust #[non_exhaustive] pub enum SdJournalError { Io { op: &'static str, path: Option, source: Error, }, PermissionDenied { path: PathBuf, }, InvalidQuery { reason: String, }, Unsupported { reason: String, }, Corrupt { path: Option, offset: Option, reason: String, }, Transient { path: Option, reason: String, }, DecompressFailed { algo: CompressionAlgo, reason: String, }, LimitExceeded { kind: LimitKind, limit: u64, }, NotFound, } ``` -------------------------------- ### Mutably Iterate Result with iter_mut Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Returns a mutable iterator that yields a mutable reference to the contained value if the Result is Ok. ```rust let mut x: Result = Ok(7); match x.iter_mut().next() { Some(v) => *v = 40, None => {}, } assert_eq!(x, Ok(40)); let mut x: Result = Err("nothing!"); assert_eq!(x.iter_mut().next(), None); ``` -------------------------------- ### Flattening Nested Results Source: https://docs.rs/sdjournal/0.1.21/sdjournal/type.Result.html Remove one level of nesting from a Result containing another Result. ```rust let x: Result, u32> = Ok(Ok("hello")); assert_eq!(Ok("hello"), x.flatten()); let x: Result, u32> = Ok(Err(6)); assert_eq!(Err(6), x.flatten()); let x: Result, u32> = Err(6); assert_eq!(Err(6), x.flatten()); ``` ```rust let x: Result, u32>, u32> = Ok(Ok(Ok("hello"))); assert_eq!(Ok(Ok("hello")), x.flatten()); assert_eq!(Ok("hello"), x.flatten().flatten()); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.