10000 Adds test harness for itoa function; fixes bugs in that function by boredzo · Pull Request #32 · haywire/haywire · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Adds test harness for itoa function; fixes bugs in that function #32

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
13 changes: 9 additions & 4 deletions src/haywire/http_response.c
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,17 @@ void hw_set_body(hw_http_response* response, char* body)
resp->body = body;
}

char* itoa(int val, int base)
char* itoa(unsigned int val, unsigned int base)
{
static char buf[32] = {0};
int i = 30;
enum {
buf_size = 33,
terminator_idx = buf_size - 1,
last_character_index = terminator_idx - 1
};
static char buf[buf_size] = {0};
int i = last_character_index;

for(; val && i ; --i, val /= base)
for(; val && (i >= 0) ; --i, val /= base)
{

buf[i] = "0123456789abcdef"[val % base];
Expand Down
7 changes: 7 additions & 0 deletions test/test_itoa/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
CFLAGS?=-std=c99 -I../../include -Wall -Wextra -Wno-unused-parameter -g

test: test_itoa
./$^
.PHONY: test

test_itoa: test_itoa.o ../../src/haywire/http_response.o
32 changes: 32 additions & 0 deletions test/test_itoa/test_itoa.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#include <stdbool.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>

char* itoa(unsigned int val, unsigned int base);
static bool test_itoa(unsigned int val, unsigned int base, const char *expected);

#define INT_NIBBLES(h, g, f, e, d, c, b, a) (h##g##f##e##d##c##b##a)
#define STR_NIBBLES(h, g, f, e, d, c, b, a) #h #g #f #e #d #c #b #a

int main(int argc, char *argv[]) {
int status = EXIT_SUCCESS;
status |= !test_itoa(42, 10, "42");
//2**31
status |= !test_itoa(INT_NIBBLES(0b1000,0000,0000,0000,0000,0000,0000,0000), 2, STR_NIBBLES(1000,0000,0000,0000,0000,0000,0000,0000));

return status;
}

static bool test_itoa(unsigned int val, unsigned int base, const char *expected) {
const char *itoa_output = itoa(val, base);

if (strcmp(itoa_output, expected) != 0) {
fprintf(stderr, "itoa(%u, %d) failed: expected \"%s\"; got \"%s\"\n", val, base, expected, itoa_output);
return false;
}

return true;
}
0