hermit_toolkit_utils/
padding.rs

1use cosmwasm_std::{HandleResult, QueryResult};
2
3/// Take a Vec<u8> and pad it up to a multiple of `block_size`, using spaces at the end.
4pub fn space_pad(message: &mut Vec<u8>, block_size: usize) -> &mut Vec<u8> {
5    let len = message.len();
6    let surplus = len % block_size;
7    if surplus == 0 {
8        return message;
9    }
10
11    let missing = block_size - surplus;
12    message.reserve(missing);
13    message.extend(std::iter::repeat(b' ').take(missing));
14    message
15}
16
17/// Pad the data and logs in a `HandleResult` to the block size, with spaces.
18// The big `where` clause is based on the `where` clause of `HandleResponse`.
19// Users don't need to care about it as the type `T` has a default, and will
20// always be known in the context of the caller.
21pub fn pad_handle_result<T>(response: HandleResult<T>, block_size: usize) -> HandleResult<T>
22where
23    T: Clone + std::fmt::Debug + PartialEq + schemars::JsonSchema,
24{
25    response.map(|mut response| {
26        response.data = response.data.map(|mut data| {
27            space_pad(&mut data.0, block_size);
28            data
29        });
30        for log in &mut response.log {
31            // Safety: These two are safe because we know the characters that
32            // `space_pad` appends are valid UTF-8
33            unsafe { space_pad(log.key.as_mut_vec(), block_size) };
34            unsafe { space_pad(log.value.as_mut_vec(), block_size) };
35        }
36        response
37    })
38}
39
40/// Pad a `QueryResult` with spaces
41pub fn pad_query_result(response: QueryResult, block_size: usize) -> QueryResult {
42    response.map(|mut response| {
43        space_pad(&mut response.0, block_size);
44        response
45    })
46}