Passing a fixed length slice to func expecting an arbitrary slice
⚓ Rust 📅 2025-09-24 👤 surdeus 👁️ 8So I have a function where I need to accept arbitrary sized U8 slices, but rust will not let me. How can I fix this?
note: I am in an embedded env, I cannot use allocation, I cannot use std, I cannot use vectors, lists, etc - they require allocation.
It really needs to be done with slices passed by reference
The actual application is HUGE to large to put here.
The small example that i can create that is small and to the point
accepts:
(A) A binary input slice, and
(B) produces an ASCII output slice.
fn  bin2ascii( bin_data_input : &[u8], ascii_data_output : &[u8] )
{
   /* I really want this to be generic for all cases.
    * I do not want "FIXED SIZED" slices.
    * The actual function in the larger context creates packet..
    * But my simple example produces ascii hex in the out buffer.
    */
}
/* I have several hundred "msg functions" like this.
 * Each msg is a different length in ascii.
 *
 * An other example might be creating a UDP network msg.
 * The OUTPUT buffer must always be large enough to hold the msg.
 */
fn sendMsgA( cmd_packet : &[u8:75] )
{
    // Sort of dumb cause the next function effectively initializes this.
     let ascii_bytes : [u8 ; MSG_A_LEN ] = [0;MSG_A_LEN]
     // ERROR[E0053]: See below, second example
     send_msg( ascii_bytes, MSG_A_LEN );
}
fn sendMsgB( cmd_packet : &[u8:32] )
{
     let ascii_bytes : [u8 ; MSG_B_LEN ] = [0;MSG_B_LEN]
     // ERROR[E0053]:  ascii_bytes
     //  expected an array with a size of 64, found one with a size of 129
     bin2ascii( cmd_packet, ascii_bytes );
     send_msg( ascii_bytes, MSG_B_LEN );
}
other things I have considered:
A) using one common buffer size( the largest of them all) presents other problems - It is embedded, so I need to control stack allocation and not be stupid about it, so creating one giant output buffer that is massive is a no go.
B) Or I have a UNIQUE bin2ascii function for every possible size/combination - that seems to be insane
What is necessary is the buffer is large enough for the message.
It is sufficient if the buffer is LARGER then the message
How can I pass an 'large enough buffer' to the common function that formats the data?
2 posts - 2 participants
🏷️ Rust_feed