···9393typedef struct BindleWriter BindleWriter;
94949595/**
9696- * Open a bindle file from disk, the path paramter should be NUL terminated
9696+ * Creates a new archive, overwriting any existing file.
9797+ *
9898+ * # Parameters
9999+ * * `path` - NUL-terminated path to the archive file
100100+ *
101101+ * # Returns
102102+ * A pointer to the Bindle handle, or NULL on error. Must be freed with `bindle_close()`.
103103+ */
104104+struct Bindle *bindle_create(const char *path);
105105+106106+/**
107107+ * Opens an existing archive or creates a new one.
108108+ *
109109+ * # Parameters
110110+ * * `path` - NUL-terminated path to the archive file
111111+ *
112112+ * # Returns
113113+ * A pointer to the Bindle handle, or NULL on error. Must be freed with `bindle_close()`.
97114 */
98115struct Bindle *bindle_open(const char *path);
99116100117/**
101101- * Adds a new entry, the name should be NUL terminated, will the data can contain NUL characters since the length
102102- * is provided
118118+ * Opens an existing archive. Returns NULL if the file doesn't exist.
119119+ *
120120+ * # Parameters
121121+ * * `path` - NUL-terminated path to the archive file
122122+ *
123123+ * # Returns
124124+ * A pointer to the Bindle handle, or NULL on error. Must be freed with `bindle_close()`.
125125+ */
126126+struct Bindle *bindle_load(const char *path);
127127+128128+/**
129129+ * Adds data to the archive with the given name.
130130+ *
131131+ * # Parameters
132132+ * * `ctx` - Bindle handle from `bindle_open()`
133133+ * * `name` - NUL-terminated entry name
134134+ * * `data` - Data bytes (may contain NUL bytes)
135135+ * * `data_len` - Length of data in bytes
136136+ * * `compress` - Compression mode (BindleCompressNone, BindleCompressZstd, or BindleCompressAuto)
137137+ *
138138+ * # Returns
139139+ * True on success. Call `bindle_save()` to commit changes.
103140 */
104141bool bindle_add(struct Bindle *ctx,
105142 const char *name,
···108145 BindleCompress compress);
109146110147/**
111111- * Adds a new entry, the name should be NUL terminated, will the data can contain NUL characters since the length
112112- * is provided
148148+ * Adds a file from the filesystem to the archive.
149149+ *
150150+ * # Parameters
151151+ * * `ctx` - Bindle handle from `bindle_open()`
152152+ * * `name` - NUL-terminated entry name
153153+ * * `path` - NUL-terminated path to file on disk
154154+ * * `compress` - Compression mode
155155+ *
156156+ * # Returns
157157+ * True on success. Call `bindle_save()` to commit changes.
113158 */
114159bool bindle_add_file(struct Bindle *ctx,
115160 const char *name,
···117162 BindleCompress compress);
118163119164/**
120120- * Save any changed to disk
165165+ * Commits all pending changes to disk.
166166+ *
167167+ * Writes the index and footer. Must be called after add/remove operations.
121168 */
122169bool bindle_save(struct Bindle *ctx);
123170124171/**
125125- * Close an open bindle file
172172+ * Closes the archive and frees the handle.
173173+ *
174174+ * After calling this, the ctx pointer is no longer valid.
126175 */
127176void bindle_close(struct Bindle *ctx);
128177129178/**
130130- * Read a value from a bindle file in memory, returns a pointer that should be freed with
131131- * `bindle_free_buffer`
179179+ * Reads an entry from the archive, decompressing if needed.
180180+ *
181181+ * # Parameters
182182+ * * `ctx_ptr` - Bindle handle
183183+ * * `name` - NUL-terminated entry name
184184+ * * `out_len` - Output parameter for data length
185185+ *
186186+ * # Returns
187187+ * Pointer to data buffer, or NULL if not found or CRC32 check fails.
188188+ * Must be freed with `bindle_free_buffer()`.
132189 */
133190uint8_t *bindle_read(struct Bindle *ctx_ptr, const char *name, size_t *out_len);
134191135192/**
136136- * Used to free the results from `bindle_read`
193193+ * Frees a buffer returned by `bindle_read()`.
137194 */
138195void bindle_free_buffer(uint8_t *ptr);
139196140197/**
141141- * Directly read an uncompressed entry from disk, returns NULL if the entry is compressed or doesn't exist
198198+ * Reads an uncompressed entry without allocating.
199199+ *
200200+ * Returns a pointer directly into the memory-mapped archive. Only works for uncompressed entries.
201201+ *
202202+ * # Parameters
203203+ * * `ctx` - Bindle handle
204204+ * * `name` - NUL-terminated entry name
205205+ * * `out_len` - Output parameter for data length
206206+ *
207207+ * # Returns
208208+ * Pointer into the mmap, or NULL if entry is compressed or doesn't exist.
209209+ * The pointer is valid as long as the Bindle handle is open. Do NOT free this pointer.
142210 */
143211const uint8_t *bindle_read_uncompressed_direct(struct Bindle *ctx,
144212 const char *name,
145213 size_t *out_len);
146214147215/**
148148- * Get the number of entries in a bindle file
216216+ * Returns the number of entries in the archive.
149217 */
150218size_t bindle_length(const struct Bindle *ctx);
151219152220/**
153221 * Returns the name of the entry at the given index.
154154- * The string is owned by the Bindle; the caller must NOT free it.
222222+ *
223223+ * Use with `bindle_length()` to iterate over all entries. The pointer is valid as long as the Bindle handle is open.
224224+ * Do NOT free the returned pointer.
155225 */
156156-const char *bindle_entry_name(const struct Bindle *ctx, size_t index, size_t *len);
226226+const char *bindle_entry_name(const struct Bindle *ctx,
227227+ size_t index,
228228+ size_t *len);
157229158230/**
159159- * Compact and rewrite bindle file
231231+ * Reclaims space by removing shadowed data.
232232+ *
233233+ * Rebuilds the archive with only live entries.
160234 */
161235bool bindle_vacuum(struct Bindle *ctx);
162236237237+/**
238238+ * Extracts all entries to a destination directory.
239239+ */
163240bool bindle_unpack(struct Bindle *ctx, const char *dest_path);
164241242242+/**
243243+ * Recursively adds all files from a directory to the archive.
244244+ *
245245+ * Call `bindle_save()` to commit changes.
246246+ */
165247bool bindle_pack(struct Bindle *ctx, const char *src_path, BindleCompress compress);
166248249249+/**
250250+ * Returns true if an entry with the given name exists.
251251+ */
167252bool bindle_exists(const struct Bindle *ctx, const char *name);
168253169254/**
170170- * Remove an entry from the index.
171171- * The data remains in the file until bindle_vacuum is called.
172172- * Returns true if the entry existed and was removed, false otherwise.
255255+ * Removes an entry from the index.
256256+ *
257257+ * Returns true if the entry existed. Data remains in the file until `bindle_vacuum()` is called.
258258+ * Call `bindle_save()` to commit changes.
173259 */
174260bool bindle_remove(struct Bindle *ctx, const char *name);
175261176262/**
177177- * Create a new Writer, while the stream is active (until bindle_stream_finish is called), the
178178- * Bindle struct should not be accessed.
263263+ * Creates a streaming writer for adding an entry.
264264+ *
265265+ * The writer must be closed with `bindle_writer_close()`, then call `bindle_save()` to commit.
266266+ * Do not access the Bindle handle while the writer is active.
179267 */
180268struct BindleWriter *bindle_writer_new(struct Bindle *ctx,
181269 const char *name,
182270 BindleCompress compress);
183271272272+/**
273273+ * Writes data to the writer.
274274+ */
184275bool bindle_writer_write(struct BindleWriter *stream, const uint8_t *data, size_t len);
185276277277+/**
278278+ * Closes the writer and finalizes the entry.
279279+ */
186280bool bindle_writer_close(struct BindleWriter *stream);
187281282282+/**
283283+ * Creates a streaming reader for an entry.
284284+ *
285285+ * Automatically decompresses if needed. Must be freed with `bindle_reader_close()`.
286286+ * Call `bindle_reader_verify_crc32()` after reading to verify integrity.
287287+ */
188288struct BindleReader *bindle_reader_new(const struct Bindle *ctx, const char *name);
189289290290+/**
291291+ * Reads data from the reader into the provided buffer.
292292+ *
293293+ * Returns the number of bytes read, or -1 on error. Returns 0 on EOF.
294294+ */
190295ptrdiff_t bindle_reader_read(struct BindleReader *reader, uint8_t *buffer, size_t buffer_len);
191296192297/**
···196301 */
197302bool bindle_reader_verify_crc32(const struct BindleReader *reader);
198303304304+/**
305305+ * Closes the reader and frees the handle.
306306+ */
199307void bindle_reader_close(struct BindleReader *reader);
200308201309#endif /* BINDLE_H */
+139-20
src/ffi.rs
···7788use crate::{Bindle, Compress, Reader, Writer};
991010-/// Open a bindle file from disk, the path paramter should be NUL terminated
1010+/// Creates a new archive, overwriting any existing file.
1111+///
1212+/// # Parameters
1313+/// * `path` - NUL-terminated path to the archive file
1414+///
1515+/// # Returns
1616+/// A pointer to the Bindle handle, or NULL on error. Must be freed with `bindle_close()`.
1717+#[unsafe(no_mangle)]
1818+pub unsafe extern "C" fn bindle_create(path: *const c_char) -> *mut Bindle {
1919+ if path.is_null() {
2020+ return std::ptr::null_mut();
2121+ }
2222+2323+ let path_str = unsafe {
2424+ match CStr::from_ptr(path).to_str() {
2525+ Ok(s) => s,
2626+ Err(_) => return std::ptr::null_mut(),
2727+ }
2828+ };
2929+3030+ match Bindle::create(path_str) {
3131+ Ok(b) => Box::into_raw(Box::new(b)),
3232+ Err(_) => std::ptr::null_mut(),
3333+ }
3434+}
3535+3636+/// Opens an existing archive or creates a new one.
3737+///
3838+/// # Parameters
3939+/// * `path` - NUL-terminated path to the archive file
4040+///
4141+/// # Returns
4242+/// A pointer to the Bindle handle, or NULL on error. Must be freed with `bindle_close()`.
1143#[unsafe(no_mangle)]
1244pub unsafe extern "C" fn bindle_open(path: *const c_char) -> *mut Bindle {
1345 if path.is_null() {
1446 return std::ptr::null_mut();
1547 }
16481717- // Explicit unsafe block for raw pointer dereference
1849 let path_str = unsafe {
1950 match CStr::from_ptr(path).to_str() {
2051 Ok(s) => s,
···2859 }
2960}
30613131-/// Adds a new entry, the name should be NUL terminated, will the data can contain NUL characters since the length
3232-/// is provided
6262+/// Opens an existing archive. Returns NULL if the file doesn't exist.
6363+///
6464+/// # Parameters
6565+/// * `path` - NUL-terminated path to the archive file
6666+///
6767+/// # Returns
6868+/// A pointer to the Bindle handle, or NULL on error. Must be freed with `bindle_close()`.
6969+#[unsafe(no_mangle)]
7070+pub unsafe extern "C" fn bindle_load(path: *const c_char) -> *mut Bindle {
7171+ if path.is_null() {
7272+ return std::ptr::null_mut();
7373+ }
7474+7575+ let path_str = unsafe {
7676+ match CStr::from_ptr(path).to_str() {
7777+ Ok(s) => s,
7878+ Err(_) => return std::ptr::null_mut(),
7979+ }
8080+ };
8181+8282+ match Bindle::load(path_str) {
8383+ Ok(b) => Box::into_raw(Box::new(b)),
8484+ Err(_) => std::ptr::null_mut(),
8585+ }
8686+}
8787+8888+/// Adds data to the archive with the given name.
8989+///
9090+/// # Parameters
9191+/// * `ctx` - Bindle handle from `bindle_open()`
9292+/// * `name` - NUL-terminated entry name
9393+/// * `data` - Data bytes (may contain NUL bytes)
9494+/// * `data_len` - Length of data in bytes
9595+/// * `compress` - Compression mode (BindleCompressNone, BindleCompressZstd, or BindleCompressAuto)
9696+///
9797+/// # Returns
9898+/// True on success. Call `bindle_save()` to commit changes.
3399#[unsafe(no_mangle)]
34100pub unsafe extern "C" fn bindle_add(
35101 ctx: *mut Bindle,
···55121 }
56122}
571235858-/// Adds a new entry, the name should be NUL terminated, will the data can contain NUL characters since the length
5959-/// is provided
124124+/// Adds a file from the filesystem to the archive.
125125+///
126126+/// # Parameters
127127+/// * `ctx` - Bindle handle from `bindle_open()`
128128+/// * `name` - NUL-terminated entry name
129129+/// * `path` - NUL-terminated path to file on disk
130130+/// * `compress` - Compression mode
131131+///
132132+/// # Returns
133133+/// True on success. Call `bindle_save()` to commit changes.
60134#[unsafe(no_mangle)]
61135pub unsafe extern "C" fn bindle_add_file(
62136 ctx: *mut Bindle,
···85159 }
86160}
871618888-/// Save any changed to disk
162162+/// Commits all pending changes to disk.
163163+///
164164+/// Writes the index and footer. Must be called after add/remove operations.
89165#[unsafe(no_mangle)]
90166pub unsafe extern "C" fn bindle_save(ctx: *mut Bindle) -> bool {
91167 if ctx.is_null() {
···97173 }
98174}
99175100100-/// Close an open bindle file
176176+/// Closes the archive and frees the handle.
177177+///
178178+/// After calling this, the ctx pointer is no longer valid.
101179#[unsafe(no_mangle)]
102180pub unsafe extern "C" fn bindle_close(ctx: *mut Bindle) {
103181 if ctx.is_null() {
···106184 unsafe { drop(Box::from_raw(ctx)) }
107185}
108186109109-/// Read a value from a bindle file in memory, returns a pointer that should be freed with
110110-/// `bindle_free_buffer`
187187+/// Reads an entry from the archive, decompressing if needed.
188188+///
189189+/// # Parameters
190190+/// * `ctx_ptr` - Bindle handle
191191+/// * `name` - NUL-terminated entry name
192192+/// * `out_len` - Output parameter for data length
193193+///
194194+/// # Returns
195195+/// Pointer to data buffer, or NULL if not found or CRC32 check fails.
196196+/// Must be freed with `bindle_free_buffer()`.
111197#[unsafe(no_mangle)]
112198pub unsafe extern "C" fn bindle_read(
113199 ctx_ptr: *mut Bindle,
···167253 }
168254}
169255170170-/// Used to free the results from `bindle_read`
256256+/// Frees a buffer returned by `bindle_read()`.
171257#[unsafe(no_mangle)]
172258pub unsafe extern "C" fn bindle_free_buffer(ptr: *mut u8) {
173259 unsafe {
···192278 }
193279}
194280195195-/// Directly read an uncompressed entry from disk, returns NULL if the entry is compressed or doesn't exist
281281+/// Reads an uncompressed entry without allocating.
282282+///
283283+/// Returns a pointer directly into the memory-mapped archive. Only works for uncompressed entries.
284284+///
285285+/// # Parameters
286286+/// * `ctx` - Bindle handle
287287+/// * `name` - NUL-terminated entry name
288288+/// * `out_len` - Output parameter for data length
289289+///
290290+/// # Returns
291291+/// Pointer into the mmap, or NULL if entry is compressed or doesn't exist.
292292+/// The pointer is valid as long as the Bindle handle is open. Do NOT free this pointer.
196293#[unsafe(no_mangle)]
197294pub unsafe extern "C" fn bindle_read_uncompressed_direct(
198295 ctx: *mut Bindle,
···221318 }
222319}
223320224224-/// Get the number of entries in a bindle file
321321+/// Returns the number of entries in the archive.
225322#[unsafe(no_mangle)]
226323pub unsafe extern "C" fn bindle_length(ctx: *const Bindle) -> usize {
227324 if ctx.is_null() {
···231328}
232329233330/// Returns the name of the entry at the given index.
234234-/// The string is owned by the Bindle; the caller must NOT free it.
331331+///
332332+/// Use with `bindle_length()` to iterate over all entries. The pointer is valid as long as the Bindle handle is open.
333333+/// Do NOT free the returned pointer.
235334#[unsafe(no_mangle)]
236335pub unsafe extern "C" fn bindle_entry_name(
237336 ctx: *const Bindle,
···254353 }
255354}
256355257257-/// Compact and rewrite bindle file
356356+/// Reclaims space by removing shadowed data.
357357+///
358358+/// Rebuilds the archive with only live entries.
258359#[unsafe(no_mangle)]
259360pub unsafe extern "C" fn bindle_vacuum(ctx: *mut Bindle) -> bool {
260361 if ctx.is_null() {
···264365 b.vacuum().is_ok()
265366}
266367368368+/// Extracts all entries to a destination directory.
267369#[unsafe(no_mangle)]
268370pub unsafe extern "C" fn bindle_unpack(ctx: *mut Bindle, dest_path: *const c_char) -> bool {
269371 if ctx.is_null() || dest_path.is_null() {
···274376 b.unpack(path.as_ref()).is_ok()
275377}
276378379379+/// Recursively adds all files from a directory to the archive.
380380+///
381381+/// Call `bindle_save()` to commit changes.
277382#[unsafe(no_mangle)]
278383pub unsafe extern "C" fn bindle_pack(
279384 ctx: *mut Bindle,
···288393 b.pack(path.as_ref(), compress).is_ok()
289394}
290395396396+/// Returns true if an entry with the given name exists.
291397#[unsafe(no_mangle)]
292398pub unsafe extern "C" fn bindle_exists(ctx: *const Bindle, name: *const c_char) -> bool {
293399 if ctx.is_null() || name.is_null() {
···305411 b.exists(name_str)
306412}
307413308308-/// Remove an entry from the index.
309309-/// The data remains in the file until bindle_vacuum is called.
310310-/// Returns true if the entry existed and was removed, false otherwise.
414414+/// Removes an entry from the index.
415415+///
416416+/// Returns true if the entry existed. Data remains in the file until `bindle_vacuum()` is called.
417417+/// Call `bindle_save()` to commit changes.
311418#[unsafe(no_mangle)]
312419pub unsafe extern "C" fn bindle_remove(ctx: *mut Bindle, name: *const c_char) -> bool {
313420 if ctx.is_null() || name.is_null() {
···325432 b.remove(name_str)
326433}
327434328328-/// Create a new Writer, while the stream is active (until bindle_stream_finish is called), the
329329-/// Bindle struct should not be accessed.
435435+/// Creates a streaming writer for adding an entry.
436436+///
437437+/// The writer must be closed with `bindle_writer_close()`, then call `bindle_save()` to commit.
438438+/// Do not access the Bindle handle while the writer is active.
330439#[unsafe(no_mangle)]
331440pub unsafe extern "C" fn bindle_writer_new<'a>(
332441 ctx: *mut Bindle,
···344453 }
345454}
346455456456+/// Writes data to the writer.
347457#[unsafe(no_mangle)]
348458pub unsafe extern "C" fn bindle_writer_write(
349459 stream: *mut Writer,
···357467 }
358468}
359469470470+/// Closes the writer and finalizes the entry.
360471#[unsafe(no_mangle)]
361472pub unsafe extern "C" fn bindle_writer_close(stream: *mut Writer) -> bool {
362473 let s = unsafe { Box::from_raw(stream) };
363474 s.close().is_ok()
364475}
365476477477+/// Creates a streaming reader for an entry.
478478+///
479479+/// Automatically decompresses if needed. Must be freed with `bindle_reader_close()`.
480480+/// Call `bindle_reader_verify_crc32()` after reading to verify integrity.
366481#[unsafe(no_mangle)]
367482pub unsafe extern "C" fn bindle_reader_new<'a>(
368483 ctx: *const Bindle,
···381496 }
382497}
383498499499+/// Reads data from the reader into the provided buffer.
500500+///
501501+/// Returns the number of bytes read, or -1 on error. Returns 0 on EOF.
384502#[unsafe(no_mangle)]
385503pub unsafe extern "C" fn bindle_reader_read(
386504 reader: *mut Reader,
···413531 r.verify_crc32().is_ok()
414532}
415533534534+/// Closes the reader and frees the handle.
416535#[unsafe(no_mangle)]
417536pub unsafe extern "C" fn bindle_reader_close(reader: *mut Reader) {
418537 if !reader.is_null() {
+30
test/Makefile
···11+# Makefile for C API tests
22+33+CARGO_TARGET_DIR ?= ../target
44+RUST_LIB = $(CARGO_TARGET_DIR)/debug/libbindle_file.a
55+TEST_BINARY = runtest
66+77+# Detect OS
88+UNAME_S := $(shell uname -s)
99+1010+ifeq ($(UNAME_S),Darwin)
1111+ LDFLAGS = -framework Security -lSystem -lresolv -lc -lm
1212+else
1313+ LDFLAGS = -lpthread -ldl -lm
1414+endif
1515+1616+all: test
1717+1818+$(RUST_LIB):
1919+ cd .. && cargo build
2020+2121+$(TEST_BINARY): test.c $(RUST_LIB)
2222+ $(CC) -o $(TEST_BINARY) test.c $(RUST_LIB) $(LDFLAGS)
2323+2424+test: $(TEST_BINARY)
2525+ ./$(TEST_BINARY)
2626+2727+clean:
2828+ rm -f $(TEST_BINARY) *.bndl
2929+3030+.PHONY: all test clean
+1266
test/greatest.h
···11+/*
22+ * Copyright (c) 2011-2021 Scott Vokes <vokes.s@gmail.com>
33+ *
44+ * Permission to use, copy, modify, and/or distribute this software for any
55+ * purpose with or without fee is hereby granted, provided that the above
66+ * copyright notice and this permission notice appear in all copies.
77+ *
88+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
99+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
1010+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
1111+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
1212+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
1313+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
1414+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
1515+ */
1616+1717+#ifndef GREATEST_H
1818+#define GREATEST_H
1919+2020+#if defined(__cplusplus) && !defined(GREATEST_NO_EXTERN_CPLUSPLUS)
2121+extern "C" {
2222+#endif
2323+2424+/* 1.5.0 */
2525+#define GREATEST_VERSION_MAJOR 1
2626+#define GREATEST_VERSION_MINOR 5
2727+#define GREATEST_VERSION_PATCH 0
2828+2929+/* A unit testing system for C, contained in 1 file.
3030+ * It doesn't use dynamic allocation or depend on anything
3131+ * beyond ANSI C89.
3232+ *
3333+ * An up-to-date version can be found at:
3434+ * https://github.com/silentbicycle/greatest/
3535+ */
3636+3737+3838+/*********************************************************************
3939+ * Minimal test runner template
4040+ *********************************************************************/
4141+#if 0
4242+4343+#include "greatest.h"
4444+4545+TEST foo_should_foo(void) {
4646+ PASS();
4747+}
4848+4949+static void setup_cb(void *data) {
5050+ printf("setup callback for each test case\n");
5151+}
5252+5353+static void teardown_cb(void *data) {
5454+ printf("teardown callback for each test case\n");
5555+}
5656+5757+SUITE(suite) {
5858+ /* Optional setup/teardown callbacks which will be run before/after
5959+ * every test case. If using a test suite, they will be cleared when
6060+ * the suite finishes. */
6161+ SET_SETUP(setup_cb, voidp_to_callback_data);
6262+ SET_TEARDOWN(teardown_cb, voidp_to_callback_data);
6363+6464+ RUN_TEST(foo_should_foo);
6565+}
6666+6767+/* Add definitions that need to be in the test runner's main file. */
6868+GREATEST_MAIN_DEFS();
6969+7070+/* Set up, run suite(s) of tests, report pass/fail/skip stats. */
7171+int run_tests(void) {
7272+ GREATEST_INIT(); /* init. greatest internals */
7373+ /* List of suites to run (if any). */
7474+ RUN_SUITE(suite);
7575+7676+ /* Tests can also be run directly, without using test suites. */
7777+ RUN_TEST(foo_should_foo);
7878+7979+ GREATEST_PRINT_REPORT(); /* display results */
8080+ return greatest_all_passed();
8181+}
8282+8383+/* main(), for a standalone command-line test runner.
8484+ * This replaces run_tests above, and adds command line option
8585+ * handling and exiting with a pass/fail status. */
8686+int main(int argc, char **argv) {
8787+ GREATEST_MAIN_BEGIN(); /* init & parse command-line args */
8888+ RUN_SUITE(suite);
8989+ GREATEST_MAIN_END(); /* display results */
9090+}
9191+9292+#endif
9393+/*********************************************************************/
9494+9595+9696+#include <stdlib.h>
9797+#include <stdio.h>
9898+#include <string.h>
9999+#include <ctype.h>
100100+101101+/***********
102102+ * Options *
103103+ ***********/
104104+105105+/* Default column width for non-verbose output. */
106106+#ifndef GREATEST_DEFAULT_WIDTH
107107+#define GREATEST_DEFAULT_WIDTH 72
108108+#endif
109109+110110+/* FILE *, for test logging. */
111111+#ifndef GREATEST_STDOUT
112112+#define GREATEST_STDOUT stdout
113113+#endif
114114+115115+/* Remove GREATEST_ prefix from most commonly used symbols? */
116116+#ifndef GREATEST_USE_ABBREVS
117117+#define GREATEST_USE_ABBREVS 1
118118+#endif
119119+120120+/* Set to 0 to disable all use of setjmp/longjmp. */
121121+#ifndef GREATEST_USE_LONGJMP
122122+#define GREATEST_USE_LONGJMP 0
123123+#endif
124124+125125+/* Make it possible to replace fprintf with another
126126+ * function with the same interface. */
127127+#ifndef GREATEST_FPRINTF
128128+#define GREATEST_FPRINTF fprintf
129129+#endif
130130+131131+#if GREATEST_USE_LONGJMP
132132+#include <setjmp.h>
133133+#endif
134134+135135+/* Set to 0 to disable all use of time.h / clock(). */
136136+#ifndef GREATEST_USE_TIME
137137+#define GREATEST_USE_TIME 1
138138+#endif
139139+140140+#if GREATEST_USE_TIME
141141+#include <time.h>
142142+#endif
143143+144144+/* Floating point type, for ASSERT_IN_RANGE. */
145145+#ifndef GREATEST_FLOAT
146146+#define GREATEST_FLOAT double
147147+#define GREATEST_FLOAT_FMT "%g"
148148+#endif
149149+150150+/* Size of buffer for test name + optional '_' separator and suffix */
151151+#ifndef GREATEST_TESTNAME_BUF_SIZE
152152+#define GREATEST_TESTNAME_BUF_SIZE 128
153153+#endif
154154+155155+156156+/*********
157157+ * Types *
158158+ *********/
159159+160160+/* Info for the current running suite. */
161161+typedef struct greatest_suite_info {
162162+ unsigned int tests_run;
163163+ unsigned int passed;
164164+ unsigned int failed;
165165+ unsigned int skipped;
166166+167167+#if GREATEST_USE_TIME
168168+ /* timers, pre/post running suite and individual tests */
169169+ clock_t pre_suite;
170170+ clock_t post_suite;
171171+ clock_t pre_test;
172172+ clock_t post_test;
173173+#endif
174174+} greatest_suite_info;
175175+176176+/* Type for a suite function. */
177177+typedef void greatest_suite_cb(void);
178178+179179+/* Types for setup/teardown callbacks. If non-NULL, these will be run
180180+ * and passed the pointer to their additional data. */
181181+typedef void greatest_setup_cb(void *udata);
182182+typedef void greatest_teardown_cb(void *udata);
183183+184184+/* Type for an equality comparison between two pointers of the same type.
185185+ * Should return non-0 if equal, otherwise 0.
186186+ * UDATA is a closure value, passed through from ASSERT_EQUAL_T[m]. */
187187+typedef int greatest_equal_cb(const void *expd, const void *got, void *udata);
188188+189189+/* Type for a callback that prints a value pointed to by T.
190190+ * Return value has the same meaning as printf's.
191191+ * UDATA is a closure value, passed through from ASSERT_EQUAL_T[m]. */
192192+typedef int greatest_printf_cb(const void *t, void *udata);
193193+194194+/* Callbacks for an arbitrary type; needed for type-specific
195195+ * comparisons via GREATEST_ASSERT_EQUAL_T[m].*/
196196+typedef struct greatest_type_info {
197197+ greatest_equal_cb *equal;
198198+ greatest_printf_cb *print;
199199+} greatest_type_info;
200200+201201+typedef struct greatest_memory_cmp_env {
202202+ const unsigned char *exp;
203203+ const unsigned char *got;
204204+ size_t size;
205205+} greatest_memory_cmp_env;
206206+207207+/* Callbacks for string and raw memory types. */
208208+extern greatest_type_info greatest_type_info_string;
209209+extern greatest_type_info greatest_type_info_memory;
210210+211211+typedef enum {
212212+ GREATEST_FLAG_FIRST_FAIL = 0x01,
213213+ GREATEST_FLAG_LIST_ONLY = 0x02,
214214+ GREATEST_FLAG_ABORT_ON_FAIL = 0x04
215215+} greatest_flag_t;
216216+217217+/* Internal state for a PRNG, used to shuffle test order. */
218218+struct greatest_prng {
219219+ unsigned char random_order; /* use random ordering? */
220220+ unsigned char initialized; /* is random ordering initialized? */
221221+ unsigned char pad_0[6];
222222+ unsigned long state; /* PRNG state */
223223+ unsigned long count; /* how many tests, this pass */
224224+ unsigned long count_ceil; /* total number of tests */
225225+ unsigned long count_run; /* total tests run */
226226+ unsigned long a; /* LCG multiplier */
227227+ unsigned long c; /* LCG increment */
228228+ unsigned long m; /* LCG modulus, based on count_ceil */
229229+};
230230+231231+/* Struct containing all test runner state. */
232232+typedef struct greatest_run_info {
233233+ unsigned char flags;
234234+ unsigned char verbosity;
235235+ unsigned char running_test; /* guard for nested RUN_TEST calls */
236236+ unsigned char exact_name_match;
237237+238238+ unsigned int tests_run; /* total test count */
239239+240240+ /* currently running test suite */
241241+ greatest_suite_info suite;
242242+243243+ /* overall pass/fail/skip counts */
244244+ unsigned int passed;
245245+ unsigned int failed;
246246+ unsigned int skipped;
247247+ unsigned int assertions;
248248+249249+ /* info to print about the most recent failure */
250250+ unsigned int fail_line;
251251+ unsigned int pad_1;
252252+ const char *fail_file;
253253+ const char *msg;
254254+255255+ /* current setup/teardown hooks and userdata */
256256+ greatest_setup_cb *setup;
257257+ void *setup_udata;
258258+ greatest_teardown_cb *teardown;
259259+ void *teardown_udata;
260260+261261+ /* formatting info for ".....s...F"-style output */
262262+ unsigned int col;
263263+ unsigned int width;
264264+265265+ /* only run a specific suite or test */
266266+ const char *suite_filter;
267267+ const char *test_filter;
268268+ const char *test_exclude;
269269+ const char *name_suffix; /* print suffix with test name */
270270+ char name_buf[GREATEST_TESTNAME_BUF_SIZE];
271271+272272+ struct greatest_prng prng[2]; /* 0: suites, 1: tests */
273273+274274+#if GREATEST_USE_TIME
275275+ /* overall timers */
276276+ clock_t begin;
277277+ clock_t end;
278278+#endif
279279+280280+#if GREATEST_USE_LONGJMP
281281+ int pad_jmp_buf;
282282+ unsigned char pad_2[4];
283283+ jmp_buf jump_dest;
284284+#endif
285285+} greatest_run_info;
286286+287287+struct greatest_report_t {
288288+ /* overall pass/fail/skip counts */
289289+ unsigned int passed;
290290+ unsigned int failed;
291291+ unsigned int skipped;
292292+ unsigned int assertions;
293293+};
294294+295295+/* Global var for the current testing context.
296296+ * Initialized by GREATEST_MAIN_DEFS(). */
297297+extern greatest_run_info greatest_info;
298298+299299+/* Type for ASSERT_ENUM_EQ's ENUM_STR argument. */
300300+typedef const char *greatest_enum_str_fun(int value);
301301+302302+303303+/**********************
304304+ * Exported functions *
305305+ **********************/
306306+307307+/* These are used internally by greatest macros. */
308308+int greatest_test_pre(const char *name);
309309+void greatest_test_post(int res);
310310+int greatest_do_assert_equal_t(const void *expd, const void *got,
311311+ greatest_type_info *type_info, void *udata);
312312+void greatest_prng_init_first_pass(int id);
313313+int greatest_prng_init_second_pass(int id, unsigned long seed);
314314+void greatest_prng_step(int id);
315315+316316+/* These are part of the public greatest API. */
317317+void GREATEST_SET_SETUP_CB(greatest_setup_cb *cb, void *udata);
318318+void GREATEST_SET_TEARDOWN_CB(greatest_teardown_cb *cb, void *udata);
319319+void GREATEST_INIT(void);
320320+void GREATEST_PRINT_REPORT(void);
321321+int greatest_all_passed(void);
322322+void greatest_set_suite_filter(const char *filter);
323323+void greatest_set_test_filter(const char *filter);
324324+void greatest_set_test_exclude(const char *filter);
325325+void greatest_set_exact_name_match(void);
326326+void greatest_stop_at_first_fail(void);
327327+void greatest_abort_on_fail(void);
328328+void greatest_list_only(void);
329329+void greatest_get_report(struct greatest_report_t *report);
330330+unsigned int greatest_get_verbosity(void);
331331+void greatest_set_verbosity(unsigned int verbosity);
332332+void greatest_set_flag(greatest_flag_t flag);
333333+void greatest_set_test_suffix(const char *suffix);
334334+335335+336336+/********************
337337+* Language Support *
338338+********************/
339339+340340+/* If __VA_ARGS__ (C99) is supported, allow parametric testing
341341+* without needing to manually manage the argument struct. */
342342+#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 19901L) || \
343343+ (defined(_MSC_VER) && _MSC_VER >= 1800)
344344+#define GREATEST_VA_ARGS
345345+#endif
346346+347347+348348+/**********
349349+ * Macros *
350350+ **********/
351351+352352+/* Define a suite. (The duplication is intentional -- it eliminates
353353+ * a warning from -Wmissing-declarations.) */
354354+#define GREATEST_SUITE(NAME) void NAME(void); void NAME(void)
355355+356356+/* Declare a suite, provided by another compilation unit. */
357357+#define GREATEST_SUITE_EXTERN(NAME) void NAME(void)
358358+359359+/* Start defining a test function.
360360+ * The arguments are not included, to allow parametric testing. */
361361+#define GREATEST_TEST static enum greatest_test_res
362362+363363+/* PASS/FAIL/SKIP result from a test. Used internally. */
364364+typedef enum greatest_test_res {
365365+ GREATEST_TEST_RES_PASS = 0,
366366+ GREATEST_TEST_RES_FAIL = -1,
367367+ GREATEST_TEST_RES_SKIP = 1
368368+} greatest_test_res;
369369+370370+/* Run a suite. */
371371+#define GREATEST_RUN_SUITE(S_NAME) greatest_run_suite(S_NAME, #S_NAME)
372372+373373+/* Run a test in the current suite. */
374374+#define GREATEST_RUN_TEST(TEST) \
375375+ do { \
376376+ if (greatest_test_pre(#TEST) == 1) { \
377377+ enum greatest_test_res res = GREATEST_SAVE_CONTEXT(); \
378378+ if (res == GREATEST_TEST_RES_PASS) { \
379379+ res = TEST(); \
380380+ } \
381381+ greatest_test_post(res); \
382382+ } \
383383+ } while (0)
384384+385385+/* Ignore a test, don't warn about it being unused. */
386386+#define GREATEST_IGNORE_TEST(TEST) (void)TEST
387387+388388+/* Run a test in the current suite with one void * argument,
389389+ * which can be a pointer to a struct with multiple arguments. */
390390+#define GREATEST_RUN_TEST1(TEST, ENV) \
391391+ do { \
392392+ if (greatest_test_pre(#TEST) == 1) { \
393393+ enum greatest_test_res res = GREATEST_SAVE_CONTEXT(); \
394394+ if (res == GREATEST_TEST_RES_PASS) { \
395395+ res = TEST(ENV); \
396396+ } \
397397+ greatest_test_post(res); \
398398+ } \
399399+ } while (0)
400400+401401+#ifdef GREATEST_VA_ARGS
402402+#define GREATEST_RUN_TESTp(TEST, ...) \
403403+ do { \
404404+ if (greatest_test_pre(#TEST) == 1) { \
405405+ enum greatest_test_res res = GREATEST_SAVE_CONTEXT(); \
406406+ if (res == GREATEST_TEST_RES_PASS) { \
407407+ res = TEST(__VA_ARGS__); \
408408+ } \
409409+ greatest_test_post(res); \
410410+ } \
411411+ } while (0)
412412+#endif
413413+414414+415415+/* Check if the test runner is in verbose mode. */
416416+#define GREATEST_IS_VERBOSE() ((greatest_info.verbosity) > 0)
417417+#define GREATEST_LIST_ONLY() \
418418+ (greatest_info.flags & GREATEST_FLAG_LIST_ONLY)
419419+#define GREATEST_FIRST_FAIL() \
420420+ (greatest_info.flags & GREATEST_FLAG_FIRST_FAIL)
421421+#define GREATEST_ABORT_ON_FAIL() \
422422+ (greatest_info.flags & GREATEST_FLAG_ABORT_ON_FAIL)
423423+#define GREATEST_FAILURE_ABORT() \
424424+ (GREATEST_FIRST_FAIL() && \
425425+ (greatest_info.suite.failed > 0 || greatest_info.failed > 0))
426426+427427+/* Message-less forms of tests defined below. */
428428+#define GREATEST_PASS() GREATEST_PASSm(NULL)
429429+#define GREATEST_FAIL() GREATEST_FAILm(NULL)
430430+#define GREATEST_SKIP() GREATEST_SKIPm(NULL)
431431+#define GREATEST_ASSERT(COND) \
432432+ GREATEST_ASSERTm(#COND, COND)
433433+#define GREATEST_ASSERT_OR_LONGJMP(COND) \
434434+ GREATEST_ASSERT_OR_LONGJMPm(#COND, COND)
435435+#define GREATEST_ASSERT_FALSE(COND) \
436436+ GREATEST_ASSERT_FALSEm(#COND, COND)
437437+#define GREATEST_ASSERT_EQ(EXP, GOT) \
438438+ GREATEST_ASSERT_EQm(#EXP " != " #GOT, EXP, GOT)
439439+#define GREATEST_ASSERT_NEQ(EXP, GOT) \
440440+ GREATEST_ASSERT_NEQm(#EXP " == " #GOT, EXP, GOT)
441441+#define GREATEST_ASSERT_GT(EXP, GOT) \
442442+ GREATEST_ASSERT_GTm(#EXP " <= " #GOT, EXP, GOT)
443443+#define GREATEST_ASSERT_GTE(EXP, GOT) \
444444+ GREATEST_ASSERT_GTEm(#EXP " < " #GOT, EXP, GOT)
445445+#define GREATEST_ASSERT_LT(EXP, GOT) \
446446+ GREATEST_ASSERT_LTm(#EXP " >= " #GOT, EXP, GOT)
447447+#define GREATEST_ASSERT_LTE(EXP, GOT) \
448448+ GREATEST_ASSERT_LTEm(#EXP " > " #GOT, EXP, GOT)
449449+#define GREATEST_ASSERT_EQ_FMT(EXP, GOT, FMT) \
450450+ GREATEST_ASSERT_EQ_FMTm(#EXP " != " #GOT, EXP, GOT, FMT)
451451+#define GREATEST_ASSERT_IN_RANGE(EXP, GOT, TOL) \
452452+ GREATEST_ASSERT_IN_RANGEm(#EXP " != " #GOT " +/- " #TOL, EXP, GOT, TOL)
453453+#define GREATEST_ASSERT_EQUAL_T(EXP, GOT, TYPE_INFO, UDATA) \
454454+ GREATEST_ASSERT_EQUAL_Tm(#EXP " != " #GOT, EXP, GOT, TYPE_INFO, UDATA)
455455+#define GREATEST_ASSERT_STR_EQ(EXP, GOT) \
456456+ GREATEST_ASSERT_STR_EQm(#EXP " != " #GOT, EXP, GOT)
457457+#define GREATEST_ASSERT_STRN_EQ(EXP, GOT, SIZE) \
458458+ GREATEST_ASSERT_STRN_EQm(#EXP " != " #GOT, EXP, GOT, SIZE)
459459+#define GREATEST_ASSERT_MEM_EQ(EXP, GOT, SIZE) \
460460+ GREATEST_ASSERT_MEM_EQm(#EXP " != " #GOT, EXP, GOT, SIZE)
461461+#define GREATEST_ASSERT_ENUM_EQ(EXP, GOT, ENUM_STR) \
462462+ GREATEST_ASSERT_ENUM_EQm(#EXP " != " #GOT, EXP, GOT, ENUM_STR)
463463+464464+/* The following forms take an additional message argument first,
465465+ * to be displayed by the test runner. */
466466+467467+/* Fail if a condition is not true, with message. */
468468+#define GREATEST_ASSERTm(MSG, COND) \
469469+ do { \
470470+ greatest_info.assertions++; \
471471+ if (!(COND)) { GREATEST_FAILm(MSG); } \
472472+ } while (0)
473473+474474+/* Fail if a condition is not true, longjmping out of test. */
475475+#define GREATEST_ASSERT_OR_LONGJMPm(MSG, COND) \
476476+ do { \
477477+ greatest_info.assertions++; \
478478+ if (!(COND)) { GREATEST_FAIL_WITH_LONGJMPm(MSG); } \
479479+ } while (0)
480480+481481+/* Fail if a condition is not false, with message. */
482482+#define GREATEST_ASSERT_FALSEm(MSG, COND) \
483483+ do { \
484484+ greatest_info.assertions++; \
485485+ if ((COND)) { GREATEST_FAILm(MSG); } \
486486+ } while (0)
487487+488488+/* Internal macro for relational assertions */
489489+#define GREATEST__REL(REL, MSG, EXP, GOT) \
490490+ do { \
491491+ greatest_info.assertions++; \
492492+ if (!((EXP) REL (GOT))) { GREATEST_FAILm(MSG); } \
493493+ } while (0)
494494+495495+/* Fail if EXP is not ==, !=, >, <, >=, or <= to GOT. */
496496+#define GREATEST_ASSERT_EQm(MSG,E,G) GREATEST__REL(==, MSG,E,G)
497497+#define GREATEST_ASSERT_NEQm(MSG,E,G) GREATEST__REL(!=, MSG,E,G)
498498+#define GREATEST_ASSERT_GTm(MSG,E,G) GREATEST__REL(>, MSG,E,G)
499499+#define GREATEST_ASSERT_GTEm(MSG,E,G) GREATEST__REL(>=, MSG,E,G)
500500+#define GREATEST_ASSERT_LTm(MSG,E,G) GREATEST__REL(<, MSG,E,G)
501501+#define GREATEST_ASSERT_LTEm(MSG,E,G) GREATEST__REL(<=, MSG,E,G)
502502+503503+/* Fail if EXP != GOT (equality comparison by ==).
504504+ * Warning: FMT, EXP, and GOT will be evaluated more
505505+ * than once on failure. */
506506+#define GREATEST_ASSERT_EQ_FMTm(MSG, EXP, GOT, FMT) \
507507+ do { \
508508+ greatest_info.assertions++; \
509509+ if ((EXP) != (GOT)) { \
510510+ GREATEST_FPRINTF(GREATEST_STDOUT, "\nExpected: "); \
511511+ GREATEST_FPRINTF(GREATEST_STDOUT, FMT, EXP); \
512512+ GREATEST_FPRINTF(GREATEST_STDOUT, "\n Got: "); \
513513+ GREATEST_FPRINTF(GREATEST_STDOUT, FMT, GOT); \
514514+ GREATEST_FPRINTF(GREATEST_STDOUT, "\n"); \
515515+ GREATEST_FAILm(MSG); \
516516+ } \
517517+ } while (0)
518518+519519+/* Fail if EXP is not equal to GOT, printing enum IDs. */
520520+#define GREATEST_ASSERT_ENUM_EQm(MSG, EXP, GOT, ENUM_STR) \
521521+ do { \
522522+ int greatest_EXP = (int)(EXP); \
523523+ int greatest_GOT = (int)(GOT); \
524524+ greatest_enum_str_fun *greatest_ENUM_STR = ENUM_STR; \
525525+ if (greatest_EXP != greatest_GOT) { \
526526+ GREATEST_FPRINTF(GREATEST_STDOUT, "\nExpected: %s", \
527527+ greatest_ENUM_STR(greatest_EXP)); \
528528+ GREATEST_FPRINTF(GREATEST_STDOUT, "\n Got: %s\n", \
529529+ greatest_ENUM_STR(greatest_GOT)); \
530530+ GREATEST_FAILm(MSG); \
531531+ } \
532532+ } while (0) \
533533+534534+/* Fail if GOT not in range of EXP +|- TOL. */
535535+#define GREATEST_ASSERT_IN_RANGEm(MSG, EXP, GOT, TOL) \
536536+ do { \
537537+ GREATEST_FLOAT greatest_EXP = (EXP); \
538538+ GREATEST_FLOAT greatest_GOT = (GOT); \
539539+ GREATEST_FLOAT greatest_TOL = (TOL); \
540540+ greatest_info.assertions++; \
541541+ if ((greatest_EXP > greatest_GOT && \
542542+ greatest_EXP - greatest_GOT > greatest_TOL) || \
543543+ (greatest_EXP < greatest_GOT && \
544544+ greatest_GOT - greatest_EXP > greatest_TOL)) { \
545545+ GREATEST_FPRINTF(GREATEST_STDOUT, \
546546+ "\nExpected: " GREATEST_FLOAT_FMT \
547547+ " +/- " GREATEST_FLOAT_FMT \
548548+ "\n Got: " GREATEST_FLOAT_FMT \
549549+ "\n", \
550550+ greatest_EXP, greatest_TOL, greatest_GOT); \
551551+ GREATEST_FAILm(MSG); \
552552+ } \
553553+ } while (0)
554554+555555+/* Fail if EXP is not equal to GOT, according to strcmp. */
556556+#define GREATEST_ASSERT_STR_EQm(MSG, EXP, GOT) \
557557+ do { \
558558+ GREATEST_ASSERT_EQUAL_Tm(MSG, EXP, GOT, \
559559+ &greatest_type_info_string, NULL); \
560560+ } while (0) \
561561+562562+/* Fail if EXP is not equal to GOT, according to strncmp. */
563563+#define GREATEST_ASSERT_STRN_EQm(MSG, EXP, GOT, SIZE) \
564564+ do { \
565565+ size_t size = SIZE; \
566566+ GREATEST_ASSERT_EQUAL_Tm(MSG, EXP, GOT, \
567567+ &greatest_type_info_string, &size); \
568568+ } while (0) \
569569+570570+/* Fail if EXP is not equal to GOT, according to memcmp. */
571571+#define GREATEST_ASSERT_MEM_EQm(MSG, EXP, GOT, SIZE) \
572572+ do { \
573573+ greatest_memory_cmp_env env; \
574574+ env.exp = (const unsigned char *)EXP; \
575575+ env.got = (const unsigned char *)GOT; \
576576+ env.size = SIZE; \
577577+ GREATEST_ASSERT_EQUAL_Tm(MSG, env.exp, env.got, \
578578+ &greatest_type_info_memory, &env); \
579579+ } while (0) \
580580+581581+/* Fail if EXP is not equal to GOT, according to a comparison
582582+ * callback in TYPE_INFO. If they are not equal, optionally use a
583583+ * print callback in TYPE_INFO to print them. */
584584+#define GREATEST_ASSERT_EQUAL_Tm(MSG, EXP, GOT, TYPE_INFO, UDATA) \
585585+ do { \
586586+ greatest_type_info *type_info = (TYPE_INFO); \
587587+ greatest_info.assertions++; \
588588+ if (!greatest_do_assert_equal_t(EXP, GOT, \
589589+ type_info, UDATA)) { \
590590+ if (type_info == NULL || type_info->equal == NULL) { \
591591+ GREATEST_FAILm("type_info->equal callback missing!"); \
592592+ } else { \
593593+ GREATEST_FAILm(MSG); \
594594+ } \
595595+ } \
596596+ } while (0) \
597597+598598+/* Pass. */
599599+#define GREATEST_PASSm(MSG) \
600600+ do { \
601601+ greatest_info.msg = MSG; \
602602+ return GREATEST_TEST_RES_PASS; \
603603+ } while (0)
604604+605605+/* Fail. */
606606+#define GREATEST_FAILm(MSG) \
607607+ do { \
608608+ greatest_info.fail_file = __FILE__; \
609609+ greatest_info.fail_line = __LINE__; \
610610+ greatest_info.msg = MSG; \
611611+ if (GREATEST_ABORT_ON_FAIL()) { abort(); } \
612612+ return GREATEST_TEST_RES_FAIL; \
613613+ } while (0)
614614+615615+/* Optional GREATEST_FAILm variant that longjmps. */
616616+#if GREATEST_USE_LONGJMP
617617+#define GREATEST_FAIL_WITH_LONGJMP() GREATEST_FAIL_WITH_LONGJMPm(NULL)
618618+#define GREATEST_FAIL_WITH_LONGJMPm(MSG) \
619619+ do { \
620620+ greatest_info.fail_file = __FILE__; \
621621+ greatest_info.fail_line = __LINE__; \
622622+ greatest_info.msg = MSG; \
623623+ longjmp(greatest_info.jump_dest, GREATEST_TEST_RES_FAIL); \
624624+ } while (0)
625625+#endif
626626+627627+/* Skip the current test. */
628628+#define GREATEST_SKIPm(MSG) \
629629+ do { \
630630+ greatest_info.msg = MSG; \
631631+ return GREATEST_TEST_RES_SKIP; \
632632+ } while (0)
633633+634634+/* Check the result of a subfunction using ASSERT, etc. */
635635+#define GREATEST_CHECK_CALL(RES) \
636636+ do { \
637637+ enum greatest_test_res greatest_RES = RES; \
638638+ if (greatest_RES != GREATEST_TEST_RES_PASS) { \
639639+ return greatest_RES; \
640640+ } \
641641+ } while (0) \
642642+643643+#if GREATEST_USE_TIME
644644+#define GREATEST_SET_TIME(NAME) \
645645+ NAME = clock(); \
646646+ if (NAME == (clock_t) -1) { \
647647+ GREATEST_FPRINTF(GREATEST_STDOUT, \
648648+ "clock error: %s\n", #NAME); \
649649+ exit(EXIT_FAILURE); \
650650+ }
651651+652652+#define GREATEST_CLOCK_DIFF(C1, C2) \
653653+ GREATEST_FPRINTF(GREATEST_STDOUT, " (%lu ticks, %.3f sec)", \
654654+ (long unsigned int) (C2) - (long unsigned int)(C1), \
655655+ (double)((C2) - (C1)) / (1.0 * (double)CLOCKS_PER_SEC))
656656+#else
657657+#define GREATEST_SET_TIME(UNUSED)
658658+#define GREATEST_CLOCK_DIFF(UNUSED1, UNUSED2)
659659+#endif
660660+661661+#if GREATEST_USE_LONGJMP
662662+#define GREATEST_SAVE_CONTEXT() \
663663+ /* setjmp returns 0 (GREATEST_TEST_RES_PASS) on first call * \
664664+ * so the test runs, then RES_FAIL from FAIL_WITH_LONGJMP. */ \
665665+ ((enum greatest_test_res)(setjmp(greatest_info.jump_dest)))
666666+#else
667667+#define GREATEST_SAVE_CONTEXT() \
668668+ /*a no-op, since setjmp/longjmp aren't being used */ \
669669+ GREATEST_TEST_RES_PASS
670670+#endif
671671+672672+/* Run every suite / test function run within BODY in pseudo-random
673673+ * order, seeded by SEED. (The top 3 bits of the seed are ignored.)
674674+ *
675675+ * This should be called like:
676676+ * GREATEST_SHUFFLE_TESTS(seed, {
677677+ * GREATEST_RUN_TEST(some_test);
678678+ * GREATEST_RUN_TEST(some_other_test);
679679+ * GREATEST_RUN_TEST(yet_another_test);
680680+ * });
681681+ *
682682+ * Note that the body of the second argument will be evaluated
683683+ * multiple times. */
684684+#define GREATEST_SHUFFLE_SUITES(SD, BODY) GREATEST_SHUFFLE(0, SD, BODY)
685685+#define GREATEST_SHUFFLE_TESTS(SD, BODY) GREATEST_SHUFFLE(1, SD, BODY)
686686+#define GREATEST_SHUFFLE(ID, SD, BODY) \
687687+ do { \
688688+ struct greatest_prng *prng = &greatest_info.prng[ID]; \
689689+ greatest_prng_init_first_pass(ID); \
690690+ do { \
691691+ prng->count = 0; \
692692+ if (prng->initialized) { greatest_prng_step(ID); } \
693693+ BODY; \
694694+ if (!prng->initialized) { \
695695+ if (!greatest_prng_init_second_pass(ID, SD)) { break; } \
696696+ } else if (prng->count_run == prng->count_ceil) { \
697697+ break; \
698698+ } \
699699+ } while (!GREATEST_FAILURE_ABORT()); \
700700+ prng->count_run = prng->random_order = prng->initialized = 0; \
701701+ } while(0)
702702+703703+/* Include several function definitions in the main test file. */
704704+#define GREATEST_MAIN_DEFS() \
705705+ \
706706+/* Is FILTER a subset of NAME? */ \
707707+static int greatest_name_match(const char *name, const char *filter, \
708708+ int res_if_none) { \
709709+ size_t offset = 0; \
710710+ size_t filter_len = filter ? strlen(filter) : 0; \
711711+ if (filter_len == 0) { return res_if_none; } /* no filter */ \
712712+ if (greatest_info.exact_name_match && strlen(name) != filter_len) { \
713713+ return 0; /* ignore substring matches */ \
714714+ } \
715715+ while (name[offset] != '\0') { \
716716+ if (name[offset] == filter[0]) { \
717717+ if (0 == strncmp(&name[offset], filter, filter_len)) { \
718718+ return 1; \
719719+ } \
720720+ } \
721721+ offset++; \
722722+ } \
723723+ \
724724+ return 0; \
725725+} \
726726+ \
727727+static void greatest_buffer_test_name(const char *name) { \
728728+ struct greatest_run_info *g = &greatest_info; \
729729+ size_t len = strlen(name), size = sizeof(g->name_buf); \
730730+ memset(g->name_buf, 0x00, size); \
731731+ (void)strncat(g->name_buf, name, size - 1); \
732732+ if (g->name_suffix && (len + 1 < size)) { \
733733+ g->name_buf[len] = '_'; \
734734+ strncat(&g->name_buf[len+1], g->name_suffix, size-(len+2)); \
735735+ } \
736736+} \
737737+ \
738738+/* Before running a test, check the name filtering and \
739739+ * test shuffling state, if applicable, and then call setup hooks. */ \
740740+int greatest_test_pre(const char *name) { \
741741+ struct greatest_run_info *g = &greatest_info; \
742742+ int match; \
743743+ greatest_buffer_test_name(name); \
744744+ match = greatest_name_match(g->name_buf, g->test_filter, 1) && \
745745+ !greatest_name_match(g->name_buf, g->test_exclude, 0); \
746746+ if (GREATEST_LIST_ONLY()) { /* just listing test names */ \
747747+ if (match) { \
748748+ GREATEST_FPRINTF(GREATEST_STDOUT, " %s\n", g->name_buf); \
749749+ } \
750750+ goto clear; \
751751+ } \
752752+ if (match && (!GREATEST_FIRST_FAIL() || g->suite.failed == 0)) { \
753753+ struct greatest_prng *p = &g->prng[1]; \
754754+ if (p->random_order) { \
755755+ p->count++; \
756756+ if (!p->initialized || ((p->count - 1) != p->state)) { \
757757+ goto clear; /* don't run this test yet */ \
758758+ } \
759759+ } \
760760+ if (g->running_test) { \
761761+ fprintf(stderr, "Error: Test run inside another test.\n"); \
762762+ return 0; \
763763+ } \
764764+ GREATEST_SET_TIME(g->suite.pre_test); \
765765+ if (g->setup) { g->setup(g->setup_udata); } \
766766+ p->count_run++; \
767767+ g->running_test = 1; \
768768+ return 1; /* test should be run */ \
769769+ } else { \
770770+ goto clear; /* skipped */ \
771771+ } \
772772+clear: \
773773+ g->name_suffix = NULL; \
774774+ return 0; \
775775+} \
776776+ \
777777+static void greatest_do_pass(void) { \
778778+ struct greatest_run_info *g = &greatest_info; \
779779+ if (GREATEST_IS_VERBOSE()) { \
780780+ GREATEST_FPRINTF(GREATEST_STDOUT, "PASS %s: %s", \
781781+ g->name_buf, g->msg ? g->msg : ""); \
782782+ } else { \
783783+ GREATEST_FPRINTF(GREATEST_STDOUT, "."); \
784784+ } \
785785+ g->suite.passed++; \
786786+} \
787787+ \
788788+static void greatest_do_fail(void) { \
789789+ struct greatest_run_info *g = &greatest_info; \
790790+ if (GREATEST_IS_VERBOSE()) { \
791791+ GREATEST_FPRINTF(GREATEST_STDOUT, \
792792+ "FAIL %s: %s (%s:%u)", g->name_buf, \
793793+ g->msg ? g->msg : "", g->fail_file, g->fail_line); \
794794+ } else { \
795795+ GREATEST_FPRINTF(GREATEST_STDOUT, "F"); \
796796+ g->col++; /* add linebreak if in line of '.'s */ \
797797+ if (g->col != 0) { \
798798+ GREATEST_FPRINTF(GREATEST_STDOUT, "\n"); \
799799+ g->col = 0; \
800800+ } \
801801+ GREATEST_FPRINTF(GREATEST_STDOUT, "FAIL %s: %s (%s:%u)\n", \
802802+ g->name_buf, g->msg ? g->msg : "", \
803803+ g->fail_file, g->fail_line); \
804804+ } \
805805+ g->suite.failed++; \
806806+} \
807807+ \
808808+static void greatest_do_skip(void) { \
809809+ struct greatest_run_info *g = &greatest_info; \
810810+ if (GREATEST_IS_VERBOSE()) { \
811811+ GREATEST_FPRINTF(GREATEST_STDOUT, "SKIP %s: %s", \
812812+ g->name_buf, g->msg ? g->msg : ""); \
813813+ } else { \
814814+ GREATEST_FPRINTF(GREATEST_STDOUT, "s"); \
815815+ } \
816816+ g->suite.skipped++; \
817817+} \
818818+ \
819819+void greatest_test_post(int res) { \
820820+ GREATEST_SET_TIME(greatest_info.suite.post_test); \
821821+ if (greatest_info.teardown) { \
822822+ void *udata = greatest_info.teardown_udata; \
823823+ greatest_info.teardown(udata); \
824824+ } \
825825+ \
826826+ greatest_info.running_test = 0; \
827827+ if (res <= GREATEST_TEST_RES_FAIL) { \
828828+ greatest_do_fail(); \
829829+ } else if (res >= GREATEST_TEST_RES_SKIP) { \
830830+ greatest_do_skip(); \
831831+ } else if (res == GREATEST_TEST_RES_PASS) { \
832832+ greatest_do_pass(); \
833833+ } \
834834+ greatest_info.name_suffix = NULL; \
835835+ greatest_info.suite.tests_run++; \
836836+ greatest_info.col++; \
837837+ if (GREATEST_IS_VERBOSE()) { \
838838+ GREATEST_CLOCK_DIFF(greatest_info.suite.pre_test, \
839839+ greatest_info.suite.post_test); \
840840+ GREATEST_FPRINTF(GREATEST_STDOUT, "\n"); \
841841+ } else if (greatest_info.col % greatest_info.width == 0) { \
842842+ GREATEST_FPRINTF(GREATEST_STDOUT, "\n"); \
843843+ greatest_info.col = 0; \
844844+ } \
845845+ fflush(GREATEST_STDOUT); \
846846+} \
847847+ \
848848+static void report_suite(void) { \
849849+ if (greatest_info.suite.tests_run > 0) { \
850850+ GREATEST_FPRINTF(GREATEST_STDOUT, \
851851+ "\n%u test%s - %u passed, %u failed, %u skipped", \
852852+ greatest_info.suite.tests_run, \
853853+ greatest_info.suite.tests_run == 1 ? "" : "s", \
854854+ greatest_info.suite.passed, \
855855+ greatest_info.suite.failed, \
856856+ greatest_info.suite.skipped); \
857857+ GREATEST_CLOCK_DIFF(greatest_info.suite.pre_suite, \
858858+ greatest_info.suite.post_suite); \
859859+ GREATEST_FPRINTF(GREATEST_STDOUT, "\n"); \
860860+ } \
861861+} \
862862+ \
863863+static void update_counts_and_reset_suite(void) { \
864864+ greatest_info.setup = NULL; \
865865+ greatest_info.setup_udata = NULL; \
866866+ greatest_info.teardown = NULL; \
867867+ greatest_info.teardown_udata = NULL; \
868868+ greatest_info.passed += greatest_info.suite.passed; \
869869+ greatest_info.failed += greatest_info.suite.failed; \
870870+ greatest_info.skipped += greatest_info.suite.skipped; \
871871+ greatest_info.tests_run += greatest_info.suite.tests_run; \
872872+ memset(&greatest_info.suite, 0, sizeof(greatest_info.suite)); \
873873+ greatest_info.col = 0; \
874874+} \
875875+ \
876876+static int greatest_suite_pre(const char *suite_name) { \
877877+ struct greatest_prng *p = &greatest_info.prng[0]; \
878878+ if (!greatest_name_match(suite_name, greatest_info.suite_filter, 1) \
879879+ || (GREATEST_FAILURE_ABORT())) { return 0; } \
880880+ if (p->random_order) { \
881881+ p->count++; \
882882+ if (!p->initialized || ((p->count - 1) != p->state)) { \
883883+ return 0; /* don't run this suite yet */ \
884884+ } \
885885+ } \
886886+ p->count_run++; \
887887+ update_counts_and_reset_suite(); \
888888+ GREATEST_FPRINTF(GREATEST_STDOUT, "\n* Suite %s:\n", suite_name); \
889889+ GREATEST_SET_TIME(greatest_info.suite.pre_suite); \
890890+ return 1; \
891891+} \
892892+ \
893893+static void greatest_suite_post(void) { \
894894+ GREATEST_SET_TIME(greatest_info.suite.post_suite); \
895895+ report_suite(); \
896896+} \
897897+ \
898898+static void greatest_run_suite(greatest_suite_cb *suite_cb, \
899899+ const char *suite_name) { \
900900+ if (greatest_suite_pre(suite_name)) { \
901901+ suite_cb(); \
902902+ greatest_suite_post(); \
903903+ } \
904904+} \
905905+ \
906906+int greatest_do_assert_equal_t(const void *expd, const void *got, \
907907+ greatest_type_info *type_info, void *udata) { \
908908+ int eq = 0; \
909909+ if (type_info == NULL || type_info->equal == NULL) { return 0; } \
910910+ eq = type_info->equal(expd, got, udata); \
911911+ if (!eq) { \
912912+ if (type_info->print != NULL) { \
913913+ GREATEST_FPRINTF(GREATEST_STDOUT, "\nExpected: "); \
914914+ (void)type_info->print(expd, udata); \
915915+ GREATEST_FPRINTF(GREATEST_STDOUT, "\n Got: "); \
916916+ (void)type_info->print(got, udata); \
917917+ GREATEST_FPRINTF(GREATEST_STDOUT, "\n"); \
918918+ } \
919919+ } \
920920+ return eq; \
921921+} \
922922+ \
923923+static void greatest_usage(const char *name) { \
924924+ GREATEST_FPRINTF(GREATEST_STDOUT, \
925925+ "Usage: %s [-hlfavex] [-s SUITE] [-t TEST] [-x EXCLUDE]\n" \
926926+ " -h, --help print this Help\n" \
927927+ " -l List suites and tests, then exit (dry run)\n" \
928928+ " -f Stop runner after first failure\n" \
929929+ " -a Abort on first failure (implies -f)\n" \
930930+ " -v Verbose output\n" \
931931+ " -s SUITE only run suites containing substring SUITE\n" \
932932+ " -t TEST only run tests containing substring TEST\n" \
933933+ " -e only run exact name match for -s or -t\n" \
934934+ " -x EXCLUDE exclude tests containing substring EXCLUDE\n", \
935935+ name); \
936936+} \
937937+ \
938938+static void greatest_parse_options(int argc, char **argv) { \
939939+ int i = 0; \
940940+ for (i = 1; i < argc; i++) { \
941941+ if (argv[i][0] == '-') { \
942942+ char f = argv[i][1]; \
943943+ if ((f == 's' || f == 't' || f == 'x') && argc <= i + 1) { \
944944+ greatest_usage(argv[0]); exit(EXIT_FAILURE); \
945945+ } \
946946+ switch (f) { \
947947+ case 's': /* suite name filter */ \
948948+ greatest_set_suite_filter(argv[i + 1]); i++; break; \
949949+ case 't': /* test name filter */ \
950950+ greatest_set_test_filter(argv[i + 1]); i++; break; \
951951+ case 'x': /* test name exclusion */ \
952952+ greatest_set_test_exclude(argv[i + 1]); i++; break; \
953953+ case 'e': /* exact name match */ \
954954+ greatest_set_exact_name_match(); break; \
955955+ case 'f': /* first fail flag */ \
956956+ greatest_stop_at_first_fail(); break; \
957957+ case 'a': /* abort() on fail flag */ \
958958+ greatest_abort_on_fail(); break; \
959959+ case 'l': /* list only (dry run) */ \
960960+ greatest_list_only(); break; \
961961+ case 'v': /* first fail flag */ \
962962+ greatest_info.verbosity++; break; \
963963+ case 'h': /* help */ \
964964+ greatest_usage(argv[0]); exit(EXIT_SUCCESS); \
965965+ default: \
966966+ case '-': \
967967+ if (0 == strncmp("--help", argv[i], 6)) { \
968968+ greatest_usage(argv[0]); exit(EXIT_SUCCESS); \
969969+ } else if (0 == strcmp("--", argv[i])) { \
970970+ return; /* ignore following arguments */ \
971971+ } \
972972+ GREATEST_FPRINTF(GREATEST_STDOUT, \
973973+ "Unknown argument '%s'\n", argv[i]); \
974974+ greatest_usage(argv[0]); \
975975+ exit(EXIT_FAILURE); \
976976+ } \
977977+ } \
978978+ } \
979979+} \
980980+ \
981981+int greatest_all_passed(void) { return (greatest_info.failed == 0); } \
982982+ \
983983+void greatest_set_test_filter(const char *filter) { \
984984+ greatest_info.test_filter = filter; \
985985+} \
986986+ \
987987+void greatest_set_test_exclude(const char *filter) { \
988988+ greatest_info.test_exclude = filter; \
989989+} \
990990+ \
991991+void greatest_set_suite_filter(const char *filter) { \
992992+ greatest_info.suite_filter = filter; \
993993+} \
994994+ \
995995+void greatest_set_exact_name_match(void) { \
996996+ greatest_info.exact_name_match = 1; \
997997+} \
998998+ \
999999+void greatest_stop_at_first_fail(void) { \
10001000+ greatest_set_flag(GREATEST_FLAG_FIRST_FAIL); \
10011001+} \
10021002+ \
10031003+void greatest_abort_on_fail(void) { \
10041004+ greatest_set_flag(GREATEST_FLAG_ABORT_ON_FAIL); \
10051005+} \
10061006+ \
10071007+void greatest_list_only(void) { \
10081008+ greatest_set_flag(GREATEST_FLAG_LIST_ONLY); \
10091009+} \
10101010+ \
10111011+void greatest_get_report(struct greatest_report_t *report) { \
10121012+ if (report) { \
10131013+ report->passed = greatest_info.passed; \
10141014+ report->failed = greatest_info.failed; \
10151015+ report->skipped = greatest_info.skipped; \
10161016+ report->assertions = greatest_info.assertions; \
10171017+ } \
10181018+} \
10191019+ \
10201020+unsigned int greatest_get_verbosity(void) { \
10211021+ return greatest_info.verbosity; \
10221022+} \
10231023+ \
10241024+void greatest_set_verbosity(unsigned int verbosity) { \
10251025+ greatest_info.verbosity = (unsigned char)verbosity; \
10261026+} \
10271027+ \
10281028+void greatest_set_flag(greatest_flag_t flag) { \
10291029+ greatest_info.flags = (unsigned char)(greatest_info.flags | flag); \
10301030+} \
10311031+ \
10321032+void greatest_set_test_suffix(const char *suffix) { \
10331033+ greatest_info.name_suffix = suffix; \
10341034+} \
10351035+ \
10361036+void GREATEST_SET_SETUP_CB(greatest_setup_cb *cb, void *udata) { \
10371037+ greatest_info.setup = cb; \
10381038+ greatest_info.setup_udata = udata; \
10391039+} \
10401040+ \
10411041+void GREATEST_SET_TEARDOWN_CB(greatest_teardown_cb *cb, void *udata) { \
10421042+ greatest_info.teardown = cb; \
10431043+ greatest_info.teardown_udata = udata; \
10441044+} \
10451045+ \
10461046+static int greatest_string_equal_cb(const void *expd, const void *got, \
10471047+ void *udata) { \
10481048+ size_t *size = (size_t *)udata; \
10491049+ return (size != NULL \
10501050+ ? (0 == strncmp((const char *)expd, (const char *)got, *size)) \
10511051+ : (0 == strcmp((const char *)expd, (const char *)got))); \
10521052+} \
10531053+ \
10541054+static int greatest_string_printf_cb(const void *t, void *udata) { \
10551055+ (void)udata; /* note: does not check \0 termination. */ \
10561056+ return GREATEST_FPRINTF(GREATEST_STDOUT, "%s", (const char *)t); \
10571057+} \
10581058+ \
10591059+greatest_type_info greatest_type_info_string = { \
10601060+ greatest_string_equal_cb, greatest_string_printf_cb, \
10611061+}; \
10621062+ \
10631063+static int greatest_memory_equal_cb(const void *expd, const void *got, \
10641064+ void *udata) { \
10651065+ greatest_memory_cmp_env *env = (greatest_memory_cmp_env *)udata; \
10661066+ return (0 == memcmp(expd, got, env->size)); \
10671067+} \
10681068+ \
10691069+/* Hexdump raw memory, with differences highlighted */ \
10701070+static int greatest_memory_printf_cb(const void *t, void *udata) { \
10711071+ greatest_memory_cmp_env *env = (greatest_memory_cmp_env *)udata; \
10721072+ const unsigned char *buf = (const unsigned char *)t; \
10731073+ unsigned char diff_mark = ' '; \
10741074+ FILE *out = GREATEST_STDOUT; \
10751075+ size_t i, line_i, line_len = 0; \
10761076+ int len = 0; /* format hexdump with differences highlighted */ \
10771077+ for (i = 0; i < env->size; i+= line_len) { \
10781078+ diff_mark = ' '; \
10791079+ line_len = env->size - i; \
10801080+ if (line_len > 16) { line_len = 16; } \
10811081+ for (line_i = i; line_i < i + line_len; line_i++) { \
10821082+ if (env->exp[line_i] != env->got[line_i]) diff_mark = 'X'; \
10831083+ } \
10841084+ len += GREATEST_FPRINTF(out, "\n%04x %c ", \
10851085+ (unsigned int)i, diff_mark); \
10861086+ for (line_i = i; line_i < i + line_len; line_i++) { \
10871087+ int m = env->exp[line_i] == env->got[line_i]; /* match? */ \
10881088+ len += GREATEST_FPRINTF(out, "%02x%c", \
10891089+ buf[line_i], m ? ' ' : '<'); \
10901090+ } \
10911091+ for (line_i = 0; line_i < 16 - line_len; line_i++) { \
10921092+ len += GREATEST_FPRINTF(out, " "); \
10931093+ } \
10941094+ GREATEST_FPRINTF(out, " "); \
10951095+ for (line_i = i; line_i < i + line_len; line_i++) { \
10961096+ unsigned char c = buf[line_i]; \
10971097+ len += GREATEST_FPRINTF(out, "%c", isprint(c) ? c : '.'); \
10981098+ } \
10991099+ } \
11001100+ len += GREATEST_FPRINTF(out, "\n"); \
11011101+ return len; \
11021102+} \
11031103+ \
11041104+void greatest_prng_init_first_pass(int id) { \
11051105+ greatest_info.prng[id].random_order = 1; \
11061106+ greatest_info.prng[id].count_run = 0; \
11071107+} \
11081108+ \
11091109+int greatest_prng_init_second_pass(int id, unsigned long seed) { \
11101110+ struct greatest_prng *p = &greatest_info.prng[id]; \
11111111+ if (p->count == 0) { return 0; } \
11121112+ p->count_ceil = p->count; \
11131113+ for (p->m = 1; p->m < p->count; p->m <<= 1) {} \
11141114+ p->state = seed & 0x1fffffff; /* only use lower 29 bits */ \
11151115+ p->a = 4LU * p->state; /* to avoid overflow when */ \
11161116+ p->a = (p->a ? p->a : 4) | 1; /* multiplied by 4 */ \
11171117+ p->c = 2147483647; /* and so p->c ((2 ** 31) - 1) is */ \
11181118+ p->initialized = 1; /* always relatively prime to p->a. */ \
11191119+ fprintf(stderr, "init_second_pass: a %lu, c %lu, state %lu\n", \
11201120+ p->a, p->c, p->state); \
11211121+ return 1; \
11221122+} \
11231123+ \
11241124+/* Step the pseudorandom number generator until its state reaches \
11251125+ * another test ID between 0 and the test count. \
11261126+ * This use a linear congruential pseudorandom number generator, \
11271127+ * with the power-of-two ceiling of the test count as the modulus, the \
11281128+ * masked seed as the multiplier, and a prime as the increment. For \
11291129+ * each generated value < the test count, run the corresponding test. \
11301130+ * This will visit all IDs 0 <= X < mod once before repeating, \
11311131+ * with a starting position chosen based on the initial seed. \
11321132+ * For details, see: Knuth, The Art of Computer Programming \
11331133+ * Volume. 2, section 3.2.1. */ \
11341134+void greatest_prng_step(int id) { \
11351135+ struct greatest_prng *p = &greatest_info.prng[id]; \
11361136+ do { \
11371137+ p->state = ((p->a * p->state) + p->c) & (p->m - 1); \
11381138+ } while (p->state >= p->count_ceil); \
11391139+} \
11401140+ \
11411141+void GREATEST_INIT(void) { \
11421142+ /* Suppress unused function warning if features aren't used */ \
11431143+ (void)greatest_run_suite; \
11441144+ (void)greatest_parse_options; \
11451145+ (void)greatest_prng_step; \
11461146+ (void)greatest_prng_init_first_pass; \
11471147+ (void)greatest_prng_init_second_pass; \
11481148+ (void)greatest_set_test_suffix; \
11491149+ \
11501150+ memset(&greatest_info, 0, sizeof(greatest_info)); \
11511151+ greatest_info.width = GREATEST_DEFAULT_WIDTH; \
11521152+ GREATEST_SET_TIME(greatest_info.begin); \
11531153+} \
11541154+ \
11551155+/* Report passes, failures, skipped tests, the number of \
11561156+ * assertions, and the overall run time. */ \
11571157+void GREATEST_PRINT_REPORT(void) { \
11581158+ if (!GREATEST_LIST_ONLY()) { \
11591159+ update_counts_and_reset_suite(); \
11601160+ GREATEST_SET_TIME(greatest_info.end); \
11611161+ GREATEST_FPRINTF(GREATEST_STDOUT, \
11621162+ "\nTotal: %u test%s", \
11631163+ greatest_info.tests_run, \
11641164+ greatest_info.tests_run == 1 ? "" : "s"); \
11651165+ GREATEST_CLOCK_DIFF(greatest_info.begin, \
11661166+ greatest_info.end); \
11671167+ GREATEST_FPRINTF(GREATEST_STDOUT, ", %u assertion%s\n", \
11681168+ greatest_info.assertions, \
11691169+ greatest_info.assertions == 1 ? "" : "s"); \
11701170+ GREATEST_FPRINTF(GREATEST_STDOUT, \
11711171+ "Pass: %u, fail: %u, skip: %u.\n", \
11721172+ greatest_info.passed, \
11731173+ greatest_info.failed, greatest_info.skipped); \
11741174+ } \
11751175+} \
11761176+ \
11771177+greatest_type_info greatest_type_info_memory = { \
11781178+ greatest_memory_equal_cb, greatest_memory_printf_cb, \
11791179+}; \
11801180+ \
11811181+greatest_run_info greatest_info
11821182+11831183+/* Handle command-line arguments, etc. */
11841184+#define GREATEST_MAIN_BEGIN() \
11851185+ do { \
11861186+ GREATEST_INIT(); \
11871187+ greatest_parse_options(argc, argv); \
11881188+ } while (0)
11891189+11901190+/* Report results, exit with exit status based on results. */
11911191+#define GREATEST_MAIN_END() \
11921192+ do { \
11931193+ GREATEST_PRINT_REPORT(); \
11941194+ return (greatest_all_passed() ? EXIT_SUCCESS : EXIT_FAILURE); \
11951195+ } while (0)
11961196+11971197+/* Make abbreviations without the GREATEST_ prefix for the
11981198+ * most commonly used symbols. */
11991199+#if GREATEST_USE_ABBREVS
12001200+#define TEST GREATEST_TEST
12011201+#define SUITE GREATEST_SUITE
12021202+#define SUITE_EXTERN GREATEST_SUITE_EXTERN
12031203+#define RUN_TEST GREATEST_RUN_TEST
12041204+#define RUN_TEST1 GREATEST_RUN_TEST1
12051205+#define RUN_SUITE GREATEST_RUN_SUITE
12061206+#define IGNORE_TEST GREATEST_IGNORE_TEST
12071207+#define ASSERT GREATEST_ASSERT
12081208+#define ASSERTm GREATEST_ASSERTm
12091209+#define ASSERT_FALSE GREATEST_ASSERT_FALSE
12101210+#define ASSERT_EQ GREATEST_ASSERT_EQ
12111211+#define ASSERT_NEQ GREATEST_ASSERT_NEQ
12121212+#define ASSERT_GT GREATEST_ASSERT_GT
12131213+#define ASSERT_GTE GREATEST_ASSERT_GTE
12141214+#define ASSERT_LT GREATEST_ASSERT_LT
12151215+#define ASSERT_LTE GREATEST_ASSERT_LTE
12161216+#define ASSERT_EQ_FMT GREATEST_ASSERT_EQ_FMT
12171217+#define ASSERT_IN_RANGE GREATEST_ASSERT_IN_RANGE
12181218+#define ASSERT_EQUAL_T GREATEST_ASSERT_EQUAL_T
12191219+#define ASSERT_STR_EQ GREATEST_ASSERT_STR_EQ
12201220+#define ASSERT_STRN_EQ GREATEST_ASSERT_STRN_EQ
12211221+#define ASSERT_MEM_EQ GREATEST_ASSERT_MEM_EQ
12221222+#define ASSERT_ENUM_EQ GREATEST_ASSERT_ENUM_EQ
12231223+#define ASSERT_FALSEm GREATEST_ASSERT_FALSEm
12241224+#define ASSERT_EQm GREATEST_ASSERT_EQm
12251225+#define ASSERT_NEQm GREATEST_ASSERT_NEQm
12261226+#define ASSERT_GTm GREATEST_ASSERT_GTm
12271227+#define ASSERT_GTEm GREATEST_ASSERT_GTEm
12281228+#define ASSERT_LTm GREATEST_ASSERT_LTm
12291229+#define ASSERT_LTEm GREATEST_ASSERT_LTEm
12301230+#define ASSERT_EQ_FMTm GREATEST_ASSERT_EQ_FMTm
12311231+#define ASSERT_IN_RANGEm GREATEST_ASSERT_IN_RANGEm
12321232+#define ASSERT_EQUAL_Tm GREATEST_ASSERT_EQUAL_Tm
12331233+#define ASSERT_STR_EQm GREATEST_ASSERT_STR_EQm
12341234+#define ASSERT_STRN_EQm GREATEST_ASSERT_STRN_EQm
12351235+#define ASSERT_MEM_EQm GREATEST_ASSERT_MEM_EQm
12361236+#define ASSERT_ENUM_EQm GREATEST_ASSERT_ENUM_EQm
12371237+#define PASS GREATEST_PASS
12381238+#define FAIL GREATEST_FAIL
12391239+#define SKIP GREATEST_SKIP
12401240+#define PASSm GREATEST_PASSm
12411241+#define FAILm GREATEST_FAILm
12421242+#define SKIPm GREATEST_SKIPm
12431243+#define SET_SETUP GREATEST_SET_SETUP_CB
12441244+#define SET_TEARDOWN GREATEST_SET_TEARDOWN_CB
12451245+#define CHECK_CALL GREATEST_CHECK_CALL
12461246+#define SHUFFLE_TESTS GREATEST_SHUFFLE_TESTS
12471247+#define SHUFFLE_SUITES GREATEST_SHUFFLE_SUITES
12481248+12491249+#ifdef GREATEST_VA_ARGS
12501250+#define RUN_TESTp GREATEST_RUN_TESTp
12511251+#endif
12521252+12531253+#if GREATEST_USE_LONGJMP
12541254+#define ASSERT_OR_LONGJMP GREATEST_ASSERT_OR_LONGJMP
12551255+#define ASSERT_OR_LONGJMPm GREATEST_ASSERT_OR_LONGJMPm
12561256+#define FAIL_WITH_LONGJMP GREATEST_FAIL_WITH_LONGJMP
12571257+#define FAIL_WITH_LONGJMPm GREATEST_FAIL_WITH_LONGJMPm
12581258+#endif
12591259+12601260+#endif /* USE_ABBREVS */
12611261+12621262+#if defined(__cplusplus) && !defined(GREATEST_NO_EXTERN_CPLUSPLUS)
12631263+}
12641264+#endif
12651265+12661266+#endif