Skip to content

Commit 1dbba8f

Browse files
committed
Improve try_with_gas readability
1 parent b94f6f3 commit 1dbba8f

File tree

2 files changed

+15
-9
lines changed

2 files changed

+15
-9
lines changed

packages/vm/src/backend.rs

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -195,18 +195,24 @@ pub trait Querier {
195195
/// must always have gas information attached.
196196
pub type BackendResult<T> = (core::result::Result<T, BackendError>, GasInfo);
197197

198-
/// The equivalent of the `?` operator, but for a [`BackendResult`]
199-
macro_rules! try_br {
200-
($res: expr $(,)?) => {
201-
let (result, gas) = $res;
202-
198+
/// This aims to be similar to the `?` operator, but for a [`BackendResult`].
199+
///
200+
/// The first argument is a result. If it is Ok, return the value.
201+
/// If it is Err, end the current function with a `return BackendResult::Err`.
202+
///
203+
/// The second argument is the gas value that will be used in the error case.
204+
/// It should be the sum of all gas used in the calling function.
205+
macro_rules! try_with_gas {
206+
($result: expr $(,)?, $gas_total: expr $(,)?) => {
207+
let result: core::result::Result<_, _> = $result; // just a type check
208+
let gas: GasInfo = $gas_total; // just a type check
203209
match result {
204210
Ok(v) => v,
205211
Err(e) => return (Err(e), gas),
206212
}
207213
};
208214
}
209-
pub(crate) use try_br;
215+
pub(crate) use try_with_gas;
210216

211217
#[derive(Error, Debug, PartialEq, Eq)]
212218
#[non_exhaustive]

packages/vm/src/testing/mock.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use sha2::{Digest, Sha256};
66

77
use super::querier::MockQuerier;
88
use super::storage::MockStorage;
9-
use crate::backend::try_br;
9+
use crate::backend::try_with_gas;
1010
use crate::{Backend, BackendApi, BackendError, BackendResult, GasInfo};
1111

1212
pub const MOCK_CONTRACT_ADDR: &str = "cosmwasmcontract"; // TODO: use correct address
@@ -178,7 +178,7 @@ impl BackendApi for MockApi {
178178
),
179179
Ok((_, decoded, Variant::Bech32)) => match Vec::<u8>::from_base32(&decoded) {
180180
Ok(bytes) => {
181-
try_br!((validate_length(&bytes), gas_info));
181+
try_with_gas!(validate_length(&bytes), gas_info);
182182
(Ok(bytes), gas_info)
183183
}
184184
Err(_) => (Err(BackendError::user_err("Invalid bech32 data")), gas_info),
@@ -195,7 +195,7 @@ impl BackendApi for MockApi {
195195
MockApiImpl::Bech32 { bech32_prefix } => bech32_prefix,
196196
};
197197

198-
try_br!((validate_length(canonical), gas_info));
198+
try_with_gas!(validate_length(canonical), gas_info);
199199

200200
let result = encode(bech32_prefix, canonical.to_base32(), Variant::Bech32)
201201
.map_err(|_| BackendError::user_err("Invalid bech32 prefix"));

0 commit comments

Comments
 (0)