Skip to content

Commit

Permalink
Add s utility function to frame support (#2275)
Browse files Browse the repository at this point in the history
A utility function I consider quite useful to declare string literals
that are backed by an array.

---------

Co-authored-by: Bastian Köcher <git@kchr.de>
Co-authored-by: Davide Galassi <davxy@datawok.net>
  • Loading branch information
3 people committed Nov 11, 2023
1 parent 6b7be11 commit 0c5dcca
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions substrate/primitives/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -954,6 +954,32 @@ pub fn print(print: impl traits::Printable) {
print.print();
}

/// Utility function to declare string literals backed by an array of length N.
///
/// The input can be shorter than N, in that case the end of the array is padded with zeros.
///
/// [`str_array`] is useful when converting strings that end up in the storage as fixed size arrays
/// or in const contexts where static data types have strings that could also end up in the storage.
///
/// # Example
///
/// ```rust
/// # use sp_runtime::str_array;
/// const MY_STR: [u8; 6] = str_array("data");
/// assert_eq!(MY_STR, *b"data\0\0");
/// ```
pub const fn str_array<const N: usize>(s: &str) -> [u8; N] {
debug_assert!(s.len() <= N, "String literal doesn't fit in array");
let mut i = 0;
let mut arr = [0; N];
let s = s.as_bytes();
while i < s.len() {
arr[i] = s[i];
i += 1;
}
arr
}

/// Describes on what should happen with a storage transaction.
pub enum TransactionOutcome<R> {
/// Commit the transaction.
Expand Down

0 comments on commit 0c5dcca

Please sign in to comment.