stn is a simple integer parsing library. It does not aim to be optimal or extremely performant, but rather to be correct and simple to use.
This library provides parsing functions for signed and unsigned integers from 8 to 64 bits wide. The parsing can be done in any base from 2 and 36, inclusive. Two flavors of functions are provided: ranged and non-ranged. Non-ranged functions parse all integer values representable in the integer type they parse. Ranged functions, however, let the user provide a range that the integer value in the string must be contained in for the parse to be considered successful.
Unlike integer parsing functions in libc, such as atoi and stoi, this library does not use null-terminated strings. All functions accept the input
string as a char pointer and a length. This means that you can parse integers in the
middle of a string without null terminating it.
Once you have the header file accessible in your project, do the following in ONE of your source files:
#define STN_IMPLEMENTATION
#include "stn.h"This will create the function implementations in that translation unit. Other translation units in your program can include stn.h without the preceding definition. This will give them access to the function declarations, but not the function definitions.
When calling a function in this library, there are four arguments that must always be provided: a pointer to the beginning of the string, the length of the string, a pointer to the variable where the result will be stored, and the number base to use. Ranged functions additionally require a min and max value that signify the bounds that the integer may fall in.
If the parsing succeeded, the function will return 1 and the value of the integer that was represented in the string will be stored in the location pointed to by the pointer provided to the function. If the string contained an invalid integer and the parsing failed, 0 will be returned from the function.
#include <stdio.h>
#define STN_IMPLEMENTATION
#include "stn.h"
int main()
{
const char str[] = "123";
int32_t n = 0;
if (stn_parse_s32(str, sizeof(str) - 1, &n, 10)) {
printf("Successfully parsed number: %d\n", n);
} else {
fprintf(stderr, "Error!\n");
}
}