title: What is the Rust equivalent of a char buffer / ASCII string on the stack?
body: <p>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.</p>
  <p>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.</p>
  <pre class="lang-c prettyprint-override"><code>#include &lt;stdint.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;time.h&gt;
  #include &lt;string.h&gt;
  #include &lt;stdio.h&gt;
  
  #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 &lt; 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(&quot;Generated string: %s\n&quot;, generate_string());
      return 0;
  }
  </code></pre>
  <p>What I explored so far:</p>
  <ul>
  <li>Using a buffer <code>String::with_capacity(50)</code> or <code>BytesMut</code>, 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 calling <code>generate_string()</code> a billion times. That is a billion malloc calls to allocate the buffer. I don't want to use static memory.</li>
  <li>Using a an array of chars on the stack, but it consumes 4x the space for just ASCII characters</li>
  </ul>
  <p>What are your suggestions?</p>
  <p>EDIT:</p>
  <ol>
  <li>Yes, it leaks memory. That't not the point of my question, unless you want much longer snippets of code.</li>
  <li>Yes, it has insecure random characters. That's not the point of my question.</li>
  <li>Why would I allocate the buffer on the heap once per <code>generate_string()</code> call? To make the function self contained, stateless and without static memory. It does not require a pre-allocated buffer externally.</li>
  </ol>