struct
is a binary data formatting library inspired by
'The Practice of Programming (Brian W. Kernighan, Rob Pike)' and
Python struct module.
struct
uses following format characters (note that struct
does not fully
support the Python struct module's format):
Table 1. Byte order
Character | Byte order |
---|---|
= |
native |
< |
little-endian |
> |
big-endian |
! |
network (= big-endian) |
Table 2. Format characters
Format | C/C++ Type | Standard size |
---|---|---|
b |
char | 1 |
B |
unsigned char | 1 |
h |
short | 2 |
H |
unsigned short | 2 |
i |
int | 4 |
I |
unsigned int | 4 |
l |
long | 4 |
L |
unsigned long | 4 |
q |
long long | 8 |
Q |
unsigned long long | 8 |
f |
float | 4 |
d |
double | 8 |
s |
char[] | |
p |
char[] | |
x |
pad bytes | |
v |
go/pbuf svarint | |
V |
go/pbuf varint |
#include "struct.h"
...
char buf1[BUFSIZ] = {'\0',};
char buf2[BUFSIZ] = {'\0',};
char str[BUFSIZ] = {'\0',};
char fmt[BUFSIZ] = {'\0',};
int val = 42;
struct_pack(buf1, "i", val);
strcpy(str, "test");
snprintf(fmt, sizeof(fmt), "%ds", strlen(str));
struct_pack(buf2, fmt, str);
...
int rval;
char rstr[32] = {'\0',};
struct_unpack(buf1, "i", &rval);
struct_unpack(buf2, fmt, rstr);
mkdir build
cd build
cmake ..
make
make install
headers: build/release/include/struct/
.
library: build/release/lib/
.
cmake -DSTRUCT_BUILD_TEST=ON ..
make
make test
or run struct_test
.
valgrind memory check:
ctest -T memcheck
bazel build //:struct
bazel test //test:struct_test
or
bazel test --test_output=all //test:struct_test
you can use git_repository
to fetch struct
library.
WORKSPACE:
load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")
git_repository(
name = "struct",
branch = "master",
remote = "https://github.com/svperbeast/struct",
)
BUILD:
cc_binary(
name = ...,
srcs = [...],
deps = [
"@struct//:struct",
],
)
The Practice of Programming (9.1 Formatting Data)
Code released under the MIT license.