linera_base/
lib.rs

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