Skip to content

Commit

Permalink
[refactor] #4289: Use nonzero! instead of fallible NonZero* constru…
Browse files Browse the repository at this point in the history
…ctors (#4402)

[refactor] #4289: Use `nonzero!` instead of fallible NonZero* constructors
[refactor] #4289: Disable `std` in `nonzero_ext` 
[refactor] #4289: Use `nonzero!` in integration tests

Signed-off-by: Nurzhan Sakén <nurzhan.sakenov@gmail.com>
  • Loading branch information
nxsaken authored Apr 3, 2024
1 parent 172769c commit fee1cfc
Show file tree
Hide file tree
Showing 18 changed files with 55 additions and 61 deletions.
4 changes: 4 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ impls = "1.0.3"

base64 = { version = "0.21.4", default-features = false }
hex = { version = "0.4.3", default-features = false }
nonzero_ext = "0.3.0"
nonzero_ext = { version = "0.3.0", default-features = false }

url = "2.4.1"
prometheus = { version = "0.13.3", default-features = false }
Expand Down
1 change: 1 addition & 0 deletions client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ tungstenite = { workspace = true }
futures-util = "0.3.28"
merge = "0.1.0"
toml = { workspace = true }
nonzero_ext = { workspace = true }

[dev-dependencies]
iroha_wasm_builder = { workspace = true }
Expand Down
26 changes: 10 additions & 16 deletions client/benches/tps/utils.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,4 @@
use std::{
fmt,
fs::File,
io::BufReader,
num::NonZeroU32,
path::Path,
str::FromStr as _,
sync::mpsc,
thread::{self, JoinHandle},
time,
};
use std::{fmt, fs::File, io::BufReader, path::Path, str::FromStr as _, sync::mpsc, thread, time};

use eyre::{Result, WrapErr};
use iroha_client::{
Expand All @@ -19,6 +9,7 @@ use iroha_client::{
},
};
use iroha_data_model::events::pipeline::{BlockEventFilter, BlockStatus};
use nonzero_ext::nonzero;
use serde::Deserialize;
use test_network::*;

Expand Down Expand Up @@ -163,7 +154,7 @@ impl MeasurerUnit {
let register_me = Register::account(Account::new(account_id, keypair.public_key().clone()));
self.client.submit_blocking(register_me)?;

let mint_a_rose = Mint::asset_numeric(1u32, asset_id);
let mint_a_rose = Mint::asset_numeric(1_u32, asset_id);
self.client.submit_blocking(mint_a_rose)?;

Ok(self)
Expand Down Expand Up @@ -193,15 +184,18 @@ impl MeasurerUnit {
}

/// Spawn who periodically submits transactions
fn spawn_transaction_submitter(&self, shutdown_signal: mpsc::Receiver<()>) -> JoinHandle<()> {
fn spawn_transaction_submitter(
&self,
shutdown_signal: mpsc::Receiver<()>,
) -> thread::JoinHandle<()> {
let chain_id = ChainId::from("0");

let submitter = self.client.clone();
let interval_us_per_tx = self.config.interval_us_per_tx;
let instructions = self.instructions();
let alice_id = AccountId::from_str("alice@wonderland").expect("Failed to parse account id");

let mut nonce = NonZeroU32::new(1).expect("Valid");
let mut nonce = nonzero!(1_u32);

thread::spawn(move || {
for instruction in instructions {
Expand All @@ -217,7 +211,7 @@ impl MeasurerUnit {
iroha_logger::error!(?error, "Failed to submit transaction");
}

nonce = nonce.checked_add(1).or(NonZeroU32::new(1)).expect("Valid");
nonce = nonce.checked_add(1).unwrap_or(nonzero!(1_u32));
thread::sleep(time::Duration::from_micros(interval_us_per_tx));
}
Err(mpsc::TryRecvError::Disconnected) => {
Expand All @@ -237,7 +231,7 @@ impl MeasurerUnit {
}

fn mint(&self) -> InstructionBox {
Mint::asset_numeric(1u32, asset_id(self.name)).into()
Mint::asset_numeric(1_u32, asset_id(self.name)).into()
}
}

Expand Down
13 changes: 6 additions & 7 deletions client/tests/integration/pagination.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
use std::num::{NonZeroU32, NonZeroU64};

use eyre::Result;
use iroha_client::{
client::{asset, Client, QueryResult},
data_model::{asset::AssetDefinition, prelude::*, query::Pagination},
};
use nonzero_ext::nonzero;
use test_network::*;

#[test]
Expand All @@ -17,8 +16,8 @@ fn limits_should_work() -> Result<()> {
let vec = &client
.build_query(asset::all_definitions())
.with_pagination(Pagination {
limit: NonZeroU32::new(5),
start: NonZeroU64::new(5),
limit: Some(nonzero!(5_u32)),
start: Some(nonzero!(5_u64)),
})
.execute()?
.collect::<QueryResult<Vec<_>>>()?;
Expand All @@ -36,10 +35,10 @@ fn fetch_size_should_work() -> Result<()> {
let iter = client
.build_query(asset::all_definitions())
.with_pagination(Pagination {
limit: NonZeroU32::new(20),
start: NonZeroU64::new(0),
limit: Some(nonzero!(20_u32)),
start: None,
})
.with_fetch_size(FetchSize::new(Some(NonZeroU32::new(12).expect("Valid"))))
.with_fetch_size(FetchSize::new(Some(nonzero!(12_u32))))
.execute()?;
assert_eq!(iter.batch_len(), 12);
Ok(())
Expand Down
1 change: 1 addition & 0 deletions client/tests/integration/smartcontracts/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ anyhow = { version = "1.0.71", default-features = false }
serde = { version = "1.0.151", default-features = false }
serde_json = { version = "1.0.91", default-features = false }
getrandom = { version = "0.2", features = ["custom"] }
nonzero_ext = { version = "0.3.0", default-features = false }

lol_alloc = "0.4.0"
panic-halt = "0.2.0"
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,5 @@ panic-halt.workspace = true
lol_alloc.workspace = true
getrandom.workspace = true
parity-scale-codec.workspace = true
nonzero_ext.workspace = true
serde_json = { version = "1.0.108", default-features = false }
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,14 @@ extern crate panic_halt;
extern crate alloc;

use alloc::string::ToString as _;
use core::num::NonZeroU32;

use iroha_smart_contract::{
data_model::{metadata::MetadataValueBox, query::cursor::ForwardCursor},
parse,
prelude::*,
};
use lol_alloc::{FreeListAllocator, LockedAllocator};
use nonzero_ext::nonzero;
use parity_scale_codec::{Decode, DecodeAll, Encode};

#[global_allocator]
Expand All @@ -37,7 +37,7 @@ fn main(owner: AccountId) {
// we guess the layout by encoding and then decoding
let asset_cursor = QueryOutputCursor::decode_all(
&mut &FindAllAssets
.fetch_size(FetchSize::new(Some(NonZeroU32::try_from(1).dbg_unwrap())))
.fetch_size(FetchSize::new(Some(nonzero!(1_u32))))
.execute()
.dbg_unwrap()
.encode()[..],
Expand Down
13 changes: 5 additions & 8 deletions client/tests/integration/sorting.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
use std::{
collections::HashSet,
num::{NonZeroU32, NonZeroU64},
str::FromStr as _,
};
use std::{collections::HashSet, str::FromStr as _};

use eyre::{Result, WrapErr as _};
use iroha_client::{
Expand All @@ -17,6 +13,7 @@ use iroha_client::{
},
};
use iroha_data_model::isi::InstructionBox;
use nonzero_ext::nonzero;
use test_network::*;

use crate::integration::new_account_with_random_public_key;
Expand Down Expand Up @@ -64,7 +61,7 @@ fn correct_pagination_assets_after_creating_new_one() {
let res = test_client
.build_query(client::asset::by_account_id(account_id.clone()))
.with_pagination(Pagination {
limit: NonZeroU32::new(5),
limit: Some(nonzero!(5_u32)),
start: None,
})
.with_sorting(sorting.clone())
Expand Down Expand Up @@ -107,8 +104,8 @@ fn correct_pagination_assets_after_creating_new_one() {
let res = test_client
.build_query(client::asset::by_account_id(account_id))
.with_pagination(Pagination {
limit: NonZeroU32::new(13),
start: NonZeroU64::new(8),
limit: Some(nonzero!(13_u32)),
start: Some(nonzero!(8_u64)),
})
.with_sorting(sorting)
.execute()
Expand Down
11 changes: 4 additions & 7 deletions client/tests/integration/tx_history.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
use std::{
num::{NonZeroU32, NonZeroU64},
str::FromStr as _,
thread,
};
use std::{str::FromStr as _, thread};

use eyre::Result;
use iroha_client::{
client::{transaction, QueryResult},
data_model::{prelude::*, query::Pagination},
};
use iroha_config::parameters::actual::Root as Config;
use nonzero_ext::nonzero;
use test_network::*;

#[ignore = "ignore, more in #2851"]
Expand Down Expand Up @@ -56,8 +53,8 @@ fn client_has_rejected_and_acepted_txs_should_return_tx_history() -> Result<()>
let transactions = client
.build_query(transaction::by_account_id(account_id.clone()))
.with_pagination(Pagination {
limit: NonZeroU32::new(50),
start: NonZeroU64::new(1),
limit: Some(nonzero!(50_u32)),
start: Some(nonzero!(1_u64)),
})
.execute()?
.collect::<QueryResult<Vec<_>>>()?;
Expand Down
1 change: 1 addition & 0 deletions core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ displaydoc = { workspace = true }
wasmtime = { workspace = true }
parking_lot = { workspace = true, features = ["deadlock_detection"] }
derive_more = { workspace = true }
nonzero_ext = { workspace = true }

uuid = { version = "1.4.1", features = ["v4"] }
indexmap = "2.1.0"
Expand Down
15 changes: 7 additions & 8 deletions core/src/query/pagination.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,8 @@ impl<I: Iterator> Iterator for Paginated<I> {

#[cfg(test)]
mod tests {
use std::num::{NonZeroU32, NonZeroU64};

use iroha_data_model::query::pagination::Pagination;
use nonzero_ext::nonzero;

use super::*;

Expand All @@ -72,7 +71,7 @@ mod tests {
.into_iter()
.paginate(Pagination {
limit: None,
start: NonZeroU64::new(1)
start: Some(nonzero!(1_u64))
})
.collect::<Vec<_>>(),
vec![2_i32, 3_i32]
Expand All @@ -82,7 +81,7 @@ mod tests {
.into_iter()
.paginate(Pagination {
limit: None,
start: NonZeroU64::new(3)
start: Some(nonzero!(3_u64))
})
.collect::<Vec<_>>(),
Vec::<i32>::new()
Expand All @@ -95,7 +94,7 @@ mod tests {
vec![1_i32, 2_i32, 3_i32]
.into_iter()
.paginate(Pagination {
limit: NonZeroU32::new(2),
limit: Some(nonzero!(2_u32)),
start: None
})
.collect::<Vec<_>>(),
Expand All @@ -105,7 +104,7 @@ mod tests {
vec![1_i32, 2_i32, 3_i32]
.into_iter()
.paginate(Pagination {
limit: NonZeroU32::new(4),
limit: Some(nonzero!(4_u32)),
start: None
})
.collect::<Vec<_>>(),
Expand All @@ -119,8 +118,8 @@ mod tests {
vec![1_i32, 2_i32, 3_i32]
.into_iter()
.paginate(Pagination {
limit: NonZeroU32::new(1),
start: NonZeroU64::new(1),
limit: Some(nonzero!(1_u32)),
start: Some(nonzero!(1_u64)),
})
.collect::<Vec<_>>(),
vec![2_i32]
Expand Down
5 changes: 2 additions & 3 deletions core/src/query/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -307,9 +307,8 @@ impl LiveQueryStoreHandle {

#[cfg(test)]
mod tests {
use std::num::NonZeroU32;

use iroha_data_model::metadata::MetadataValueBox;
use nonzero_ext::nonzero;

use super::*;

Expand All @@ -322,7 +321,7 @@ mod tests {
for i in 0..10_000 {
let pagination = Pagination::default();
let fetch_size = FetchSize {
fetch_size: NonZeroU32::new(1),
fetch_size: Some(nonzero!(1_u32)),
};
let sorting = Sorting::default();

Expand Down
3 changes: 2 additions & 1 deletion core/src/queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,7 @@ pub mod tests {
use std::{str::FromStr, sync::Arc, thread, time::Duration};

use iroha_data_model::{prelude::*, transaction::TransactionLimits};
use nonzero_ext::nonzero;
use rand::Rng as _;
use tokio::test;

Expand Down Expand Up @@ -497,7 +498,7 @@ pub mod tests {

#[test]
async fn push_tx_overflow() {
let capacity = NonZeroUsize::new(10).unwrap();
let capacity = nonzero!(10_usize);

let key_pair = KeyPair::random();
let kura = Kura::blank_kura_for_testing();
Expand Down
1 change: 1 addition & 0 deletions data_model/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ getset = { workspace = true }
strum = { workspace = true, features = ["derive"] }
base64 = { workspace = true, features = ["alloc"] }
once_cell = { workspace = true, optional = true }
nonzero_ext = { workspace = true }

[dev-dependencies]
iroha_crypto = { workspace = true, features = ["rand"] }
Expand Down
9 changes: 3 additions & 6 deletions data_model/src/query/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ use iroha_data_model_derive::{model, EnumRef};
use iroha_primitives::{numeric::Numeric, small::SmallVec};
use iroha_schema::IntoSchema;
use iroha_version::prelude::*;
use nonzero_ext::nonzero;
pub use pagination::Pagination;
use parity_scale_codec::{Decode, Encode};
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -47,14 +48,10 @@ pub mod sorting;
const FETCH_SIZE: &str = "fetch_size";

/// Default value for `fetch_size` parameter in queries.
// SAFETY: `10` is greater than `0`
#[allow(unsafe_code)]
pub const DEFAULT_FETCH_SIZE: NonZeroU32 = unsafe { NonZeroU32::new_unchecked(10) };
pub const DEFAULT_FETCH_SIZE: NonZeroU32 = nonzero!(10_u32);

/// Max value for `fetch_size` parameter in queries.
// SAFETY: `10_000` is greater than `0`
#[allow(unsafe_code)]
pub const MAX_FETCH_SIZE: NonZeroU32 = unsafe { NonZeroU32::new_unchecked(10_000) };
pub const MAX_FETCH_SIZE: NonZeroU32 = nonzero!(10_000_u32);

/// Structure for query fetch size parameter encoding/decoding
#[derive(
Expand Down
Loading

0 comments on commit fee1cfc

Please sign in to comment.