From 2d7192324ed0149ae35a0d26a9fc24ef86776cc9 Mon Sep 17 00:00:00 2001 From: Daniyar Nurmukhamet Date: Mon, 3 Jan 2022 10:17:11 +0600 Subject: [PATCH] added reading pgn library from binary --- src/pgn.rs | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/src/pgn.rs b/src/pgn.rs index 8c8cded..2d5ad63 100644 --- a/src/pgn.rs +++ b/src/pgn.rs @@ -70,6 +70,23 @@ impl PgnLibrary { Self::from_encoded_dbc_file(path, ISO_8859_1) } + /// Convenience function for loading an entire DBC file from buffer into a returned `PgnLibrary`. This + /// function ignores unparseable lines as well as `Entry` variants which don't apply to + /// `PgnLibrary` (such as `Entry::Version`). Fails on `io::Error`. + /// + /// # Example + /// + /// ```rust + /// use canparse::pgn::PgnLibrary; + /// + /// let lib: PgnLibrary = PgnLibrary::from_buffer(buffer).unwrap(); + /// + /// ``` + pub fn from_buffer(buffer: &[u8]) -> io::Result + { + Self::from_not_encoded_buffer(buffer) + } + /// Convenience function for loading an entire DBC file into a returned `PgnLibrary`, using /// a specified `Encoding` codec. This function ignores unparseable lines as well as `Entry` /// variants which don't apply to `PgnLibrary` (such as `Entry::Version`). @@ -131,6 +148,40 @@ impl PgnLibrary { Ok(lib) } + #[doc(hidden)] + pub fn from_not_encoded_buffer(buffer: &[u8]) -> io::Result + { + let mut lib = PgnLibrary::default(); + + let mut i: &str = ""; + let parsed_string_result = std::str::from_utf8(buffer); + match parsed_string_result { + Ok(parsed_string) => i = parsed_string, + Err(_) => { + // TODO: Handle from_utf8 error + } + } + while !i.is_empty() { + match nomparse::entry(i) { + Ok((new_i, entry)) => { + if let Err(_e) = lib.add_entry(entry) { + // TODO: Handle add_entry error + } + i = new_i; + } + // FIXME: handling `IResult::Err`s could be better + Err(nom::Err::Incomplete(_)) => { + break; + } + Err(_) => { + i = &i[1..]; + } + } + } + + Ok(lib) + } + /// Converts/combines DBC `Entry` values into entries within `PgnLibrary`. Different `Entry` /// variants can modify the same internal entry, hence the need for mutability. This function /// is meant to be called when parsing lines in a `dbc` file.