Skip to content

Commit 0c5dcca

Browse files
olanodbkchrdavxy
authored
Add s utility function to frame support (#2275)
A utility function I consider quite useful to declare string literals that are backed by an array. --------- Co-authored-by: Bastian Köcher <[email protected]> Co-authored-by: Davide Galassi <[email protected]>
1 parent 6b7be11 commit 0c5dcca

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

  • substrate/primitives/runtime/src

substrate/primitives/runtime/src/lib.rs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -954,6 +954,32 @@ pub fn print(print: impl traits::Printable) {
954954
print.print();
955955
}
956956

957+
/// Utility function to declare string literals backed by an array of length N.
958+
///
959+
/// The input can be shorter than N, in that case the end of the array is padded with zeros.
960+
///
961+
/// [`str_array`] is useful when converting strings that end up in the storage as fixed size arrays
962+
/// or in const contexts where static data types have strings that could also end up in the storage.
963+
///
964+
/// # Example
965+
///
966+
/// ```rust
967+
/// # use sp_runtime::str_array;
968+
/// const MY_STR: [u8; 6] = str_array("data");
969+
/// assert_eq!(MY_STR, *b"data\0\0");
970+
/// ```
971+
pub const fn str_array<const N: usize>(s: &str) -> [u8; N] {
972+
debug_assert!(s.len() <= N, "String literal doesn't fit in array");
973+
let mut i = 0;
974+
let mut arr = [0; N];
975+
let s = s.as_bytes();
976+
while i < s.len() {
977+
arr[i] = s[i];
978+
i += 1;
979+
}
980+
arr
981+
}
982+
957983
/// Describes on what should happen with a storage transaction.
958984
pub enum TransactionOutcome<R> {
959985
/// Commit the transaction.

0 commit comments

Comments
 (0)