Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add str_array utility function to runtime primitives #2275

Merged
merged 3 commits into from
Nov 11, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions substrate/primitives/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -954,6 +954,23 @@ 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.
bkchr marked this conversation as resolved.
Show resolved Hide resolved
///
/// [`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.
ggwpez marked this conversation as resolved.
Show resolved Hide resolved
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
Loading