From 5e6a3dd7f6d2ac182aa0eb8c6d83e2b42cdff216 Mon Sep 17 00:00:00 2001 From: librelois <elois@ifee.fr> Date: Fri, 10 May 2019 23:19:58 +0200 Subject: [PATCH] [ref] common-tools: split into several files --- lib/modules/ws2p-v1-legacy/src/ws2p_db.rs | 4 +- .../src/ws_connections/messages.rs | 8 +- .../ws2p-v1-legacy/src/ws_connections/mod.rs | 2 +- lib/tools/common-tools/src/fns/bin_file.rs | 42 +++++++++ lib/tools/common-tools/src/fns/mod.rs | 20 +++++ lib/tools/common-tools/src/fns/str_escape.rs | 46 ++++++++++ lib/tools/common-tools/src/fns/time.rs | 28 ++++++ lib/tools/common-tools/src/lib.rs | 85 +------------------ .../common-tools/src/macros/fatal_error.rs | 34 ++++++++ lib/tools/common-tools/src/macros/mod.rs | 18 ++++ .../documents/src/parsers/transactions.rs | 2 +- 11 files changed, 198 insertions(+), 91 deletions(-) create mode 100644 lib/tools/common-tools/src/fns/bin_file.rs create mode 100644 lib/tools/common-tools/src/fns/mod.rs create mode 100644 lib/tools/common-tools/src/fns/str_escape.rs create mode 100644 lib/tools/common-tools/src/fns/time.rs create mode 100644 lib/tools/common-tools/src/macros/fatal_error.rs create mode 100644 lib/tools/common-tools/src/macros/mod.rs diff --git a/lib/modules/ws2p-v1-legacy/src/ws2p_db.rs b/lib/modules/ws2p-v1-legacy/src/ws2p_db.rs index 0b09fb1f..8746d8fd 100644 --- a/lib/modules/ws2p-v1-legacy/src/ws2p_db.rs +++ b/lib/modules/ws2p-v1-legacy/src/ws2p_db.rs @@ -74,7 +74,7 @@ pub fn get_endpoints( file_path: &Path, ) -> Result<HashMap<NodeFullId, DbEndpoint>, Ws2pPeersDbError> { if file_path.exists() { - let bin_endpoints = durs_common_tools::read_bin_file(file_path)?; + let bin_endpoints = durs_common_tools::fns::bin_file::read_bin_file(file_path)?; if bin_endpoints.is_empty() { Ok(HashMap::new()) } else { @@ -91,7 +91,7 @@ pub fn write_endpoints<S: std::hash::BuildHasher>( endpoints: &HashMap<NodeFullId, DbEndpoint, S>, ) -> Result<(), Ws2pPeersDbError> { let bin_endpoints = bincode::serialize(&endpoints)?; - durs_common_tools::write_bin_file(file_path, &bin_endpoints)?; + durs_common_tools::fns::bin_file::write_bin_file(file_path, &bin_endpoints)?; Ok(()) } diff --git a/lib/modules/ws2p-v1-legacy/src/ws_connections/messages.rs b/lib/modules/ws2p-v1-legacy/src/ws_connections/messages.rs index d6465184..08724c4a 100644 --- a/lib/modules/ws2p-v1-legacy/src/ws_connections/messages.rs +++ b/lib/modules/ws2p-v1-legacy/src/ws_connections/messages.rs @@ -80,7 +80,7 @@ pub fn ws2p_conn_message_pretreatment( .get_mut(&ws2p_full_id) .expect("WS2P: Fail to get mut ep !"); dal_ep.state = WS2PConnectionState::WSError; - dal_ep.last_check = durs_common_tools::current_timestamp(); + dal_ep.last_check = durs_common_tools::fns::time::current_timestamp(); return WS2PSignal::WSError(ws2p_full_id); } WS2PConnectionMessagePayload::TryToSendConnectMess => { @@ -96,7 +96,7 @@ pub fn ws2p_conn_message_pretreatment( .get_mut(&ws2p_full_id) .expect("WS2P: Fail to get mut ep !"); dal_ep.state = WS2PConnectionState::Unreachable; - dal_ep.last_check = durs_common_tools::current_timestamp(); + dal_ep.last_check = durs_common_tools::fns::time::current_timestamp(); } WS2PConnectionMessagePayload::WebsocketOk(sender) => { ws2p_module.websockets.insert(ws2p_full_id, sender); @@ -119,7 +119,7 @@ pub fn ws2p_conn_message_pretreatment( .get_mut(&ws2p_full_id) .expect("WS2P: Fail to get mut ep !"); dal_ep.state = WS2PConnectionState::Close; - dal_ep.last_check = durs_common_tools::current_timestamp(); + dal_ep.last_check = durs_common_tools::fns::time::current_timestamp(); } } WS2PConnectionMessagePayload::ValidAckMessage(response, new_con_state) => { @@ -230,7 +230,7 @@ pub fn ws2p_conn_message_pretreatment( .get_mut(&ws2p_full_id) .expect("WS2P: Fail to get mut ep !"); dal_ep.state = WS2PConnectionState::Unreachable; - dal_ep.last_check = durs_common_tools::current_timestamp(); + dal_ep.last_check = durs_common_tools::fns::time::current_timestamp(); } } close_connection( diff --git a/lib/modules/ws2p-v1-legacy/src/ws_connections/mod.rs b/lib/modules/ws2p-v1-legacy/src/ws_connections/mod.rs index d7fb34e7..dfe35c5e 100644 --- a/lib/modules/ws2p-v1-legacy/src/ws_connections/mod.rs +++ b/lib/modules/ws2p-v1-legacy/src/ws_connections/mod.rs @@ -156,7 +156,7 @@ pub fn close_connection( | WS2PCloseConnectionReason::Unknow => { if let Some(dal_ep) = ws2p_module.ws2p_endpoints.get_mut(ws2p_full_id) { dal_ep.state = WS2PConnectionState::Close; - dal_ep.last_check = durs_common_tools::current_timestamp(); + dal_ep.last_check = durs_common_tools::fns::time::current_timestamp(); } } } diff --git a/lib/tools/common-tools/src/fns/bin_file.rs b/lib/tools/common-tools/src/fns/bin_file.rs new file mode 100644 index 00000000..1168d64e --- /dev/null +++ b/lib/tools/common-tools/src/fns/bin_file.rs @@ -0,0 +1,42 @@ +// Copyright (C) 2019 Éloïs SANCHEZ +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see <https://www.gnu.org/licenses/>. + +//! Common rust functions for read/write binary files. + +use std::fs::File; +use std::io::Read; +use std::io::Write; +use std::path::Path; + +/// Read bin file +pub fn read_bin_file(file_path: &Path) -> Result<Vec<u8>, std::io::Error> { + let mut file = File::open(file_path)?; + if file.metadata()?.len() == 0 { + Ok(vec![]) + } else { + let mut bin_datas = Vec::new(); + file.read_to_end(&mut bin_datas)?; + + Ok(bin_datas) + } +} + +/// Write bin file +pub fn write_bin_file(file_path: &Path, datas: &[u8]) -> Result<(), std::io::Error> { + let mut file = File::create(file_path)?; + file.write_all(&datas[..])?; + + Ok(()) +} diff --git a/lib/tools/common-tools/src/fns/mod.rs b/lib/tools/common-tools/src/fns/mod.rs new file mode 100644 index 00000000..ca694e4e --- /dev/null +++ b/lib/tools/common-tools/src/fns/mod.rs @@ -0,0 +1,20 @@ +// Copyright (C) 2019 Éloïs SANCHEZ +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see <https://www.gnu.org/licenses/>. + +//! Common rust functions for DURS project. + +pub mod bin_file; +pub mod str_escape; +pub mod time; diff --git a/lib/tools/common-tools/src/fns/str_escape.rs b/lib/tools/common-tools/src/fns/str_escape.rs new file mode 100644 index 00000000..a18b0da9 --- /dev/null +++ b/lib/tools/common-tools/src/fns/str_escape.rs @@ -0,0 +1,46 @@ +// Copyright (C) 2019 Éloïs SANCHEZ +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see <https://www.gnu.org/licenses/>. + +//! Common rust functions to (un)escape strings. + +/// Unescape backslash +pub fn unescape_str(source: &str) -> String { + let mut previous_char = None; + let mut str_result = String::with_capacity(source.len()); + + for current_char in source.chars() { + if previous_char.is_some() && previous_char.unwrap() == '\\' { + match current_char { + '\\' => {} // Do nothing + _ => str_result.push(current_char), + } + } else { + str_result.push(current_char); + } + previous_char = Some(current_char); + } + + str_result +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + pub fn test_unescape_str() { + assert_eq!("\\".to_owned(), unescape_str("\\\\")); + } +} diff --git a/lib/tools/common-tools/src/fns/time.rs b/lib/tools/common-tools/src/fns/time.rs new file mode 100644 index 00000000..e3adf4b0 --- /dev/null +++ b/lib/tools/common-tools/src/fns/time.rs @@ -0,0 +1,28 @@ +// Copyright (C) 2019 Éloïs SANCHEZ +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see <https://www.gnu.org/licenses/>. + +//! Common rust functions for manage time. + +use std::time::SystemTime; +use std::time::UNIX_EPOCH; + +#[inline] +/// Get current timestamp in seconds +pub fn current_timestamp() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("SystemTime::duration_since failed") + .as_secs() +} diff --git a/lib/tools/common-tools/src/lib.rs b/lib/tools/common-tools/src/lib.rs index be0eee5c..56b827ac 100644 --- a/lib/tools/common-tools/src/lib.rs +++ b/lib/tools/common-tools/src/lib.rs @@ -26,87 +26,6 @@ unused_import_braces )] -use std::fs::File; -use std::io::Read; +pub mod fns; +pub mod macros; use std::io::Write; -use std::path::Path; -use std::time::SystemTime; -use std::time::UNIX_EPOCH; - -/// Interrupts the program and log error message -/// WARNING: this macro must not be called before the logger is initialized ! -#[macro_export] -macro_rules! fatal_error { - ($msg:expr) => ({ - error!("{}", &dbg!($msg)); - panic!($msg); - }); - ($msg:expr,) => ({ - error!("{}", &dbg!($msg)); - panic!($msg); - }); - ($fmt:expr, $($arg:tt)+) => ({ - error!("{}", dbg!(format!($fmt, $($arg)+))); - panic!($fmt, $($arg)+); - }); -} - -#[inline] -/// Get current timestamp in seconds -pub fn current_timestamp() -> u64 { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .expect("SystemTime::duration_since failed") - .as_secs() -} - -/// Read bin file -pub fn read_bin_file(file_path: &Path) -> Result<Vec<u8>, std::io::Error> { - let mut file = File::open(file_path)?; - if file.metadata()?.len() == 0 { - Ok(vec![]) - } else { - let mut bin_datas = Vec::new(); - file.read_to_end(&mut bin_datas)?; - - Ok(bin_datas) - } -} - -/// Write bin file -pub fn write_bin_file(file_path: &Path, datas: &[u8]) -> Result<(), std::io::Error> { - let mut file = File::create(file_path)?; - file.write_all(&datas[..])?; - - Ok(()) -} - -/// Unescape backslash -pub fn unescape_str(source: &str) -> String { - let mut previous_char = None; - let mut str_result = String::with_capacity(source.len()); - - for current_char in source.chars() { - if previous_char.is_some() && previous_char.unwrap() == '\\' { - match current_char { - '\\' => {} // Do nothing - _ => str_result.push(current_char), - } - } else { - str_result.push(current_char); - } - previous_char = Some(current_char); - } - - str_result -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - pub fn test_unescape_str() { - assert_eq!("\\".to_owned(), unescape_str("\\\\")); - } -} diff --git a/lib/tools/common-tools/src/macros/fatal_error.rs b/lib/tools/common-tools/src/macros/fatal_error.rs new file mode 100644 index 00000000..f1e51b1a --- /dev/null +++ b/lib/tools/common-tools/src/macros/fatal_error.rs @@ -0,0 +1,34 @@ +// Copyright (C) 2019 Éloïs SANCHEZ +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see <https://www.gnu.org/licenses/>. + +//! Fatal error macro for DURS project. + +/// Interrupts the program and log error message +/// WARNING: this macro must not be called before the logger is initialized ! +#[macro_export] +macro_rules! fatal_error { + ($msg:expr) => ({ + error!("{}", &dbg!($msg)); + panic!($msg); + }); + ($msg:expr,) => ({ + error!("{}", &dbg!($msg)); + panic!($msg); + }); + ($fmt:expr, $($arg:tt)+) => ({ + error!("{}", dbg!(format!($fmt, $($arg)+))); + panic!($fmt, $($arg)+); + }); +} diff --git a/lib/tools/common-tools/src/macros/mod.rs b/lib/tools/common-tools/src/macros/mod.rs new file mode 100644 index 00000000..9a084595 --- /dev/null +++ b/lib/tools/common-tools/src/macros/mod.rs @@ -0,0 +1,18 @@ +// Copyright (C) 2019 Éloïs SANCHEZ +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see <https://www.gnu.org/licenses/>. + +//! Common rust macros for DURS project. + +pub mod fatal_error; diff --git a/lib/tools/documents/src/parsers/transactions.rs b/lib/tools/documents/src/parsers/transactions.rs index ceea9c1f..a7e7d950 100644 --- a/lib/tools/documents/src/parsers/transactions.rs +++ b/lib/tools/documents/src/parsers/transactions.rs @@ -64,7 +64,7 @@ pub fn parse_json_transaction( .iter() .map(|i| TransactionOutput::from_str(i)) .collect::<Result<Vec<TransactionOutput>, TextDocumentParseError>>()?, - comment: &durs_common_tools::unescape_str(get_str(json_tx, "comment")?), + comment: &durs_common_tools::fns::str_escape::unescape_str(get_str(json_tx, "comment")?), hash: if let Some(hash_str) = get_optional_str(json_tx, "hash")? { Some(Hash::from_hex(hash_str)?) } else { -- GitLab