~begs/hru

6d9571881141d02eb89b93cadbd78ee4516185f0 — Maxim Karasev 11 months ago 10c51c2
*.[ch]: stop using separate string for result

Now original string is overwriten by result codepoint by codepoint. It
should be a bit more performant, and also simplifies usage.
3 files changed, 6 insertions(+), 17 deletions(-)

M grunt.c
M grunt.h
M main.c
M grunt.c => grunt.c +3 -6
@@ 59,12 59,10 @@ int convert_char(struct grunt_options options, utf8proc_int32_t *chptr,
}

// Process text of arbitrary size, returns true on success.
bool convert_text(struct grunt_options options, char *result, char *string,
	int len) {
bool convert_text(struct grunt_options options, char *string, int len) {
	// Initialize required variables
	utf8proc_int32_t ch = 0;
	char *string_pos = string;
	char *result_pos = result;
	int grunt_pos = 0;
	int char_size = 0;



@@ 81,9 79,8 @@ bool convert_text(struct grunt_options options, char *result, char *string,
			return 1;
		}

		// Write substitution character to result string
		result_pos +=
			utf8proc_encode_char(ch, (unsigned char *)result_pos);
		// Overwrite original character with substitution
		utf8proc_encode_char(ch, (unsigned char *)string_pos - char_size);
	}

	return 1;

M grunt.h => grunt.h +1 -2
@@ 7,8 7,7 @@ struct grunt_options {
	const char *cyr_grunt;
};

extern bool convert_text(struct grunt_options options, char *result,
	char *string, int len);
extern bool convert_text(struct grunt_options options, char *string, int len);

extern int convert_char(struct grunt_options options, utf8proc_int32_t *chptr,
	int grunt_pos, int char_size);

M main.c => main.c +2 -9
@@ 28,26 28,19 @@ int main(int argc, char *argv[]) {

	// Initialize required variables
	char *string = NULL;
	char *result = NULL;
	size_t len = 0;
	ssize_t nread;

	// Iterate over lines from stdin
	while ((nread = getline(&string, &len, stdin)) != -1) {
		// Allocate memory for result string
		result = malloc(nread);

		// Process input line, writing grunt to result
		if (!convert_text(options, result, string, nread)) {
		if (!convert_text(options, string, nread)) {
			fprintf(stderr, "failed to process string\n");
			return 1;
		}

		// Print result
		fwrite(result, nread, 1, stdout);

		// Free allocated memory
		free(result);
		fwrite(string, nread, 1, stdout);
	}

	// Free allocated memory