How to create string from uint8[] in Vala?

Viewed 644

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?

2 Answers

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

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

Output:

!"#$%

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]);
}
Related