2

I am doing async reads from a DataInputStream filling a buffer with bytes.

uint8[] buffer = new uint8[4096];
size_t bytes = 0;
bool success = false;

do
{
  success = yield process.get_stdout_pipe().read_all_async(
    buffer,
    GLib.Priority.LOW, 
    null, 
    out bytes
  );
{
while(success && bytes > 0);

I want to combine the data into a string. I had a look at StringBuilder but that has no function to append any arrays.

What is the best approach to build a string while async reading?

aggsol
  • 2,343
  • 1
  • 32
  • 49

2 Answers2

2

You can just cast uint8[] to string anytime.
Code:

uint8[] chars = {31,32,33,34,35,36,37};
print(@"$((string) chars)\n");

Output:

!"#$%
gavr
  • 807
  • 7
  • 16
  • 2
    A string in C (and Vala) is zero terminated. As long as the buffer is zero terminated this will work fine. – AlThomas Mar 16 '20 at 21:33
  • This works. As the length is known, I look for a way where the length is considered like `printf(@"%.*s\n", bytes, (string) buffer)` I feel like StringBuilder is missing an essential feature here. – aggsol Mar 17 '20 at 08:41
2

As an alternative to the print solution a simple loop and using append_c from the StringBuilder in a loop works. Just append every byte till the end of array

var builder = new StringBuilder(buffer.length);
for(int i=0; i<buffer.length; i++ {
  builder.append_c(buffer[i]);
}
aggsol
  • 2,343
  • 1
  • 32
  • 49