1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
// Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! This module provides a common set of types and library functions that are shared
//! between the Linera protocol (compiled from Rust to native code) and Linera
//! applications (compiled from Rust to Wasm).
#![deny(missing_docs)]
#![deny(clippy::large_futures)]
#[doc(hidden)]
pub use async_trait::async_trait;
pub mod abi;
#[cfg(not(target_arch = "wasm32"))]
pub mod command;
pub mod crypto;
pub mod data_types;
mod graphql;
pub mod identifiers;
pub mod ownership;
#[cfg(with_metrics)]
pub mod prometheus_util;
#[cfg(not(chain))]
pub mod task;
pub mod tracing;
#[cfg(test)]
mod unit_tests;
pub use graphql::BcsHexParseError;
#[doc(hidden)]
pub use {async_graphql, bcs, hex};
cfg_if::cfg_if! {
if #[cfg(web)] {
#[cfg(web)]
pub use web_time as time;
} else {
pub use std::time;
}
}
/// A macro for asserting that a condition is true, returning an error if it is not.
///
/// # Examples
///
/// ```
/// # use linera_base::ensure;
/// fn divide(x: i32, y: i32) -> Result<i32, String> {
/// ensure!(y != 0, "division by zero");
/// Ok(x / y)
/// }
///
/// assert_eq!(divide(10, 2), Ok(5));
/// assert_eq!(divide(10, 0), Err(String::from("division by zero")));
/// ```
#[macro_export]
macro_rules! ensure {
($cond:expr, $e:expr) => {
if !($cond) {
return Err($e.into());
}
};
}
/// Formats a byte sequence as a hexadecimal string, and elides bytes in the middle if it is longer
/// than 32 bytes.
///
/// This function is intended to be used with the `#[debug(with = "hex_debug")]` field
/// annotation of `custom_debug_derive::Debug`.
///
/// # Examples
///
/// ```
/// # use linera_base::hex_debug;
/// use custom_debug_derive::Debug;
///
/// #[derive(Debug)]
/// struct Message {
/// #[debug(with = "hex_debug")]
/// bytes: Vec<u8>,
/// }
///
/// let msg = Message {
/// bytes: vec![0x12, 0x34, 0x56, 0x78],
/// };
///
/// assert_eq!(format!("{:?}", msg), "Message { bytes: 12345678 }");
///
/// let long_msg = Message {
/// bytes: b" 10 20 30 40 50".to_vec(),
/// };
///
/// assert_eq!(
/// format!("{:?}", long_msg),
/// "Message { bytes: 20202020202020203130202020202020..20202020343020202020202020203530 }"
/// );
/// ```
pub fn hex_debug<T: AsRef<[u8]>>(bytes: &T, f: &mut std::fmt::Formatter) -> std::fmt::Result {
const ELIDE_AFTER: usize = 16;
let bytes = bytes.as_ref();
if bytes.len() <= 2 * ELIDE_AFTER {
write!(f, "{}", hex::encode(bytes))?;
} else {
write!(
f,
"{}..{}",
hex::encode(&bytes[..ELIDE_AFTER]),
hex::encode(&bytes[(bytes.len() - ELIDE_AFTER)..])
)?;
}
Ok(())
}