I'm trying to find the Rust equivalent of having a ASCII string buffer on the stack to have the same efficiency as plain C code has.
Here an example on what I mean with a simplified toy exercise: the goal is to generate a random-content and random-length ASCII string that is at most 50 characters long. Thus I keep a char buffer on the stack that is used to iteratively construct the string. Once finished, the string is copied onto the heap with the just-right malloc size and returned to the user.
#include <stdint.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <stdio.h>
#define ASCII_PRINTABLE_FIRST ' '
#define ASCII_PRINTABLE_AMOUNT 95
#define MAX_LEN 50
#define MAX_LEN_WITH_TERM (MAX_LEN + 1)
char* generate_string(void) {
char buffer[MAX_LEN_WITH_TERM];
srand((unsigned) time(NULL));
// Generate random string length
const int len = rand() % MAX_LEN_WITH_TERM;
int i;
for (i = 0; i < len; i++) {
// Fill with random ASCII printable character
buffer[i] = (char)
((rand() % ASCII_PRINTABLE_AMOUNT) + ASCII_PRINTABLE_FIRST);
}
buffer[i] = '\0';
return strdup(buffer);
}
int main(void) {
printf("Generated string: %s\n", generate_string());
return 0;
}
What I explored so far:
- Using a buffer
String::with_capacity(50)
orBytesMut
, but that allocates the buffer on the heap, which I would like to avoid. Sure, it's premature optimisation, but as an optimisation exercise let's image me callinggenerate_string()
a billion times. That is a billion malloc calls to allocate the buffer. I don't want to use static memory. - Using a an array of chars on the stack, but it consumes 4x the space for just ASCII characters
What are your suggestions?
EDIT:
- Yes, it leaks memory. That't not the point of my question, unless you want much longer snippets of code.
- Yes, it has insecure random characters. That's not the point of my question.
- Why would I allocate the buffer on the heap once per
generate_string()
call? To make the function self contained, stateless and without static memory. It does not require a pre-allocated buffer externally.