Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions cstring.h
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#include <stdbool.h>
#include <assert.h>
#include <inttypes.h>
#include <stdarg.h>

typedef enum EErrorCode {
ERR_NO_ERROR,
Expand Down Expand Up @@ -609,6 +610,34 @@ TString stringSubstring(TString s, size_t pos, size_t len) {
return res;
}

TString stringFormat(const char* format, ...) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add the function definition somewhere at the beginning next to the rest
And add some tests for your function

va_list args;
va_start(args, format);
va_list args_copy;
va_copy(args_copy, args);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it possible to do it without a copy?

const int size = vsnprintf(NULL, 0, format, args_copy);
va_end(args_copy);
if (size < 0) {
const TString error_result = { NULL, 0, 0 };
va_end(args);
return error_result;
}
TString result;
result.size = size;
result.capacity = size + 1;
result.data = (char*)malloc(result.capacity);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
result.data = (char*)malloc(result.capacity);
result.data = (char*)malloc(result.capacity * sizeof(char));


if (!result.data) {
result.size = 0;
result.capacity = 0;
va_end(args);
return result;
}
vsnprintf(result.data, result.capacity, format, args);
va_end(args);
return result;
}

void stringScan(TString *s) {
if (s == NULL) {
setError(ERR_NULL_POINTER);
Expand Down