797 Commits
Author SHA1 Message Date
Patrick Pelissier 62c8ac3e5d V0.6.0 2021-11-11 19:59:19 +01:00
Patrick Pelissier 1d7e93251c Fix overflow of one element in deque _remove 2021-11-11 19:59:19 +01:00
Patrick Pelissier 92fa4691d1 Add comment about the non presence of _it_remove 2021-11-09 21:20:16 +01:00
Patrick Pelissier a20fdf4713 Update documentation 2021-11-06 23:21:16 +01:00
Patrick Pelissier 570dedf1c3 Factorize _size & _empty_p for both dict 2021-11-06 13:54:17 +01:00
Patrick Pelissier 59e5c873ad Factorize _equal_p for both dict 2021-11-06 13:45:27 +01:00
Patrick Pelissier 8dbcdf9991 Uniformize field name between classic dict & OA dict 2021-11-06 13:38:49 +01:00
Patrick Pelissier cd43b50068 Fix name of method 2021-11-06 13:38:29 +01:00
Patrick Pelissier c0413a26f9 Add more example 2021-11-03 21:21:56 +01:00
Patrick Pelissier b2d3d86e0c Add alternative macro M_TEST_METHOD_ALTER_P 2021-11-03 20:54:03 +01:00
Patrick Pelissier bc7552f4a8 Update container summary 2021-11-03 20:53:31 +01:00
Patrick Pelissier 28ae13092f Workaround for MacOs special make 2021-11-02 18:42:41 +01:00
Patrick Pelissier 1f561da43f Add doc for deque _remove 2021-11-02 18:35:09 +01:00
Patrick Pelissier ef8dcda196 Add tests for deque _remove 2021-11-02 18:32:26 +01:00
Patrick Pelissier cf9eb892cf Update & finish deque _remove algorithm 2021-11-02 18:32:14 +01:00
Patrick Pelissier ffa1e2e59c Add WIP deque_remove method 2021-11-02 08:43:42 +01:00
Patrick Pelissier 9549e82b04 Remove launch of check-stl on MacOS as sanitizer=leak is not supported by clang on this system 2021-10-31 00:29:43 +02:00
Patrick Pelissier 50261e390e Update forgotten rename 2021-10-31 00:14:10 +02:00
Patrick Pelissier 618fc99cda Update Continuous Integration 2021-10-31 00:12:01 +02:00
Patrick Pelissier a9fc7e15f8 Rename GET_SET_KEY operator in SAFE_GET_KEY operator 2021-10-30 23:57:50 +02:00
Patrick Pelissier 6b064870f5 Rename CLEAN operator in RESET operator 2021-10-30 23:26:27 +02:00
Patrick Pelissier d78c50be3b Add new files in Makefile 2021-10-30 00:29:53 +02:00
Patrick Pelissier c96cea5a13 Port the examples to rename _get_at to _safe_get 2021-10-30 00:17:15 +02:00
Patrick Pelissier 51d4e930f5 Rename the suffix _get_at to the _safe_get suffix
(Better & clearer naming of the function)
2021-10-30 00:04:07 +02:00
Patrick Pelissier e650addfe4 Replace _clean into _reset (Fix issues for C11 build) 2021-10-28 18:42:15 +02:00
Patrick Pelissier 30afcb45d8 Replace _clean into _reset 2021-10-28 18:32:53 +02:00
Patrick Pelissier e10c3586a3 Rename BITSET & CONCURRENT _clean in _reset to avoid confusing _clean & _clear functions. See #97 2021-10-28 18:13:00 +02:00
Patrick Pelissier 836d892832 Rename BUFFER, I-LIST, PRIOQUEUE & SHARED _clean in _reset to avoid confusing _clean & _clear functions. See #97 2021-10-28 18:08:07 +02:00
Patrick Pelissier 826d251ffe Rename RBTREE & BPTREE _clean in _reset to avoid confusing _clean & _clear functions. See #97 2021-10-28 17:55:54 +02:00
Patrick Pelissier 510cd062ba Rename DICT, TUPLE & VARIANT _clean in _reset to avoid confusing _clean & _clear functions. See #97 2021-10-28 17:51:17 +02:00
Patrick Pelissier 2695cd6f3e Rename DEQUE _clean in _reset to avoid confusing _clean & _clear functions. See #97 2021-10-28 17:40:56 +02:00
Patrick Pelissier f6e3cbbb65 Rename LIST _clean in _reset to avoid confusing _clean & _clear functions. See #97 2021-10-28 17:38:18 +02:00
Patrick Pelissier f172bbaad2 Rename ARRAY _clean in _reset to avoid confusing _clean & _clear functions. See #97 2021-10-28 17:32:02 +02:00
Patrick Pelissier 9176953a8e Rename string_clean in string_reset to avoid confusing _clean & _clear functions. See #97 2021-10-28 17:27:41 +02:00
Patrick Pelissier ae6b87d646 Optimization in case of small constant strings 2021-10-24 21:48:02 +02:00
Patrick Pelissier f719b2387a Remove file 2021-10-14 21:28:26 +02:00
Patrick Pelissier 5bfa8321d0 Add check dict-set against STL 2021-10-14 21:26:02 +02:00
Patrick Pelissier e99fd23e69 Don't export IT_REF for DICT_SET as they should not be updated directly by algorithm 2021-10-14 21:23:37 +02:00
Patrick Pelissier 5057366fb2 Update documentation for RBTREE _remove 2021-10-10 20:36:02 +02:00
Patrick Pelissier 44801b8b91 Add more tests for _remove (that triggered an issue in _previous) 2021-10-10 20:35:44 +02:00
Patrick Pelissier 9eabc86bdd Fix issue in _next / _previous in some corner cases. Fix issue in _remove (IT was not updated to next item) 2021-10-10 20:35:18 +02:00
Patrick Pelissier fbc8f407eb Add test for method _remove 2021-10-10 10:18:06 +02:00
Patrick Pelissier 09a8b93634 Add method _remove for RBTREE 2021-10-10 10:17:55 +02:00
Patrick Pelissier 2caa7b77e7 Add check of RBTREE 2021-10-10 10:04:48 +02:00
Patrick Pelissier c057247126 Add missing exported method 2021-10-10 10:01:44 +02:00
Patrick Pelissier 0899be21c3 Add support for seed (set/random) for rand 2021-10-10 09:36:35 +02:00
Patrick Pelissier c29c9f9ccd Remove obsolete UPDATE operator 2021-10-09 17:57:49 +02:00
Patrick Pelissier c12f698f32 Restore exe target 2021-10-09 17:27:53 +02:00
Patrick Pelissier d6a8a6d159 Add test for _reserver and _resize 2021-10-09 17:25:43 +02:00
Patrick Pelissier 7bf325f91a Update recent framework to compute dependencies 2021-10-09 17:25:13 +02:00
Patrick Pelissier fdfff0c5c5 Add framework to test containers againts C++ library 2021-10-09 16:55:51 +02:00
Patrick Pelissier 4409f613e0 Add test more complete cases for the last issue 2021-10-09 10:11:27 +02:00
Patrick Pelissier 9de644b0f3 Fix issue in _pop_front & _front method that corrupts the deque in some cases 2021-10-09 10:11:02 +02:00
Patrick Pelissier 3e36363d28 Fix format 2021-10-09 10:08:13 +02:00
Patrick Pelissier 4f1d1a949c Document _get_at method for dict 2021-10-08 20:47:18 +02:00
Patrick Pelissier e52f3b8b30 Add more test cases for deque _next / _previous 2021-10-07 21:47:49 +02:00
Patrick Pelissier 36916e7b3d Fix issue in deque _next and deque _previous methods in some corner cases 2021-10-07 21:47:20 +02:00
Patrick Pelissier ba778e9bd2 Simplify 2021-10-07 21:40:42 +02:00
Patrick Pelissier df7112489a Add tag for identifying C code in documentation 2021-10-05 00:28:31 +02:00
Patrick Pelissier d9c203736f Update examples section 2021-10-04 20:36:39 +02:00
Patrick Pelissier 2b61ffa784 Ignore backup files 2021-10-02 19:15:03 +02:00
Patrick Pelissier ba85640172 Add bench for CTL library 2021-10-02 19:14:01 +02:00
Patrick Pelissier 4d21ad5050 Update 2021-10-02 19:13:10 +02:00
Patrick Pelissier aae14de62b Update documentation 2021-10-02 13:22:12 +02:00
Patrick Pelissier 70fa621745 Add test function for _splice function 2021-10-02 13:09:51 +02:00
Patrick Pelissier e97f4f7f41 Document _splice function for dictionary 2021-10-02 13:09:18 +02:00
Patrick Pelissier 7a08ddce9e Remove UPDATE opertor as there are no default operators that define it (and no one uses it as it is poorly documented). Replace by SET for RB-THREE. Replace by ADD for the splice function of dictionary 2021-10-02 13:06:30 +02:00
Patrick Pelissier e19c9d31a8 Update comments 2021-10-01 07:41:23 +02:00
Patrick Pelissier 51ae5f9f0c Fix spelling 2021-10-01 07:41:11 +02:00
Patrick Pelissier 22e8133f95 Test for corrected issue of IT_INSERT (Wrong behavior if IT==END) 2021-09-29 23:30:20 +02:00
Patrick Pelissier c2e19fed01 Fix issue in IT_INSERT (Wrong behavior if IT==END) 2021-09-29 23:29:57 +02:00
Patrick Pelissier 274afc9978 Fix syntax 2021-09-24 23:26:23 +02:00
Patrick Pelissier 0c337836ca Add CTL library as reference 2021-09-24 23:23:57 +02:00
Patrick Pelissier 1a3e694e20 Add new example of different containers 2021-09-23 23:06:24 +02:00
Patrick Pelissier a0572b63b1 Update documentation for tuple 2021-09-23 23:04:10 +02:00
Patrick Pelissier 1765d8ef06 Update test for testing new possibility of the tuples 2021-09-23 23:04:00 +02:00
Patrick Pelissier 1e00a102e8 TUPLE: Defined HASH/CMP/EQUAL methods if at least ONE methods is defined in the fields. Fields that don't have or have disabled method are supposed to be secondary fields that are not pertinent for comparing the objects. 2021-09-23 23:03:30 +02:00
Patrick Pelissier 61f8dcdbae Add string_set_char function 2021-09-22 23:07:35 +02:00
Patrick Pelissier 39eeb3aec7 Fix buffer overflow in ARRAY _pop_at function (reported by tyrone718) 2021-09-18 09:52:33 +02:00
Patrick Pelissier 2178dcfcab Add LIST_INIT_VALUE & LIST_DUAL_PUSH_INIT_VALUE. 2021-08-15 21:55:09 +02:00
Patrick Pelissier f8b4f44105 Add ARRAY_INIT_VALUE 2021-08-15 21:44:36 +02:00
Patrick Pelissier 9c2468c2b7 Update comments. 2021-08-15 21:27:54 +02:00
Patrick Pelissier 3d5cc55d0a Adding assembly generation for mserial-json
in order to check proper & full inlining.
2021-08-09 10:30:53 +02:00
Patrick Pelissier 5b9cccd2dd Adding more macros not to be expanded in coverage mode 2021-08-09 10:30:04 +02:00
Patrick Pelissier 103b2ab79b Fix C++ 32 bits error on Ubuntu. 2021-08-07 17:15:45 +02:00
Patrick Pelissier 05f1cd784c Add support of GCC Static Analyzer
It seems to report only false positive.
2021-08-07 17:07:38 +02:00
Patrick Pelissier 6e6754f84e Activate tests for C++ 32 bits. 2021-08-07 10:28:19 +02:00
Patrick Pelissier 33ef448a86 Update documentation. 2021-08-07 10:27:56 +02:00
Patrick Pelissier 8ce59c2e9d Maintenance:
* update comments
* simplify code.
2021-08-07 00:34:18 +02:00
Patrick Pelissier 85a363d325 Update definition of returned iterator of _it_from of RB tree
from the greatest element of 'rbtree' lower of equal than 'data'
to the lowest element of the tree 'rbtree' greater or equal than 'data'

It is more logical and natural:
if you have a tree of elements between [2, 4], and you want
to iterate all elements from 0 to 10, the old definition doesn't allow
you to iterate easily over this subset.
2021-07-16 22:46:44 +02:00
Patrick Pelissier 7dc1a9dc0e Update RB Tree:
* Fix issue of the searched element is the root node (See #93)
for _it_from. It now returns a proper iterator.

* Update _it_from to match the last documentation:
if there is no element lower or equal to the searched node,
it returns a null iterator.

* Update _it_while_p so that it returns false if it is null iterator.
2021-07-16 21:47:37 +02:00
Patrick Pelissier 983d90b731 * Complete tests on iterators to be more exhaustive.
* Add tests on _it_from/_it_until_p/_it_while_p.
2021-07-16 21:46:57 +02:00
Patrick Pelissier f307762801 Update document of _it_from, _it_until_p, _it_while_p:
* _it_from: if there is no element that matches the condition,
it returns a null iterator, which is more coherent.
* _it_until_p: clarify condition if the iterator is null.
* _it_while_p: clarify condition if the iterator is null.
2021-07-16 21:42:55 +02:00
Patrick Pelissier 7924798e7a Update names of contract macros as per macro renaming 2021-07-16 21:41:59 +02:00
Patrick Pelissier e46bbaffb9 Avoid GCC warning (-Wstringop-truncation) 2021-07-05 23:14:21 +02:00
Patrick Pelissier 0171c49413 Unlikely some if conditions. 2021-07-05 22:45:57 +02:00
Patrick Pelissier a79cd9da97 Fix issue for RB Tree _it_equal_p method
if both iterators are equal and are associated
to a RB tree without any element.
2021-07-05 22:44:58 +02:00
Patrick Pelissier 408959c927 Be more precise in the bound check. 2021-07-05 22:32:19 +02:00
Patrick Pelissier ac4d93fe29 Clean RB Tree _pop_at to avoid an aliasing issue. 2021-07-05 20:21:26 +02:00
Patrick Pelissier 82d224fa66 Clean up documentation 2021-07-05 20:19:00 +02:00
Patrick Pelissier a5b6d8e391 Rewrite assertion to be more robust. 2021-07-04 00:20:10 +02:00
Patrick Pelissier 7f79abec3f Fix issue with INIT_WITH of array/list/....
combined with tuple:
_push_back_raw was used within an expanded macro
and as a consequence was expanded multiple times,
resulting in adding a new term in the sequence
for each field of the tuple.
2021-07-04 00:01:00 +02:00
Patrick Pelissier ca8d4aa97a Update _back & _front to return a modifiable ptr
(There is no real reasons to return a const pointer).
2021-07-03 23:59:19 +02:00
PpHd 690cef561c Merge pull request #92 from P-p-H-d/let-recur
Recursive INIT_WITH within M_LET
2021-07-01 22:33:34 +02:00
Patrick Pelissier 16ac4c556b Update documentation. 2021-07-01 22:14:17 +02:00
Patrick Pelissier 3c175b9199 Update documentation. 2021-07-01 22:12:15 +02:00
Patrick Pelissier a3827cc384 Add tests for new constructs
allowed in M_LET for tuples
2021-07-01 22:12:15 +02:00
Patrick Pelissier 353daecbd1 Comment new code. 2021-07-01 22:12:15 +02:00
Patrick Pelissier 368392fb8f Add CLEAN operator for default oplist
(same as INIT operator)
2021-07-01 22:12:15 +02:00
Patrick Pelissier 57441b2fc1 Add first draft of recursive
INIT_WITH macro for tuples.
2021-07-01 22:12:15 +02:00
Patrick Pelissier b225600238 Add internal functions for tuple
that are needed for future INIT_WITH support.
2021-07-01 22:12:15 +02:00
Patrick Pelissier 6b361e0d0c Add use of M_PRINT in C11 mode. 2021-07-01 22:12:15 +02:00
Patrick Pelissier 08668aa02b Add a new example of the new M_LET feature. 2021-07-01 22:12:15 +02:00
Patrick Pelissier 3d3eb6f1d2 Update tests to new syntax of M_LET. 2021-07-01 22:12:15 +02:00
Patrick Pelissier 9bd820c652 Force use of INIT_WITH for function object. 2021-07-01 22:12:15 +02:00
Patrick Pelissier 0e960ec23f Force use of INIT_WITH within M_LET. 2021-07-01 22:12:15 +02:00
Patrick Pelissier ca65d81b60 * Fix conflict between M_MAP2 /M_MAP2B
(this arises through M_LET & M_GET_METHOD)

* Rename M_GET_OPPROPERTY into M_GET_PROPERTY

* M_LET can be configured to always use INIT_WITH for special kind of objects.
2021-07-01 22:12:15 +02:00
Patrick Pelissier 23624a1d73 Remove M_EVAL from M_LET as it is not needed anymore. 2021-07-01 22:12:15 +02:00
Patrick Pelissier 3ac08b0395 Add test with a lot of different kind of M_LET with list of strings. 2021-07-01 22:12:15 +02:00
Patrick Pelissier dedb79dbc5 Use of new initializer macro 2021-07-01 22:12:15 +02:00
Patrick Pelissier 154b503bc6 Avoid using the input more than once in macros string_init_* (Avoid issues) 2021-07-01 22:12:15 +02:00
Patrick Pelissier 5c612ce521 Update M_LET to handle both set & init_with depending on the user syntax. Add M_INIT_WITH_VAI to use this new feature. 2021-07-01 22:12:15 +02:00
Patrick Pelissier 80582ac5ce Update as the minimum level of recursion is decreased 2021-07-01 22:12:15 +02:00
Patrick Pelissier 8e6af3bfeb Add note 2021-07-01 22:12:15 +02:00
Patrick Pelissier 61671d1b18 Minor fix 2021-07-01 22:12:15 +02:00
Patrick Pelissier aa3ad973d0 Add another recussive M_LET test 2021-07-01 22:12:15 +02:00
Patrick Pelissier a19a010d1e Add WIP version for a M_LET recursive 2021-07-01 22:12:14 +02:00
Patrick Pelissier 36003b6bb3 * Add support for extented variable for M_[F]PRINT
* Update documentation
* Add test.
2021-07-01 00:13:31 +02:00
Patrick Pelissier 3c83e4088c Add internal macro M_MERGE_ARGLIST 2021-06-20 11:06:19 +02:00
Patrick Pelissier 357feb9532 Update documentation as per lastest changes. 2021-06-19 22:47:13 +02:00
Patrick Pelissier 7e234cba65 Add test of M_FPRINT using string_t. 2021-06-19 22:46:58 +02:00
Patrick Pelissier 0535ceeaeb Add support of string_t by M_PRINT macro. 2021-06-19 22:46:41 +02:00
Patrick Pelissier e688f0b1df Add internal method M_GET_OPPROPERTY to get the subproperty of an oplist
Add test for such macro
Rename operator CLASS into PROPERTIES
2021-06-17 00:20:35 +02:00
Patrick Pelissier a950e15625 Adding method for NAME operator for basic containers 2021-06-12 11:11:30 +02:00
Patrick Pelissier cf8b198dac Fix issue in M_LET: if the INIT/INIT_SET/INIT_WITH uses the macro M_IF, it may be not expanded in some cases (since the M_CALL_* is used itself within an expanded tainted M_IF). Fix this by calling M_CALL_* outside the expanded M_IF. 2021-05-23 00:53:54 +02:00
Patrick Pelissier c75d5da02d Fix: use of M_CALL_INIT / M_CALL_CLEAR instead of M_GET_INIT / M_GET_CLEAR so that API transformation can be applied 2021-05-23 00:42:43 +02:00
Patrick Pelissier cdffb15066 Simplify code 2021-05-23 00:34:08 +02:00
Patrick Pelissier cd0ad0dba9 Factorize code 2021-05-23 00:31:23 +02:00
Patrick Pelissier d3be5dba96 Reduce number of created threads, as sometimes it hits the limits 2021-05-22 18:11:09 +02:00
Patrick Pelissier cb94a26a9f Update documentation 2021-05-22 17:33:46 +02:00
Patrick Pelissier 3c8b238e75 Add operator CLASS and new keywords 2021-05-22 17:33:34 +02:00
Patrick Pelissier 74202d52b3 Adding default value for LIMITS
enabling to avoid defining then for all types.
2021-04-16 23:23:42 +02:00
Patrick Pelissier 603c92cd0e Cleanup uneeded final comma separator 2021-04-10 23:27:49 +02:00
Patrick Pelissier e514d74f43 Update test to be more pertinent 2021-04-04 22:28:32 +02:00
Patrick Pelissier 970161464a Add constraint 2021-04-04 22:28:13 +02:00
Patrick Pelissier 3e7de27c00 Rename M_HASH_SEED into M_USE_HASH_SEED
as it a user overridable macro
(API break).
2021-04-03 23:15:12 +02:00
Patrick Pelissier e28d403216 Undo previous changes until further analysis (it broke CI) 2021-03-28 11:53:18 +02:00
Patrick Pelissier fdeb9f1322 Format 2021-03-28 11:48:59 +02:00
Patrick Pelissier 76fad21103 Update comments and naming 2021-03-28 11:48:59 +02:00
Patrick Pelissier 5d4fa31083 Update doc & comments 2021-03-28 11:48:58 +02:00
Patrick Pelissier c3858f4e63 Update documentation 2021-03-28 11:48:58 +02:00
Patrick Pelissier 2e0fc21878 Fix _push_move of SPSC. It shall take a pointer to the object, not the object itself as argument, just like the other _push_move 2021-03-28 11:48:58 +02:00
Patrick Pelissier 4b71bbec7e Protect key from being changed while iterating. 2021-03-28 11:13:55 +02:00
Patrick Pelissier 052989a5a2 Update m_serial_ll_ct to have more basic types. 2021-03-28 11:09:59 +02:00
Patrick Pelissier 60cfc63c4e Add static assertion. 2021-03-28 09:39:52 +02:00
Patrick Pelissier 60ef4c7f06 Fix documentation 2021-03-28 09:39:41 +02:00
Patrick Pelissier 58fc40d0f1 Update oplist 2021-03-28 09:32:23 +02:00
Patrick Pelissier 3d7e9e7c03 Add _get_at method for B+TREE 2021-03-28 09:29:04 +02:00
Patrick Pelissier 52e745f905 Update documentation of operators 2021-03-27 21:15:03 +01:00
Patrick Pelissier 8433fc178c Fix issue for union with visual & clang-cl 2021-03-20 13:16:10 +01:00
Patrick Pelissier 59807baa18 Fix several minor issues on m-buffer:
1) Fix performance issue if the buffer was not designed
to be thread safe. The internal numbers are in this cases
just plain numbers and not atomic numbers. This is done
through union. Fix #90

2) In case of thread safe buffer, put each item in a
separate cacheline. This ensures proper performance in
case there is several producers. This however
increases the consumption size.

3) Fix a data race issue: after the mutex is locked,
and before the test if the buffer is empty (through the
atomic read of its size). It is solved by performing a
memory acquire when testing if the buffer is empty.

4) Add more comments.
2021-03-20 13:01:51 +01:00
Patrick Pelissier 9b5b15e8cb Update comment 2021-03-16 21:43:09 +01:00
Patrick Pelissier 2c54b63c51 Update dev doc 2021-03-16 21:42:48 +01:00
Patrick Pelissier e4d1167274 Improve test suite to be more representative 2021-03-14 23:42:05 +01:00
Patrick Pelissier 2f10aba390 Workaround issue with address sanitizer 2021-03-14 21:26:04 +01:00
Patrick Pelissier a044fadec8 Fix minor warning in some compiler options 2021-03-14 11:00:05 +01:00
Patrick Pelissier 0edb6165b5 Fix buffer overflow if size=64*N 2021-03-13 23:39:26 +01:00
Patrick Pelissier 7d262f2450 Fix formatting 2021-03-13 23:08:04 +01:00
Patrick Pelissier fa30328572 Reduce allowed range for buffer to unsigned int. It should be more than enough for any scenario. 2021-03-13 22:43:01 +01:00
Patrick Pelissier b0cff7c6ac Remove git checkout HEAD^2 as per recommendation of CodeQL 2021-03-09 22:39:02 +01:00
Patrick Pelissier 50da9e803c Add documentation for m_serial_str_json 2021-03-09 22:12:44 +01:00
Patrick Pelissier 26252fedf5 Add test for JSON serialization over string 2021-03-09 22:12:29 +01:00
Patrick Pelissier 2dcda90c7b Add JSON serial over string 2021-03-09 22:12:16 +01:00
Patrick Pelissier b7d79c0a83 Fix issue for wrong formatted JSON (error not properly reported) 2021-03-09 20:56:13 +01:00
Patrick Pelissier ae285c0a01 Add also const string in serial object 2021-03-09 20:55:46 +01:00
Patrick Pelissier 07db846f3b Rename internal string functions to be compliant with new scheme. Not sure if this scheme will remain however (still searching for a better naming that fits all criteria). 2021-03-01 22:18:32 +01:00
Patrick Pelissier 3b6907b743 Add more test cases. 2021-02-23 16:24:46 +01:00
Patrick Pelissier 82e49c6214 Clarify doc. 2021-02-23 16:03:03 +01:00
Patrick Pelissier 8e9aa9cac4 Fix _min & _max for B+Tree
Make code match the documentation if there is no element in the tree.
2021-02-23 15:59:45 +01:00
Patrick Pelissier 5cd6c1dd36 Update Makefile by controlling when making dist that all files are properly referenced in the Makefile 2021-02-22 18:59:49 +01:00
Patrick Pelissier a98ce5ea91 Remove unused test file 2021-02-22 18:59:49 +01:00
Patrick Pelissier a4bb0fab8f Update documentation for bitset 2021-02-22 12:06:51 +01:00
Patrick Pelissier 7b2e242c94 Add function bitset_popcount 2021-02-22 12:06:46 +01:00
Patrick Pelissier 5fd6352a4e Add more tests for bitset_resize 2021-02-22 11:40:29 +01:00
Patrick Pelissier a82f2ba065 * Fix an issue in _pop_at. * Optimize code by ensuring that the last limbs is always properly masked (simplify algorithm) 2021-02-22 11:31:49 +01:00
Patrick Pelissier 3377acd9e6 Test another bit for _pop_at 2021-02-22 11:30:59 +01:00
Patrick Pelissier 709168652a Reformat and specify clz for bitset size = 0 2021-02-21 21:41:51 +01:00
Patrick Pelissier e25e9ba29b Make the contract of Array & Buffer fail after a clear. 2021-02-21 21:08:35 +01:00
Patrick Pelissier ed5eac6e9d Update doc 2021-02-21 21:08:35 +01:00
Patrick Pelissier 651768f012 Fix name in doc 2021-02-21 21:08:35 +01:00
Patrick Pelissier 88c0a881da Update 2021-02-20 00:22:24 +01:00
Patrick Pelissier 5b9dd504e5 Add chapter "Global User Customization" 2021-02-20 00:20:54 +01:00
Patrick Pelissier 165ec09061 Rename user customizable macros
to be compliant with other
and clearer that they can be customized.
2021-02-20 00:10:26 +01:00
Patrick Pelissier 6cc972bab2 Rename header define to be compliant with others. 2021-02-20 00:08:07 +01:00
Patrick Pelissier 333047fc4c Make assertions more robust.
Fix read out of bound (with test cases).
2021-02-14 00:15:43 +01:00
Patrick Pelissier 3e4a5932c2 Rename internal function / types.
Reformat
2021-02-13 11:45:16 +01:00
Patrick Pelissier e2f6b81a03 Remove M_LOCK from readme as it is obsolete. 2021-02-13 11:45:16 +01:00
Patrick Pelissier 0231aad947 Update coding rules. 2021-02-13 11:45:16 +01:00
Patrick Pelissier 6636800c5b Remove obsolete / deprecated function/macros. 2021-02-13 11:45:16 +01:00
Patrick Pelissier d1f41de0cb Rename internal functions
to use internal prefix.
2021-02-13 11:45:16 +01:00
Patrick Pelissier c4d339cb62 Rename internal interface. 2021-02-13 11:45:16 +01:00
Patrick Pelissier 56b2adc57d Fix internal name. 2021-02-13 11:45:16 +01:00
Patrick Pelissier a73bee2650 Micro-optimization of DICT_OA
by reducing the number of cmp instructions.
2021-02-13 11:45:16 +01:00
Patrick Pelissier 517da1b999 Rename generated internal functions
to avoid "poluting" userspace naming.
2021-02-13 11:45:05 +01:00
Patrick Pelissier 25497bd96f Factorize code so that _DEF macros use _DEF_AS ones 2021-02-07 23:04:59 +01:00
Patrick Pelissier d12b1edc39 Update doc 2021-02-07 23:04:45 +01:00
Patrick Pelissier 0515cfd068 Add macro M_GREATER_THAN_P & M_LESS_OR_EQUAL_P (src, tests, doc) 2021-02-07 09:53:13 +01:00
Patrick Pelissier e84bc9fc0d Fix link 2021-02-07 09:41:10 +01:00
Patrick Pelissier d85df43329 Replace UNERDLOW/OVERFLOW by M_UNDERFLOW/M_OVERFLOW as some systems (Windows/MacOS) perform '#define UNDERFLOW value' in their headers, preventing the detection at preprocessing time. 2021-02-07 09:36:00 +01:00
Patrick Pelissier 16e2e07d41 * Fix M_REVERSE as per the doc (don't add parenthesis on the returned arglist). * Update usage to take this into account. 2021-02-07 00:50:10 +01:00
Patrick Pelissier 57fcb4012b Update doc 2021-02-07 00:42:10 +01:00
Patrick Pelissier 5be981def3 Fix warning 2021-02-07 00:41:59 +01:00
Patrick Pelissier 493e38abfc Fix formatting 2021-02-07 00:31:15 +01:00
Patrick Pelissier 6e006d216b Add macro M_GREATER_OR_EQUAL_P (src, test, doc) 2021-02-07 00:25:47 +01:00
Patrick Pelissier da613ad188 * Add macro M_LESS_THAN_P (src, test, doc). * Robustify M_INC & M_DEC so that overflow & underflow keeps returning overflow & underflow 2021-02-07 00:10:55 +01:00
Patrick Pelissier 3dad326bea Update doc 2021-02-06 23:54:16 +01:00
Patrick Pelissier 480a791f4c Update tests 2021-02-06 23:41:04 +01:00
Patrick Pelissier 753c46ef14 Add OrderPP 2021-02-06 23:40:58 +01:00
Patrick Pelissier f2d5de252b Add M_FILTER and M_FILTER_C macros (src, tests, doc) 2021-02-06 23:24:55 +01:00
Patrick Pelissier 0cb1a8054f Add M_REPLICATE & M_REPLICATE_C (src, test, doc) 2021-02-06 22:32:38 +01:00
Patrick Pelissier 07eb5697ab Remove limitation of M_AS_STR to be called within a M_APPLY 2021-02-06 22:22:50 +01:00
Patrick Pelissier e4dc06a0e2 Update doc 2021-02-06 22:13:06 +01:00
Patrick Pelissier cd2012f33d Update doc 2021-02-06 21:58:52 +01:00
Patrick Pelissier 9eba30648d Rename M_INVERT into M_REVERSE to be more coherent with REVERSE operator 2021-02-06 21:58:45 +01:00
Patrick Pelissier 7e70371197 Format & comment code 2021-02-06 21:28:18 +01:00
Patrick Pelissier 527f6d8d9a Add metalang99 2021-02-06 21:05:26 +01:00
Patrick Pelissier 9ebc12a98f Update to 0.5.1 2021-02-06 21:03:19 +01:00
Patrick Pelissier bb21d9a6ad Update Makefile to control that both versions are the same when making a distribution 2021-02-06 21:00:25 +01:00
Patrick Pelissier ad39cdd393 Add some tests for new function 2021-02-05 00:17:18 +01:00
Patrick Pelissier 0de771036b Add M_REDUCE3
Add M_MAP3_C
Add operator LIMITS.
2021-02-05 00:11:44 +01:00
Patrick Pelissier 6d6afa4cfd Update doc 2021-01-29 20:43:46 +01:00
Patrick Pelissier 7546cbedd2 Update doc 2021-01-20 20:44:48 +01:00
Patrick Pelissier 8d5962eefd Update target html & doc 2021-01-20 20:44:36 +01:00
Patrick Pelissier 8597b0b8c0 Fix warning on clang and old gcc 2021-01-18 18:21:01 +01:00
Patrick Pelissier c625c39883 Add a new implementation of M_CSTR using GNU C extension which provides faster & smaller code 2021-01-18 18:16:45 +01:00
Patrick Pelissier bce86460fe Rewrite test cases to avoid potential warnings 2021-01-18 18:16:05 +01:00
Patrick Pelissier f002eebc83 Update constraint 2021-01-18 18:01:42 +01:00
Patrick Pelissier 139da2e49f Update example 2021-01-16 10:25:55 +01:00
Patrick Pelissier 91d40a0f43 V0.5.0 2021-01-13 20:18:01 +01:00
Patrick Pelissier 25fe26deaa Happy new year 2021-01-13 20:18:01 +01:00
Patrick Pelissier cd357c5eb7 Rewrite the wrappers of strncpy & strncat:
Add one argument about the allocation of the dest buffer
Theses wrappers are internal (so no impact to API)
and only used in a few place in m-string.
This make the wrappers able to use the function
strncpy_s & strncat_s for MSVC rather than using
reimplementation of the original functions.
2021-01-13 08:34:47 +01:00
Patrick Pelissier 561f67b3b9 Update list of ignored files 2021-01-13 08:27:00 +01:00
Patrick Pelissier 15a02e3306 Update final message 2021-01-10 20:04:14 +01:00
Patrick Pelissier 944d29e8bc Workaround CLANG preprocessor failure on Windows platform 2021-01-10 20:03:28 +01:00
Patrick Pelissier aefba70c1e Rework once again how to detect a failure in an application:
IF errorlevel 1 only works for positive error code
  IF not errorlevel 0 only works for negative error code
There are not reliable. So, use && and || instead.

Remove expected failure on test as all tests pass now
(and it was broken).
2021-01-10 18:08:48 +01:00
Patrick Pelissier c9ed4ba820 Fix compiler error with MSVC with new implementation of offsetof 2021-01-10 18:01:19 +01:00
Patrick Pelissier df97ea848c Fix error for C++ 2021-01-10 10:01:54 +01:00
Patrick Pelissier 93d810421d Fix warning with newest gcc 2021-01-10 09:57:07 +01:00
Patrick Pelissier f560839516 Add example of string_sets 2021-01-10 09:51:53 +01:00
Patrick Pelissier 8a9d5f6a00 Add macro string_sets (like string_cats) 2021-01-10 09:51:38 +01:00
Patrick Pelissier 5f05c1e169 Make stdarg an optional header. Some works remain to do to make stdio fully optional 2021-01-10 09:40:37 +01:00
Patrick Pelissier 3df2408ffb Add macro M_CSTR 2021-01-10 09:26:27 +01:00
Patrick Pelissier ffc2ec8c4b Fix format 2021-01-10 09:25:27 +01:00
Patrick Pelissier b0ebbb306e Update 2021-01-10 09:20:42 +01:00
Patrick Pelissier c3574aa290 Update comments 2021-01-10 09:02:52 +01:00
Patrick Pelissier eabc867c2a Rename used namespace for C++ to m_lib 2021-01-10 08:48:46 +01:00
Patrick Pelissier a03b2e80c6 Document string_cats 2021-01-07 22:13:10 +01:00
Patrick Pelissier c4f23640d5 Add test for string_cats 2021-01-07 22:13:10 +01:00
Patrick Pelissier a42b854f14 Add macro string_cats to concat multiple strings 2021-01-07 22:13:10 +01:00
Patrick Pelissier 9aa08bfc59 Add support for struct in M_AS_TYPE 2021-01-07 22:13:10 +01:00
Patrick Pelissier 06b79a6caa Add tests for M_AS_TYPE 2021-01-07 22:13:10 +01:00
Patrick Pelissier 6d533bd52a Add (internal) macro M_CONDITIONAL 2021-01-07 22:13:10 +01:00
Patrick Pelissier 1b4c608087 Rename operator TEST_EMPTY into EMPTY_P to be compliant with iterator operator 2021-01-07 22:13:10 +01:00
Patrick Pelissier 6ccc81fd92 Remove unused operator UPDATE_TYPE 2021-01-07 22:13:09 +01:00
Patrick Pelissier 6f7d3fcd79 Add limiation on M_EMPTY_P 2020-12-31 00:12:36 +01:00
Patrick Pelissier 7484dee707 Fix a corner case for M_EMPTY_P where it performs too much evaluation steps 2020-12-31 00:12:21 +01:00
Patrick Pelissier a580aaac83 Add more test cases for M_EMPTY_P 2020-12-31 00:11:37 +01:00
Patrick Pelissier 52bef353e0 Workaround WIN clang that claims to be C11 but fails to deliver a working assert.h (See #85) 2020-12-30 19:03:10 +01:00
Patrick Pelissier 826ecf76c0 Workaround a compiler warning 2020-12-30 19:02:00 +01:00
Patrick Pelissier 2cf5bff32d Fix negative error code termination for MSVS (See #86) 2020-12-30 17:58:43 +01:00
Patrick Pelissier 1377d7a1c2 Fix usage of strncpy_s and strncat_s
Provides a full wrapper around strncpy & strncat
(for MSVS as it complains on using strncpy & strncat).
See #86
2020-12-28 23:35:50 +01:00
Patrick Pelissier ab9284ca20 Update documentation 2020-12-27 10:44:41 +01:00
Patrick Pelissier 5dab01c1c7 Fix spelling 2020-12-26 09:08:42 +01:00
Patrick Pelissier f9c434401b Fix M_GET_STRING_ARG (See #84) 2020-12-26 09:00:39 +01:00
Patrick Pelissier 76b9f9a715 Add test cases for M_GET_STRING 2020-12-26 08:58:52 +01:00
Patrick Pelissier 2ee82c478b Remove useless type (see #82) 2020-12-24 10:58:51 +01:00
Patrick Pelissier 211121435d Fix warning in C++ mode with G++ 10 2020-12-24 08:13:44 +01:00
Patrick Pelissier fffd1702a5 CLANG 3.8 stdatomic works. Update minimun version 2020-12-24 07:35:45 +01:00
Patrick Pelissier 9aa99bf230 Update package list before installing multilib 2020-12-21 15:23:49 +01:00
Patrick Pelissier 1671ca8d67 Add more assertions 2020-12-21 15:16:16 +01:00
Patrick Pelissier ad16b310e1 Fix overflow issue in bitset_last_p (see #81) 2020-12-21 15:08:19 +01:00
Patrick Pelissier 4dbcfd25b3 Fix non support of break in M_LET_IF 2020-12-16 15:27:41 +01:00
Patrick Pelissier 01167b09c4 Add an example of M_LET_IF 2020-12-16 11:07:11 +01:00
Patrick Pelissier 15d0b86c62 Update documentation & add tests as per lastest changes 2020-12-16 11:07:11 +01:00
Patrick Pelissier edbcecb272 Add support for else condition in M_LET_IF. Fix also a bug in computing unique variable per line 2020-12-16 11:07:11 +01:00
Patrick Pelissier 1689db7b9c Fix spelling 2020-12-16 11:07:11 +01:00
Patrick Pelissier f5bc8796f7 Add functions:
* string_vprintf
* string_init_vprintf
2020-12-15 22:14:43 +01:00
Patrick Pelissier e893560a48 Add macros M_LET_IF and M_DEFER to help handling with runtime errors 2020-12-14 21:26:07 +01:00
Patrick Pelissier a4ff7c71f2 Update documentation 2020-12-13 00:18:53 +01:00
Patrick Pelissier 9f780805f0 Update 2020-12-10 07:59:28 +01:00
Patrick Pelissier 749273d1bb Update list of methods 2020-12-06 08:32:54 +01:00
Patrick Pelissier d8fd2e3e69 Update doc as per latest changes 2020-12-06 00:16:53 +01:00
Patrick Pelissier d443a84254 Remove deprecated funtion 2020-12-06 00:15:17 +01:00
Patrick Pelissier ef614b19ee Fix ISO C warning. 2020-12-05 18:33:26 +01:00
Patrick Pelissier 1c5c4aa50f Fix compatibility with C++
which doesn't support designated init.
2020-12-05 18:28:30 +01:00
Patrick Pelissier 5533ffffaa Add tests for intrusive shared pointers. 2020-12-05 18:14:38 +01:00
Patrick Pelissier 34c990e259 Add function _init_once for intrusive shared pointer 2020-12-05 18:14:22 +01:00
Patrick Pelissier 5f0b6b9f26 Fix format 2020-12-05 12:42:45 +01:00
Patrick Pelissier 26eb882a30 Rename tuple function :
* _init_set2 in _init_emplace
* _set2 in _emplace
due to better & clearer naming.
(API break)
2020-12-05 12:29:20 +01:00
Patrick Pelissier 4d0e799c7a Remove obsolete function. 2020-12-05 12:27:33 +01:00
Patrick Pelissier 6801f688a4 Clarify atomic thin layer limitation (see #79) 2020-12-01 07:27:14 +01:00
Patrick Pelissier bdf29af9e9 * Add DJB Xor hash * Rename function (see #78) 2020-11-29 22:05:24 +01:00
Patrick Pelissier 79dabfc52f Update documentation as per #76 2020-11-29 20:34:05 +01:00
Patrick Pelissier de2268c406 Factorization of comparaison by using memcmp 2020-11-29 20:06:56 +01:00
Patrick Pelissier 85ea1f40dc Use classic hash rather than fast one for C-String (fix assertion failure for C-String hash) 2020-11-29 19:36:28 +01:00
Patrick Pelissier f89ba94689 Add test for computing C-string hash (raise assertion failure) 2020-11-29 19:35:52 +01:00
Patrick Pelissier 0279dcc3cc Fix issue on MacOS 2020-11-25 22:56:51 +01:00
Patrick Pelissier 62c8e005bb Add a new example of array of strings. 2020-11-25 22:41:25 +01:00
Patrick Pelissier 2a28f8d407 Add string_init_printf 2020-11-25 22:41:11 +01:00
Patrick Pelissier 9802fc5098 Remove rapidstring as it is no longer maintained, and the author deleted the repository. 2020-11-24 23:04:33 +01:00
Patrick Pelissier f372a72fd8 Update list of libraries 2020-11-23 20:29:30 +01:00
Patrick Pelissier 9d661852b2 Factorization of replace_all function for all libraries 2020-11-23 20:14:17 +01:00
Patrick Pelissier b343d356c3 Add support for empty replaced string 2020-11-22 23:29:38 +01:00
Patrick Pelissier 2e4404ca7e Fix a (strange) warning for gcc 8 without assertions.
Add back the assertions as compile hints.
2020-11-22 23:20:04 +01:00
Patrick Pelissier 29eebaf38d Factorization of the allocation. 2020-11-22 23:11:09 +01:00
Patrick Pelissier d0d69aebfa Add final null char in computation of the needed size for the new function _replace_all 2020-11-22 23:09:37 +01:00
Patrick Pelissier 477c5853f1 Update bench to use new function. 2020-11-22 23:04:50 +01:00
Patrick Pelissier 55e7b3083a Add function string_replace_all[_str]
to replace all occurences of a string by another.
2020-11-22 23:04:32 +01:00
Patrick Pelissier 0b9e27fb7f Add note on 32 bits systems where atomic library is needed 2020-11-21 11:45:25 +01:00
Patrick Pelissier 36ac6d5104 Fix issue on single core system 2020-11-21 10:53:11 +01:00
Patrick Pelissier d898d6d4cc Remove duplicate function 2020-11-21 10:26:02 +01:00
Patrick Pelissier e7388929c4 Migrate to msys2 v2 for github actions. 2020-11-19 22:43:05 +01:00
Patrick Pelissier 45f8b31efc Add function string_subset 2020-11-19 22:31:33 +01:00
Patrick Pelissier ebf440731d Fix address sanitizer issue 2020-11-15 09:43:41 +01:00
Patrick Pelissier 501a4a65ec Add test cases 2020-11-15 09:39:29 +01:00
Patrick Pelissier 800d03f728 Update documentation. 2020-11-15 09:39:15 +01:00
Patrick Pelissier 19ff6bfeac Add equal_p method for m-prioqueue 2020-11-15 09:39:01 +01:00
Patrick Pelissier 24f5739a3b Update documentation. 2020-11-14 23:56:28 +01:00
Patrick Pelissier b658598e02 Update documentation for _update & _erase of priority queues. 2020-11-14 23:48:46 +01:00
Patrick Pelissier 47343a2893 Add proper test cases for _update of priority queue 2020-11-14 23:48:23 +01:00
Patrick Pelissier c1f99359be Fix issue in update of priority in priority queue:
* Rename _update_further into _update.
* it now supports increase or decrease of priority.
* _update_further is deprecated (and was broken).
2020-11-14 23:48:08 +01:00
Patrick Pelissier bd89e162fc Add support for additional parameter id 2020-11-14 23:45:38 +01:00
Patrick Pelissier 983a63fbbc Add more comments to explain how it works. 2020-11-14 22:45:39 +01:00
Patrick Pelissier 978e0ea5d7 Fix format 2020-11-14 22:45:18 +01:00
Patrick Pelissier 85c4b50b6f Improve coverage of prioriy queue. 2020-11-08 01:00:17 +01:00
Patrick Pelissier e77aec4619 Reduce test case for MacOS / MINGW (returning incorrect return value for printf) 2020-11-05 23:33:26 +01:00
Patrick Pelissier d67e084010 Fix introduced warning 2020-11-05 22:55:03 +01:00
Patrick Pelissier b0a74f162e Fix string_printf in case of error in formating. 2020-11-05 22:51:28 +01:00
Patrick Pelissier d92126b97e Add more tests (improve coverage) 2020-11-05 22:51:02 +01:00
Patrick Pelissier c055358fa2 Reformat 2020-11-05 22:50:38 +01:00
Patrick Pelissier 9f89148b69 Remove valgrind
(not working in Multithread code)
2020-11-05 22:02:44 +01:00
Patrick Pelissier ef1145603a Update comments. 2020-10-31 17:30:14 +01:00
Patrick Pelissier d169a06f79 Rename STRING_ASSERT_SLOW into M_ASERT_SLOW 2020-10-31 17:30:14 +01:00
Patrick Pelissier 8e15a8cfe9 Fix warnings of CodeQL 2020-10-31 00:35:28 +01:00
Patrick Pelissier 6466cefbf4 Fix yml syntax 2020-10-31 00:17:13 +01:00
Patrick Pelissier bec9a897c9 Update codeql to use test executable 2020-10-31 00:13:03 +01:00
Patrick Pelissier 37d47cb0f1 Cleanup static analyser 2020-10-31 00:12:40 +01:00
Patrick Pelissier 0854136005 Add target exe for analyser
Cleanup of static analyzer
2020-10-31 00:12:02 +01:00
Patrick Pelissier 9427931e45 Add CodeQL in continuous integration backend 2020-10-31 00:01:05 +01:00
Patrick Pelissier 6aa28b4cfe Fix warnings on ARM 2020-10-30 08:02:37 +01:00
Patrick Pelissier a29682ca29 Create M_ASSERT macro to encapsulate assert within M*LIB
The goal is to enable the user to override this macro if needed so that it can enable or disable the M*LIB witout impacting its own assertions.
2020-10-29 22:46:17 +01:00
Patrick Pelissier f5afd6e275 Update comments. 2020-10-25 21:16:43 +01:00
Patrick Pelissier 7b5fd14bcf Update comment. 2020-10-24 23:29:02 +02:00
Patrick Pelissier 22ce001f03 Remove incorrect use of M_ASSUME by assert 2020-10-24 23:14:14 +02:00
Patrick Pelissier 6f761091cc Update comment. 2020-10-24 23:07:29 +02:00
Patrick Pelissier bb9e0e4f6e Adding test for M_LET for bounded string 2020-10-24 14:03:31 +02:00
Patrick Pelissier 5e658a81fe Adding INIT_WITH support for bounded string within M_LET 2020-10-24 14:03:27 +02:00
Patrick Pelissier ddc722bf78 Add FIXME 2020-10-23 21:50:57 +02:00
Patrick Pelissier 0818d0ac7c Fix macro formatting. 2020-10-23 21:46:34 +02:00
Patrick Pelissier 2f315793cd Use of M_ASSERT_INDEX for deque 2020-10-23 21:45:37 +02:00
Patrick Pelissier 067a034bc9 Use of M_ASSERT_INDEX for list. 2020-10-23 21:39:33 +02:00
Patrick Pelissier 201cc45fd8 Use of M_ASSERT_INDEX for bitset. 2020-10-23 21:37:44 +02:00
Patrick Pelissier 7a270ffacb Update documentation 2020-10-23 21:32:06 +02:00
Patrick Pelissier 27bb62533a Use of M_ASSERT_INDEX
to validate user input.
2020-10-21 23:57:52 +02:00
Patrick Pelissier 032388b790 Update message 2020-10-21 23:57:24 +02:00
Patrick Pelissier f1e2f81e79 Improve formating of macros:
if the line is too long
and can be reduced,
reduce it.
2020-10-21 23:56:55 +02:00
Patrick Pelissier 54d4b80368 Reformat macro to 80 characters 2020-10-21 23:23:40 +02:00
Patrick Pelissier 8a0a556604 Add utility to reformat automatically
macro to 80 characters.
2020-10-21 23:23:16 +02:00
Patrick Pelissier 895f362628 Fix a majorant stack usage of B+TREE 2020-10-17 22:46:43 +02:00
Patrick Pelissier d24b52586d Put a type within internal namespaces. 2020-10-17 22:25:22 +02:00
Patrick Pelissier d76585cb0e Update test as per latest changes. 2020-10-17 22:25:05 +02:00
Patrick Pelissier fb44be6efe Remove argument itret_t from *SET_DEF_AS
as it is useless
(Return type IS the key type for a set).
2020-10-17 22:24:53 +02:00
Patrick Pelissier 0b6a5aaa97 Port to last API version of CMC 2020-10-17 20:14:06 +02:00
Patrick Pelissier c00fdc65a2 Change installation directory
so that all M*LIB headers are in one directory.
2020-10-17 13:22:17 +02:00
Patrick Pelissier ab7490eb8a Fix list of distributed files. 2020-10-17 13:17:47 +02:00
Patrick Pelissier 1a46c0cd3f Clarify should usage in the documentation. 2020-10-17 13:07:41 +02:00
Patrick Pelissier 22f595c015 Update comment 2020-10-17 12:39:09 +02:00
Patrick Pelissier 68c76ad146 Update example with latest changes. 2020-10-16 21:59:53 +02:00
Patrick Pelissier 0b18792b96 Document _DEF_AS macros
Fix #60
2020-10-16 21:56:42 +02:00
Patrick Pelissier 464e8e5f8f Clean usage of 'shall' within the documentation. 2020-10-16 21:33:01 +02:00
Patrick Pelissier 45410f3f0c Update README. 2020-10-16 21:04:07 +02:00
Patrick Pelissier 556e706343 Update doc as per last rename 2020-10-16 21:01:41 +02:00
Patrick Pelissier 1e534bd307 Rename derefence type of an iterator of a dict or a B+Treee into _ittref_t. 2020-10-16 21:01:29 +02:00
Patrick Pelissier 7a517ee3ae Upate comments. 2020-10-16 20:53:34 +02:00
Patrick Pelissier 9bb1957afa Rename internal types. 2020-10-16 20:51:24 +02:00
Patrick Pelissier 86f942ee5f Fix forgotten external type in internal function. 2020-10-15 22:15:01 +02:00
Patrick Pelissier a23df528e4 Add DICT_*_AS macros. 2020-10-15 22:05:18 +02:00
Patrick Pelissier 0e9af6dfac Prepare user name integration for OA dictionnaries. 2020-10-15 21:53:11 +02:00
Patrick Pelissier 99a8db1111 Prepare integration for custom names for dict. 2020-10-15 21:41:53 +02:00
Patrick Pelissier 24cdf1ca5c Use of internal types within the code
instead of external ones.
2020-10-03 16:07:32 +02:00
Patrick Pelissier f1b794b239 Use of external documented type
instead of internal type.
2020-10-03 16:07:14 +02:00
Patrick Pelissier b4fdcbc547 Factorization of the it_deref name for overloading 2020-10-03 15:48:44 +02:00
Patrick Pelissier ce9986f6d8 Factorization of common pattern for bucket dictionnaries. 2020-10-03 14:47:47 +02:00
Patrick Pelissier ad4dcae1db Add macro VARIANT_DEF2_AS 2020-10-03 14:07:14 +02:00
Patrick Pelissier b3fa63c971 Factorization of name usage 2020-10-03 14:07:14 +02:00
Patrick Pelissier 364101592b Remove unused file 2020-10-03 14:07:14 +02:00
Patrick Pelissier 5b89196cd7 Add macro TUPLE_DEF2_AS 2020-10-03 14:07:14 +02:00
Patrick Pelissier feb8b30048 Factorization of M_C(name, _t) 2020-10-03 14:07:14 +02:00
Patrick Pelissier 8340cf70fb Add macros
FUNC_OBJ_ITF_DEF_AS
FUNC_OBJ_INS_DEF_AS
2020-10-03 14:07:14 +02:00
Patrick Pelissier affb3778a0 Rename internal types to _ct 2020-10-03 14:07:14 +02:00
Patrick Pelissier c039f07f2d Add macros
BPTREE_DEF2_AS
BPTREE_DEF_AS
BPTREE_MULTI_DEF2_AS
BPTREE_MULTI_DEF_AS
2020-10-03 14:07:14 +02:00
Patrick Pelissier c180981768 Add macros
CONCURRENT_DEF_AS
CONCURRENT_RP_DEF_AS
2020-10-03 14:07:14 +02:00
Patrick Pelissier 2cfac5c332 Fix build issue in C11 for new macros. 2020-10-03 14:07:14 +02:00
Patrick Pelissier 8ba489eef3 Add macros
SNAPSHOT_SPSC_DEF_AS
SNAPSHOT_SPMC_DEF_AS
SNAPSHOT_MPMC_DEF_AS
2020-10-03 14:07:14 +02:00
Patrick Pelissier a4cb6e3681 Add macros SHARED_PTR_DEF_AS, SHARED_PTR_RELAXED_DEF_AS, SHARED_RESOURCE_DEF_AS 2020-10-03 14:07:14 +02:00
Patrick Pelissier 379e0be211 Use of new macro to define internal types not exported. 2020-10-03 14:07:14 +02:00
Patrick Pelissier acb886c391 Add macro RBTREE_DEF_AS 2020-10-03 14:07:14 +02:00
Patrick Pelissier 7f26ef0f1c Add new macros to define container
with the full given name.
2020-10-03 14:07:14 +02:00
Patrick Pelissier 1d8e541205 Add macros BUFFER_DEF_AS, QUEUE_MPMC_DEF_AS, QUEUE_SPSC_DEF_AS 2020-10-03 14:07:14 +02:00
Patrick Pelissier a4fa70a478 Add macro DEQUE_DEF_AS 2020-10-03 14:07:14 +02:00
Patrick Pelissier 3d3a473716 Add macro ILIST_DEF_AS 2020-10-03 14:07:14 +02:00
Patrick Pelissier e04b120d41 Add new macros _DEF_AS so that
user can define its own name for the generated types.
2020-10-03 14:07:14 +02:00
Patrick Pelissier 63eee6bba3 Update comments 2020-10-03 14:07:14 +02:00
Patrick Pelissier b396b42808 Update comments 2020-10-03 14:07:14 +02:00
Patrick Pelissier eb8b106f48 Update comments. 2020-10-03 14:07:14 +02:00
Patrick Pelissier 5d144991cb Reformat & add more assertions. 2020-10-03 14:07:14 +02:00
Patrick Pelissier 35718ae551 Rename type as internal types 2020-10-03 14:07:14 +02:00
Patrick Pelissier 1dd9aff402 Factorize the name of the object at top level. 2020-10-03 14:07:14 +02:00
Patrick Pelissier 6d47074457 Rename internal types of m-core 2020-10-03 14:07:14 +02:00
Patrick Pelissier 1943650ca3 Factorization of the name of the object
at the top level to be able to create
new high level macros that enables
to select the full name of the type.
2020-10-03 14:07:14 +02:00
Patrick Pelissier 5722f19939 Update comments 2020-10-03 14:07:14 +02:00
Patrick Pelissier 7cf14b5d8a Update formatting 2020-10-03 14:07:14 +02:00
Patrick Pelissier b3a1a75f6f Rename internal types:
a suffix ending with _ct means confidential type
ans is reserved for M*LIB internal usage.

OPLIST doesn't use the external types
but rather the internal types.
It enables to be independent of the real names
of the external types.
Such external names are planned to be fully customizable
(i.e. the user may define a name that suits its coding style)
2020-10-03 14:07:14 +02:00
Patrick Pelissier eb7556f88f Replace abort by assert for static analyszer 2020-08-22 18:58:48 +02:00
Patrick Pelissier 805c747c60 Add more assertions (help static analyzer) 2020-08-22 18:54:51 +02:00
Patrick Pelissier 5f9feb833c Replace TAB by SPACE 2020-07-25 19:17:25 +02:00
Patrick Pelissier efef35c1e1 Reformat 2020-07-25 18:20:17 +02:00
Patrick Pelissier b1b32f565d Transform TAB into SPACE. 2020-07-25 18:15:57 +02:00
Patrick Pelissier f4cd8eaff9 Rename internal macro to TUPLEI_ 2020-07-25 18:01:34 +02:00
Patrick Pelissier 2cd5258f89 Add comments
Replace TAB by SPACE.
2020-07-25 17:54:01 +02:00
Patrick Pelissier 1b206931df Transform TAB into SPACE 2020-07-22 20:51:45 +02:00
Patrick Pelissier f68840ef8c Update doc 2020-07-19 01:12:12 +02:00
Patrick Pelissier 779c15ec08 Update tests as per new semantics 2020-07-19 01:11:15 +02:00
Patrick Pelissier 29bcc00202 Update format 2020-07-19 01:06:48 +02:00
Patrick Pelissier 1ff0d9fac0 Add test for _sort_intersect 2020-07-19 01:01:53 +02:00
Patrick Pelissier 4488853642 Factorization of _sort_union 2020-07-19 00:59:11 +02:00
Patrick Pelissier d5dc5d083d Fix _sort_union bug 2020-07-19 00:55:51 +02:00
Patrick Pelissier 784c42d850 Update _insert functions to update
iterators as per new specification.
2020-07-19 00:55:35 +02:00
Patrick Pelissier 8c1eb1fcb5 Add tests for _sort_union 2020-07-19 00:53:58 +02:00
Patrick Pelissier 49180bfbe5 Add documentation on IT_INSERT operator 2020-07-19 00:53:43 +02:00
Patrick Pelissier a3116dd813 Update comments 2020-07-18 09:54:12 +02:00
Patrick Pelissier 23df465401 Update comments 2020-07-14 14:44:10 +02:00
Patrick Pelissier 966170452f Improve test representativity by simulating various speeds for readers and writers 2020-07-14 14:43:14 +02:00
Patrick Pelissier eaf7ae7dee Fix spelling 2020-07-14 00:47:25 +02:00
Patrick Pelissier 8a6652646a Fix formatting (Replace TAB with SPACE) 2020-07-14 00:34:59 +02:00
Patrick Pelissier 2063bf879d Formatting: replace TAB by SPACE. 2020-07-14 00:26:26 +02:00
Patrick Pelissier 2529d4ae49 Update comments & remove warning about _Atomic 2020-07-12 22:52:36 +02:00
Patrick Pelissier 439bc06423 Fix unused value warning 2020-07-12 00:32:09 +02:00
Patrick Pelissier ab6c90f42f Fix issue with a warning that it triggers now but now before, whereas the code has not changed. Another random warning 2020-07-11 20:39:27 +02:00
Patrick Pelissier ac9e9a83b9 Fix issue with warnings on MacOS 2020-07-11 20:38:51 +02:00
Patrick Pelissier e495b92ae5 Workaround warnings about unused return value 2020-07-11 20:29:55 +02:00
Patrick Pelissier 50b1bedc54 Workaround some warnings 2020-07-11 20:13:31 +02:00
Patrick Pelissier 4a80ccd5f4 Add optimization to enable more warnings 2020-07-11 20:13:13 +02:00
Patrick Pelissier 6ca65dd60c Update comment 2020-07-11 18:36:46 +02:00
Patrick Pelissier b2be4d5397 Improve checking of failure detection 2020-07-11 18:02:27 +02:00
Patrick Pelissier de34cefa83 add test for detecting call to disable method 2020-07-11 18:02:11 +02:00
Patrick Pelissier 40c8dbae1e Update detection of disabled method 2020-07-11 18:01:48 +02:00
Patrick Pelissier 18af53cf38 Disable Wformat-nonliteral in the protected section 2020-07-11 17:18:43 +02:00
Patrick Pelissier 8510318ba5 Another minor warning about casting a double into a float 2020-07-11 17:17:59 +02:00
Patrick Pelissier 6ad02ffe56 Stop on warnings for CI 2020-07-11 16:57:03 +02:00
Patrick Pelissier 535e45d564 Update flags 2020-07-10 13:00:07 +02:00
Patrick Pelissier e2c60aa45c Fix another warnings that are triggered in another random combinaison of compiler settings 2020-07-10 12:59:31 +02:00
Patrick Pelissier 56d2a74818 Fix some warnings 2020-07-09 23:38:34 +02:00
Patrick Pelissier 8a36b5ff15 Workaround to avoid CLANG unused function warnings 2020-07-09 22:14:00 +02:00
Patrick Pelissier 7607645636 Reeanble Wunused-function 2020-07-09 22:13:24 +02:00
Patrick Pelissier cbb84accfe Add build on linux 32 bits 2020-07-09 17:31:16 +02:00
Patrick Pelissier 3e70cf7b5f TCC doesn't support -MM, so use cc to generate them 2020-07-09 10:45:09 +02:00
Patrick Pelissier 1a7deef735 Add TCC target 2020-07-09 10:38:35 +02:00
Patrick Pelissier 748771ab72 Update comment 2020-07-09 10:37:37 +02:00
Patrick Pelissier 6ef279dd2f Add comments 2020-07-07 18:30:14 +02:00
Patrick Pelissier abcf37dc72 Update 2020-07-07 13:07:54 +02:00
Patrick Pelissier 690b7bf9c1 Fix other warning for msys2 2020-07-05 23:53:06 +02:00
Patrick Pelissier 71cec5155a Fix uncompliant m-atomic support
if __STDC_NO_ATOMICS__ is defined, then in C11, there is no stdatomic header
2020-07-04 23:34:24 +02:00
Patrick Pelissier d2b0873a95 Add missing make for msys2 2020-07-04 23:09:37 +02:00
Patrick Pelissier 4cecdbb93e Add missing packages for msys2 as per https://www.msys2.org/docs/ci/ 2020-07-04 23:01:47 +02:00
Patrick Pelissier 2abca7d244 Update command line for msys2 as per https://www.msys2.org/docs/ci/ 2020-07-04 22:58:16 +02:00
Patrick Pelissier c26b467e86 Update command line for msys2 2020-07-04 22:48:41 +02:00
Patrick Pelissier 19514b09b0 Add msys2 target 2020-07-04 22:34:07 +02:00
Patrick Pelissier ab98577deb Fix warning 2020-07-04 12:50:34 +02:00
Patrick Pelissier aae5f00dbd Add new benchmark 2020-07-04 00:47:06 +02:00
Patrick Pelissier 04706d48b9 Fix further warnings 2020-07-03 23:03:12 +02:00
Patrick Pelissier c7df60c78d Fix some warnings 2020-07-03 22:44:34 +02:00
Patrick Pelissier f03a4503eb Fix some warnings 2020-07-03 22:15:54 +02:00
Patrick Pelissier a6951fe5e3 Fix warnings for clang-cl 2020-07-03 21:59:25 +02:00
Patrick Pelissier 6def48a0d1 Fix clang-cl to target x64 mode 2020-07-03 21:30:19 +02:00
Patrick Pelissier 8b5d1e07ce Fix build with MSVC in 32 bits mode 2020-07-03 21:25:20 +02:00
Patrick Pelissier 3182c39280 Add clang-cl in the continuous Integration 2020-07-03 21:18:17 +02:00
Patrick Pelissier e0b5dc2f02 Add test for clang-cl 2020-07-03 20:59:42 +02:00
Patrick Pelissier 6e5181e405 Fix doc on B+TREE 2020-07-02 23:22:44 +02:00
Patrick Pelissier 75f4f23144 Add comments and fix Pn level 2020-07-02 21:41:57 +02:00
Patrick Pelissier bc1402f66a Udpate documentation 2020-07-02 10:40:41 +02:00
Patrick Pelissier fc5ffcb404 Update API 2020-07-02 10:39:22 +02:00
Patrick Pelissier bd20a021ce Update documentation 2020-07-02 10:39:15 +02:00
Patrick Pelissier dfd12107de Add new function _clear_ptr 2020-07-02 10:39:05 +02:00
Patrick Pelissier 6743cb9456 Add posibility for user to select Thread backend directly 2020-07-02 00:09:54 +02:00
Patrick Pelissier 4aa93325e9 Update documentation 2020-07-01 12:08:24 +02:00
Patrick Pelissier f2a06ede62 Add mechanism to disable temporary compiler warnings in a sequence of code. 2020-07-01 11:47:55 +02:00
Patrick Pelissier a36752b8ce Update documentation (Fix #66) 2020-07-01 11:45:24 +02:00
Patrick Pelissier 3b347f2ba5 Reduce some warnings using the atomic compatibility layer (cannot fix all) 2020-07-01 11:06:58 +02:00
Patrick Pelissier 47296e5c11 The user can define M_USE_C11_NO_THREADS to disable C11 header (Support for broken C11 implementation) 2020-06-29 21:53:09 +02:00
Patrick Pelissier a24c530ec6 Update documentation on _init_new method 2020-06-29 16:03:54 +02:00
Patrick Pelissier 7ebe0608ae Define _init_new method only if NEW method has not been disabled 2020-06-29 16:03:38 +02:00
Patrick Pelissier 2a3021c021 Adding more code generation. 2020-06-29 16:01:38 +02:00
Patrick Pelissier 4d313aa72b Fix warning about unused function 2020-06-29 15:16:37 +02:00
Patrick Pelissier 7906a39647 Fix warning about unused function 2020-06-29 15:16:03 +02:00
Patrick Pelissier 86254958f0 Add precision on C11 thread layer (#65) 2020-06-29 15:02:34 +02:00
Patrick Pelissier 0089c1af61 Remove clang-cl as it is not available 2020-06-28 23:08:44 +02:00
Patrick Pelissier 6b5a3ddef7 Add clang-cl version 2020-06-28 23:04:06 +02:00
PpHd 42c2fd69a2 Merge pull request #64 from vladipus/patch-2
Update m-core.h
2020-06-27 21:12:44 +02:00
Vladislav Dmitrievich Turbanov bcb9b831db Update m-core.h
A tiny typo. MSVS should be referred to as MSVC - that is the standard way.
2020-06-27 19:08:52 +03:00
Patrick Pelissier f6483cbb30 It seems GNUC is force to 4 for APPLE/CLANG 2020-06-27 01:00:46 +02:00
Patrick Pelissier f742707699 Always use atomic in C++ 2020-06-27 00:31:58 +02:00
Patrick Pelissier aee02d86ab Workaround issue with CLANG++ on MAC 2020-06-27 00:10:40 +02:00
Patrick Pelissier dfbf34daf6 Remove a warning with some compiler by encoding 0 as UINT_MAX+1 2020-06-26 23:48:59 +02:00
Patrick Pelissier 494cbbecf0 Try to make Apple Make working in C11 mode 2020-06-26 23:40:49 +02:00
Patrick Pelissier a1513777f1 Activate C++ build too 2020-06-26 23:38:54 +02:00
Patrick Pelissier 9784a16d47 Get ride of modular arithmetic 2020-06-26 00:25:15 +02:00
Patrick Pelissier a8648e0cc1 Fix variable name for conditional code 2020-06-25 23:49:28 +02:00
Patrick Pelissier 3f8e93ad7a Use of intrinsic for clz within MSVS 2020-06-25 23:45:39 +02:00
Patrick Pelissier b040bc411f Add tests for builtin core functions 2020-06-25 23:35:34 +02:00
Patrick Pelissier ae8c3e5300 Update documentation about array & mandatory operators 2020-06-25 22:49:54 +02:00
Patrick Pelissier 01d390c3e9 Test array without INIT_SET & SET 2020-06-25 22:49:36 +02:00
Patrick Pelissier 56e4cda76c Make INIT_SET & SET operators of arrays as optional 2020-06-25 22:49:25 +02:00
Patrick Pelissier c59d585c22 Add new macro to test method1 or method2 in oplist 2020-06-25 22:49:08 +02:00
PpHd 81c97682a7 Merge pull request #62 from vladipus/patch-1
Update README.md
2020-06-25 21:21:18 +02:00
Patrick Pelissier a432628df6 Fix warnings for CLANG/WINDOWS (#61) 2020-06-25 21:18:01 +02:00
Vladislav Dmitrievich Turbanov d16effb4c5 Update README.md
Fixed a small typo in the ALGO_DEF example, that features an ARRAY_OPLIST with `int` instead of `array_int`
2020-06-25 22:13:53 +03:00
Patrick Pelissier 6279f98bb5 Run also in C11 mode for CI 2020-06-24 21:15:51 +02:00
Patrick Pelissier 3cbc474e76 Document M_ENUM_OPLIST 2020-06-24 21:14:00 +02:00
Patrick Pelissier c80fb7bebe Add test for M_ENUM_OPLIST (in particular I/O tests) 2020-06-24 21:13:43 +02:00
Patrick Pelissier 68788a6fb8 Add M_ENUM_OPLIST 2020-06-24 21:13:13 +02:00
Patrick Pelissier fd3cb50249 Remove temporary file 2020-06-22 00:38:19 +02:00
Patrick Pelissier 7e0bd8414d Fix warnings for mingw 2020-06-22 00:33:10 +02:00
Patrick Pelissier 70de571dc8 Fix warnings in test suite. 2020-06-22 00:14:55 +02:00
Patrick Pelissier cc6da8941c * Fix wanings for reduce precision on integers.
* Add wrapper for strncat
2020-06-22 00:14:37 +02:00
Patrick Pelissier d27c448a94 Fix some warnings with MSVS
for the test suite.
2020-06-21 23:52:12 +02:00
Patrick Pelissier 06a1590645 Add missing assertion. 2020-06-21 23:51:49 +02:00
Patrick Pelissier 652653af0b Fix some warnings by casting
for compilers which cannot detect the affectations as ok.
2020-06-21 23:50:49 +02:00
Patrick Pelissier c520b7d0be Enable Annex K for MSVS 2020-06-21 23:36:47 +02:00
Patrick Pelissier 4f4605befb Use of Annex K for MSVS to reduce warnings. 2020-06-21 23:36:34 +02:00
Patrick Pelissier 3f84f54d65 Add casts to avoid some compiler warnings
if the compiler is not able to detect the cast if safe.
2020-06-21 23:03:40 +02:00
Patrick Pelissier bf49b8e933 Enable warnings for MSVS 2020-06-21 22:43:06 +02:00
Patrick Pelissier 1edb204ec6 Update documentation 2020-06-19 21:14:46 +02:00
Patrick Pelissier dd5c9ac8ad Fix corner case of string_fget_word when it doesn't end with a separator 2020-06-19 21:11:05 +02:00
Patrick Pelissier 32b6f82249 Add corner case for string_fget_word when it doesn't end with a separator 2020-06-19 21:10:46 +02:00
Patrick Pelissier 44b3895698 Fix m_core_fscan_* in case of EOF 2020-06-19 21:02:17 +02:00
Patrick Pelissier 5ce6ccde3d Add bench for deque 2020-06-18 22:04:56 +02:00
Patrick Pelissier ee64e068f9 Add bench for rapidjson 2020-06-14 21:12:02 +02:00
Patrick Pelissier 8d89e7c958 Add leak sanitizer to sanitize target. 2020-06-14 11:33:01 +02:00
Patrick Pelissier ef74f8eb55 Fix other warnings about conversion but in C++ 2020-06-14 01:10:37 +02:00
Patrick Pelissier a7749e944f Fix strange warning with gcc 2020-06-14 00:48:58 +02:00
Patrick Pelissier 18bf06ff5f Add m_core_serial_fail for make debugging easier for serialization
Fix issue in saving size_t for 32 bits system
2020-06-14 00:40:11 +02:00
Patrick Pelissier b27f490acb Fix typing 2020-06-14 00:18:26 +02:00
Patrick Pelissier e84fa859c6 Fix implicit conversion. 2020-06-14 00:17:44 +02:00
Patrick Pelissier 4c57ca69bc Support for 32 bits system. 2020-06-14 00:17:22 +02:00
Patrick Pelissier b0d2557ea1 string_fgets:
Fix buffer overflow for very big string
2020-06-14 00:17:09 +02:00
Patrick Pelissier 82906e03e9 Add warning also for GCC. 2020-06-13 20:02:29 +02:00
Patrick Pelissier 1859868838 Fix sign conversion for algorithm tests. 2020-06-13 20:02:14 +02:00
Patrick Pelissier 4ab3a3605b Fix -Wsign-conversion warnings in tests. 2020-06-13 19:43:52 +02:00
Patrick Pelissier 279b46b4e2 Fix -Wsign-conversion warnings. 2020-06-13 19:43:38 +02:00
Patrick Pelissier 17950c5fe5 Fix corner cases for string_reserve 2020-06-13 18:57:53 +02:00
Patrick Pelissier 45b94c8abc Add corner cases for string_reserve 2020-06-13 18:57:39 +02:00
Patrick Pelissier a98ebd3b20 Fix test. 2020-06-13 18:53:40 +02:00
Patrick Pelissier cb7cd1ac67 Simplify code 2020-06-13 18:53:28 +02:00
Patrick Pelissier 9a41faf40a Fix -Wsign-conversion warning for strings. 2020-06-13 18:41:23 +02:00
Patrick Pelissier 8c44362f74 More test case. 2020-06-13 18:41:06 +02:00
Patrick Pelissier 548c0c0c61 Fix -Wsign-conversion warning 2020-06-13 18:37:10 +02:00
Patrick Pelissier 607221f480 Fix expected result due to change in list + INIT_WITH 2020-06-13 18:19:29 +02:00
Patrick Pelissier 160c76361b Add -Wsign-conversion when checking with clang 2020-06-13 18:15:53 +02:00
Patrick Pelissier 2fadad0c8d Fix warnings raised by -Wsign-conversion of clang
in m-core.h
2020-06-13 18:15:26 +02:00
Patrick Pelissier 4d4973abcc Fix warning 2020-06-13 17:57:31 +02:00
Patrick Pelissier f8ae9eb677 Add bench of serialization of integers 2020-06-13 17:38:14 +02:00
Patrick Pelissier de825203cf Ignore other temporary files 2020-06-13 17:37:54 +02:00
Patrick Pelissier 4f865176d3 Add bench for serialization. 2020-06-13 17:30:58 +02:00
Patrick Pelissier cb4b43e2e8 * Add length param for seralization write_string
to increase a little bit the performance for big strings.
* Change the format of storing strings for serial-bin.
2020-06-13 17:26:07 +02:00
Patrick Pelissier 89b6e1aac0 Adding serialization for bounded string 2020-06-13 11:30:52 +02:00
Patrick Pelissier daeaa242b8 Add new types to be used for M_LET:
* m_serial_bin_write_t
* m_serial_bin_read_t
2020-06-13 11:21:33 +02:00
Patrick Pelissier 100af17328 Make copyright notice explicit 2020-06-13 10:44:47 +02:00
Patrick Pelissier 7527bfec85 Update comments 2020-06-13 00:17:35 +02:00
Patrick Pelissier f73d25c92d Update documentation after renaming 2020-06-12 20:00:20 +02:00
Patrick Pelissier 9080f5d52f Add basic tests for M_KEEP_ARGS / M_SKIP_ARGS / M_MID_ARGS 2020-06-12 20:00:04 +02:00
Patrick Pelissier 6beb142bbe Fix conflict with SVID2/XPG mallopt options #53 2020-06-12 19:58:18 +02:00
PpHd 9b8b93288a Merge pull request #51 from vladipus/patch-1
Update README.md
2020-06-12 19:42:51 +02:00
Vladislav Dmitrievich Turbanov 6a2a549ec5 Update README.md
Fixed a M_IPTR missing *
2020-06-11 19:46:40 +03:00
Patrick Pelissier 468b7e7a0c Add bench for CMC 2020-06-10 22:29:59 +02:00
Patrick Pelissier fd640e9232 Update change of behaviors 2020-06-08 22:58:52 +02:00
Patrick Pelissier d13d7feae3 Update test as per new behavior 2020-06-08 22:58:41 +02:00
Patrick Pelissier 17f69326e2 Reverse order of a list initialized with M_LET to match the behavior of array 2020-06-08 22:58:30 +02:00
Patrick Pelissier 273fcd51b6 Add bench for rigtorp MPMCQueue 2020-06-06 12:00:52 +02:00
Patrick Pelissier f4b9185ceb Update documentation on QUEUE_MPMC 2020-06-06 11:09:55 +02:00
Patrick Pelissier b722227b39 Update comment 2020-06-05 21:06:06 +02:00
Patrick Pelissier 3d7e2f5c6b Fix m*lib version 2020-06-05 21:01:11 +02:00
Patrick Pelissier 9369530068 Comments & formating 2020-06-05 20:50:34 +02:00
Patrick Pelissier 4e968c3777 Comment the exponential backoff object. 2020-06-05 20:39:16 +02:00
Patrick Pelissier 9a5302ac19 Rename internal backoff
to avoid consummign too much namespace
2020-06-05 20:34:31 +02:00
Patrick Pelissier 8216ef0f7b Factorization of check of index
So that it can be reused for other modules.
2020-06-05 20:30:07 +02:00
Patrick Pelissier b897027021 Add user customizable ARRAY macro
for checking if index is within the allowedd bounds even in release mode
2020-06-05 00:11:22 +02:00
Patrick Pelissier 6095cf8610 Reindent file. 2020-06-04 23:51:17 +02:00
Patrick Pelissier e917ac5663 Update comments and simplify 2020-06-02 22:57:38 +02:00
Patrick Pelissier 2b44892aad Add more comments 2020-05-31 00:36:47 +02:00
Patrick Pelissier 294e45c7e1 Add comments 2020-05-31 00:15:46 +02:00
Patrick Pelissier 467acfdd10 Use of M_BOOL_OPLIST
to avoid warnings.
2020-05-30 23:45:46 +02:00
Patrick Pelissier d3823951b5 Add M_BOOL_OPLIST 2020-05-30 23:45:29 +02:00
Patrick Pelissier cc33079d43 Add comments 2020-05-30 23:38:31 +02:00
Patrick Pelissier 78d0bfb286 Port new error oplist format to all containers. 2020-05-30 18:00:43 +02:00
Patrick Pelissier b2f5ae6917 Proper generation. 2020-05-30 17:54:58 +02:00
Patrick Pelissier 9c723da768 Change format of errror on oplist
This is to enable M_GLOBAL_OPLIST_OR_DEF to properly expand the erroneous oplist to the backend generator, that will report the error.
As such the erreneous oplist is surrounded by two pairs of brackets (())
2020-05-30 17:54:22 +02:00
Patrick Pelissier 70c3932f6e Add new test on proper error checking 2020-05-30 17:52:31 +02:00
Patrick Pelissier 92bddcaab4 Fix preprocessing issue
in case of recursive tuple or variant.
2020-05-30 12:13:43 +02:00
Patrick Pelissier 79a8401d75 Fix oplist definiiton
Improve test suite
2020-05-30 12:07:21 +02:00
Patrick Pelissier 570473e465 Improve test suite. 2020-05-30 11:33:37 +02:00
Patrick Pelissier 990b7b02d7 Update list of expected failures 2020-05-30 11:23:53 +02:00
Patrick Pelissier 0b301d1cea Fix oplist definition. 2020-05-30 11:12:15 +02:00
Patrick Pelissier f35db79792 Work around C++ warnings 2020-05-30 10:46:17 +02:00
Patrick Pelissier dc1f163716 Fix option name with new cl 2020-05-30 10:41:51 +02:00
Patrick Pelissier 4d6bb407ee Reenable MSVC test suite with new compiler version (16.6) 2020-05-30 10:34:02 +02:00
Patrick Pelissier 37cef298c6 Update format 2020-05-29 21:49:03 +02:00
Patrick Pelissier 0396d1f648 Go to next development version 2020-05-29 21:07:43 +02:00
Patrick Pelissier e694d83cc4 V0.4.0 2020-05-27 21:50:03 +02:00
Patrick Pelissier 19fc150763 Discard warning with clang++ 2020-05-27 21:41:31 +02:00
Patrick Pelissier 3784f653d9 Fix warning with CLANG 2020-05-27 21:41:11 +02:00
Patrick Pelissier eb40cff6a1 Improve checkall target to stop on warning 2020-05-27 21:09:07 +02:00
Patrick Pelissier b7f84236d3 * Update comments
* Micro optimization
2020-05-25 21:41:16 +02:00
Patrick Pelissier 65e3f1049b * Update comments.
* Fix position of const for some prototypes.
2020-05-25 00:23:12 +02:00
Patrick Pelissier cc45b9c1fe Fix issue in test suite. 2020-05-24 20:39:20 +02:00
Patrick Pelissier 9340c2e55c Fix memory leak for _parse_str in case of error. 2020-05-24 19:50:32 +02:00
Patrick Pelissier 9710e014f2 Reindent function 2020-05-24 19:19:19 +02:00
Patrick Pelissier 7761fb6bf1 Add contract for tuple & variant. 2020-05-24 19:08:18 +02:00
Patrick Pelissier 2f4df5f67c Fix potential read before init in test. 2020-05-24 19:07:29 +02:00
Patrick Pelissier b841f81416 Fix package name for MS Windows
The filesystem doesn't support '*'
2020-05-24 18:14:25 +02:00
Patrick Pelissier 72fd53ab44 Update comments 2020-05-24 12:01:56 +02:00
Patrick Pelissier 8335bc525b Add comments 2020-05-23 16:09:18 +02:00
Patrick Pelissier 9e5d14ce36 Factorization & add tests 2020-05-21 13:10:50 +02:00
Patrick Pelissier 3bafede8b7 * Make the test more pertinent 2020-05-21 12:32:33 +02:00
Patrick Pelissier 3f2904ab0d * Add comment 2020-05-21 12:32:20 +02:00
Patrick Pelissier 933b495ed1 * Optimization for M_LET for a string_t in case of constant non formatted string
* Support for string_t in M_LET for string_t in C11 mode.
* Adding associate test
2020-05-21 12:19:17 +02:00
Patrick Pelissier 77813adc00 Add example of formatted C string for string in M_LET 2020-05-21 11:55:35 +02:00
Patrick Pelissier ce2adea6c0 Update documentation 2020-05-21 09:54:08 +02:00
Patrick Pelissier 3ecdfff8f0 Remove more cleanly generated configuration file. 2020-05-21 00:54:24 +02:00
Patrick Pelissier a103ceb850 Add new example of array of string. 2020-05-21 00:36:35 +02:00
Patrick Pelissier 9f24b89487 Add debug flag for example 2020-05-21 00:36:13 +02:00
Patrick Pelissier 8be06cadb3 Add comments on description. 2020-05-20 23:21:27 +02:00
Patrick Pelissier c488d979cf Ignore Visual Code directory if any. 2020-05-20 23:05:28 +02:00
Patrick Pelissier f4c24f07af Update comment description of macros and functions 2020-05-20 22:36:36 +02:00
Patrick Pelissier 3d2ce63d63 Fix performance issue in benchmarks 2020-05-19 23:21:00 +02:00
Patrick Pelissier 0ac2c62ffe Port to new API 2020-05-19 22:57:08 +02:00
Patrick Pelissier 6001781e68 Cleanup namespace, add comments, and remove dead code 2020-05-17 21:39:24 +02:00
Patrick Pelissier d90cb7caf3 Update doc 2020-05-17 12:11:10 +02:00
Patrick Pelissier 88a4835025 Fix issue when defining algorithm with same prefix than container 2020-05-17 12:11:04 +02:00
Patrick Pelissier 75ae7a06e5 Add missing tests 2020-05-17 11:53:43 +02:00
Patrick Pelissier 3885cb29a2 Add control of type and oplists 2020-05-17 11:53:27 +02:00
Patrick Pelissier bf3ffd1766 Add test cases for new control 2020-05-17 11:10:06 +02:00
Patrick Pelissier d884d257bb Export TYPE operator in oplist 2020-05-17 10:53:17 +02:00
Patrick Pelissier a87cac84dd Move up control so that it is the first error reported by the compiler. 2020-05-17 10:52:54 +02:00
Patrick Pelissier d1ae26f0fd * Add control than the type and the oplist are compatible 2020-05-17 10:27:30 +02:00
Patrick Pelissier 9c58e73c37 * Add M_CHECK_COMPATIBLE
* Fix issue in oplist
2020-05-17 10:26:40 +02:00
Patrick Pelissier 024b62a7a7 Add instance for M_CHECK_COMPATIBLE to be able to check multiple types within one container. 2020-05-17 10:26:08 +02:00
Patrick Pelissier c59731775e * Provide alternative for M_STATIC_ASSERT in GNUC + C11 with improved error messages
* Add internal macro M_CHECK_COMPATIBLE_OPLIST to check if a type and an oplist could match.
2020-05-17 09:36:50 +02:00
Patrick Pelissier 4668476c6a Fix issue with old version of ICC 2020-05-16 14:47:30 +02:00
Patrick Pelissier 743959ebde Fix micro performance issue 2020-05-16 14:09:49 +02:00
Patrick Pelissier dd27fa7e72 Add coverage for Function Object 2020-05-16 10:24:29 +02:00
Patrick Pelissier f2025f83d3 Fix help usage 2020-05-16 09:41:05 +02:00
Patrick Pelissier 8c06b43b2b Update tests for new controls 2020-05-15 21:46:18 +02:00
Patrick Pelissier 3cde7a1731 Add protection for use of oplist within a container oplist 2020-05-15 21:46:03 +02:00
Patrick Pelissier e9db1d28b8 Try to work around to print the oplist 2020-05-15 21:45:21 +02:00
Patrick Pelissier adffaf0e87 Fix illegal usage of oplist for function object 2020-05-15 21:45:02 +02:00
Patrick Pelissier 49a2e600c4 Add control of sub-oplist when creating a new oplist of a container
Add test case of this new control
Fix some corner bugs in some containers evolving their own oplists.
2020-05-15 21:19:39 +02:00
Patrick Pelissier 0bedcba32b Rewrite M_STATIC_ASSERT to include an error code and message
Add more control on the default expanded macros to check if arguments are compatible
2020-05-15 14:51:20 +02:00
Patrick Pelissier c531f805b0 Define _reduce only if SET method is properly set 2020-05-15 14:31:47 +02:00
Patrick Pelissier da0ab5ea98 Update failure tests as per latest checks 2020-05-11 20:55:16 +02:00
Patrick Pelissier 6774afd751 Add checks of missing oplist in the last _DEF macros 2020-05-11 20:54:50 +02:00
Patrick Pelissier 6d489136e7 Update help 2020-05-10 22:18:19 +02:00
Patrick Pelissier 4ea6dbc7fa Update makefile as per latest version of library 2020-05-10 20:21:03 +02:00
Patrick Pelissier defc58f6a3 Update bench code to latest version of the library. 2020-05-10 20:20:37 +02:00
Patrick Pelissier 006d0d16a5 Fix error 2020-05-10 20:20:03 +02:00
Patrick Pelissier b8af8bb344 Redisable MSVC testing with new version of compiler 2020-05-10 12:40:37 +02:00
Patrick Pelissier e249be1142 Reenable MSVC testing with new version of compiler 2020-05-10 12:38:36 +02:00
Patrick Pelissier 05fde6c3cf Display MSVC compiler full version 2020-05-10 12:06:31 +02:00
Patrick Pelissier aaa1d7dc4b Update description of test 2020-05-10 11:20:16 +02:00
Patrick Pelissier 8c479b2e5a Update tests 2020-05-10 11:17:25 +02:00
Patrick Pelissier 45d2a529b5 Add more validation of oplists before expanding data 2020-05-10 11:16:46 +02:00
Patrick Pelissier 7d17223332 Update comments 2020-05-10 11:15:56 +02:00
Patrick Pelissier 12bc65b6a8 Fix spelling 2020-05-10 11:15:28 +02:00
Patrick Pelissier a849d5c031 Make check-failure tests parallel 2020-05-09 21:39:01 +02:00
Patrick Pelissier f195b09657 Add more tests 2020-05-09 21:38:48 +02:00
Patrick Pelissier 439177ec71 Add protection against wrong oplist in more headers 2020-05-09 21:38:32 +02:00
Patrick Pelissier aadd4f11b1 Update tests as per new checks 2020-05-09 17:16:11 +02:00
Patrick Pelissier 113fdbf388 Add more controls on proper presence of oplist for _DEF macros 2020-05-09 17:16:00 +02:00
Patrick Pelissier 648406a99a Update tests as per new checks 2020-05-09 16:11:11 +02:00
Patrick Pelissier 055e74d350 Add more check for valid oplists before expanding further 2020-05-09 16:10:56 +02:00
Patrick Pelissier ac3d7568f2 Update test 2020-05-09 11:20:05 +02:00
Patrick Pelissier 6c222b9ad7 Raise proper failure if M_let is used without an oplist
Raise proper failure if a TYPE operator is used in an oplist that doesn't export it.
2020-05-09 11:15:44 +02:00
Patrick Pelissier 4426a60904 Add test for testing expected failures 2020-05-09 10:56:31 +02:00
Patrick Pelissier 34f70a031f Use M_STATIC_FAILURE to stop expanding methods in case of detected failure 2020-05-09 10:56:05 +02:00
Patrick Pelissier 79f2f396b9 Add macro M_STATIC_FAILURE to abort expansion in case of error 2020-05-09 10:55:25 +02:00
Patrick Pelissier 88143f7d52 Update ignore file 2020-05-09 10:54:30 +02:00
Patrick Pelissier c1261dd0f2 Fix doc 2020-05-08 21:47:19 +02:00
Patrick Pelissier 8f7a60ea73 Add documentation for function object 2020-05-08 21:43:35 +02:00
Patrick Pelissier 4758bbd6cc Add more tests 2020-05-08 21:23:48 +02:00
Patrick Pelissier 3f66325c19 Add new example for function object, json & algorithms 2020-05-08 17:50:07 +02:00
Patrick Pelissier 6f10d7deb9 Add synonym of serialisater with specialized oplists to be used in RAII 2020-05-08 17:49:44 +02:00
Patrick Pelissier 919900c90a Update documentation 2020-05-08 17:48:56 +02:00
Patrick Pelissier e6daaf429c Add some tests for function objects 2020-05-08 11:37:38 +02:00
Patrick Pelissier 1200f30695 * Add more Function Object support in algorithm
* Fix bug of selection sort
2020-05-08 11:35:22 +02:00
Patrick Pelissier fca1120990 No longer export IT_REF for map containers (See API changes) 2020-05-08 11:33:28 +02:00
Patrick Pelissier 3735704c95 Update new API change 2020-05-08 11:30:57 +02:00
Patrick Pelissier 8c0c1b3102 Update documentation of reduce if the container is empty 2020-05-08 11:30:38 +02:00
Patrick Pelissier db192993f1 Reduce constraint as the dictionnary iteration is not modifiable 2020-05-08 00:27:15 +02:00
Patrick Pelissier 4f44b3f60b Add CMP callback 2020-05-07 22:13:36 +02:00
Patrick Pelissier b196fcc3c0 Rename _cmp_cb_t into _eq_cb_t 2020-05-07 22:10:53 +02:00
Patrick Pelissier 395f1af19e Implement more function object algorithm 2020-05-07 22:09:07 +02:00
Patrick Pelissier d8f761e889 Update Makefile for dist 2020-05-05 23:44:27 +02:00
Patrick Pelissier 563ffb4275 Add first support for function object for certain algos (WIP) 2020-05-05 23:34:34 +02:00
Patrick Pelissier 9ba2de4b70 Add macro M_IF_FUNCOBJ to handle conditional expression if the function object is defined 2020-05-05 23:34:12 +02:00
Patrick Pelissier 0ac6a53fe9 Define callback types 2020-05-05 22:57:19 +02:00
Patrick Pelissier 4431e9f9ae Factorization / Split of the definition of the algorithm 2020-05-05 22:40:03 +02:00
Patrick Pelissier 48526ff5c7 Simplify logic due to fix of M_PARENTHESIS_P 2020-05-04 00:33:00 +02:00
Patrick Pelissier 4ee453025c Add comments 2020-05-04 00:32:40 +02:00
Patrick Pelissier 1e7b543c0f Fix issue with oplists with 3 arguments and fix warnings 2020-05-04 00:30:14 +02:00
Patrick Pelissier 8c2b4f8cf9 Add test cases for function object 2020-05-04 00:29:42 +02:00
Patrick Pelissier 13cadfa470 Update description of the list of headers 2020-05-03 18:00:46 +02:00
Patrick Pelissier deb595372b Add first version of Function Object 2020-05-03 17:49:02 +02:00
Patrick Pelissier 01fd5d929e * Fix M_RET_ARG so that it accepts also a list of the exact number of arguments (instead of one more) * Add more keywords for pattern recognation 2020-05-03 13:13:45 +02:00
Patrick Pelissier 2d60bd2c1b Fix a bug in M_PARENTHESIS_P 2020-05-02 10:19:31 +02:00
Patrick Pelissier 9655b13203 Add more corner cases for M_PARENTHESIS_P 2020-05-02 10:18:52 +02:00
Patrick Pelissier 6b97a7436d Add basic tests for dispathing init_with based on their number of args 2020-05-02 10:06:30 +02:00
Patrick Pelissier 1c792dd0a4 Add option for init_with to dispatch to different methods in function of the number of args 2020-05-02 10:06:08 +02:00
Patrick Pelissier dcbd9f496f Document NAME operator 2020-05-02 09:56:23 +02:00
Patrick Pelissier 9804120cde * Add simple test for registration of int global operator 2020-05-02 09:56:11 +02:00
Patrick Pelissier a9b06718f0 * Add simple test for NAME operator 2020-05-02 09:55:28 +02:00
Patrick Pelissier 963d819e22 * Add NAME operator. * Register default oplist for char,short,int,long,float,double 2020-05-02 09:55:10 +02:00
Patrick Pelissier 28847af43f Update constraints on MOVE & INIT_MOVE operators 2020-04-27 23:12:06 +02:00
Patrick Pelissier 130fa36970 Update iterator constraint 2020-04-27 22:55:53 +02:00
Patrick Pelissier ab99035291 Add another example 2020-04-20 23:50:05 +02:00
Patrick Pelissier 6de43d8a45 Add doc for ALGO_REDUCE with different type 2020-04-20 23:49:48 +02:00
Patrick Pelissier 7b46891622 Add test for ALGO_REDUCE with different type 2020-04-20 23:49:35 +02:00
Patrick Pelissier a0a32d8c6c ALGO_REDUCE accept dest with different type than the container 2020-04-20 23:49:16 +02:00
Patrick Pelissier 1ffd07dc6e Update format 2020-04-11 00:25:40 +02:00
Patrick Pelissier cb49cd7100 * Fix integer overflow in test of mul reduction 2020-04-10 08:35:44 +02:00
Patrick Pelissier 923b340a80 * Update documentation 2020-04-10 08:29:55 +02:00
Patrick Pelissier 5b8750ee2a * Add support for product in ALGO_REDUCE 2020-04-10 08:28:16 +02:00
Patrick Pelissier d438d089fb Add note on the provided oplists 2020-04-10 08:19:59 +02:00
Patrick Pelissier 843ddac3dd Proper prefix internal variables of macros by '_' 2020-04-01 23:40:41 +02:00
Patrick Pelissier c5238e0a4c Add new example for algorithm 2020-04-01 23:40:16 +02:00
Patrick Pelissier f99ee8aa40 Update documentation 2020-04-01 23:28:07 +02:00
Patrick Pelissier 18c7d0e11a Add test for SET_KEY only containers for ALGO_EXTRACT 2020-04-01 23:27:38 +02:00
Patrick Pelissier 4e67823593 Add support for SET_KEY only containers for ALGO_EXTRACT 2020-04-01 23:27:20 +02:00
Patrick Pelissier e7fcefb391 * Dict supports INIT_WITH method too. 2020-03-29 00:49:36 +01:00
Patrick Pelissier be06426783 Add documentation for ALGO_TRANSFORM 2020-03-28 17:41:29 +01:00
Patrick Pelissier e558e83be3 Add test case for ALGO_TRANSFORM 2020-03-28 17:41:16 +01:00
Patrick Pelissier d77a235b2a Add macro ALGO_TRANSFORM 2020-03-28 17:41:04 +01:00
Patrick Pelissier 3add6bb5bf Improve test suite 2020-03-28 17:17:43 +01:00
Patrick Pelissier 4367daaa00 Add documentation for _transform method. 2020-03-28 13:34:17 +01:00
Patrick Pelissier 4d46b3d126 Add basic test cases for _transform method. 2020-03-28 13:34:02 +01:00
Patrick Pelissier 548cd84a7f Add _transform method for algorithm. 2020-03-28 13:33:43 +01:00
Patrick Pelissier d87ffaa572 Improve documentation. 2020-03-28 13:07:35 +01:00
Patrick Pelissier 370cdb4e45 Add another example. 2020-03-28 13:05:15 +01:00
Patrick Pelissier 068d023917 Factorize in m-core.h the pattern recognication. 2020-03-28 11:36:51 +01:00
Patrick Pelissier 86b6ad54d5 Rename filln, filla, fillan into fill_n, fill_a, fill_an (same name as C++) 2020-03-28 11:10:02 +01:00
Patrick Pelissier bdf999a9fc Disable fully VC++ build as the build is fully broken due to regression in version 16.5 vs 16.4 2020-03-26 22:34:51 +01:00
Patrick Pelissier 39f8b6828b Try workaround against regression with new VisualC++ 2020-03-26 22:03:11 +01:00
Patrick Pelissier 11f84ab34b Document new algorithms 2020-03-26 21:49:04 +01:00
Patrick Pelissier c3a5306266 Add function _fill, _filln, _filla, _fillan as algorithms 2020-03-26 21:48:46 +01:00
Patrick Pelissier 1fe9e4c14c Export ADD / MUL / DIV / SUB for basic C types. 2020-03-26 21:44:19 +01:00
Patrick Pelissier e69203dc50 Remove exported PUSH / POP methods as they don't follow stricly the prototypes of such functions. 2020-03-26 21:43:44 +01:00
Patrick Pelissier 342954f272 Fix introduced build error for Mingw 2020-03-25 11:56:38 +01:00
Patrick Pelissier 741d6b8828 Test string + algorithm 2020-03-25 11:44:35 +01:00
Patrick Pelissier f1f41ef320 * Add missing iterator functions * Export iterators in oplist so that it is usable in algorithm 2020-03-25 11:43:55 +01:00
Patrick Pelissier 785792d1f4 Allow build of examples in C11 mode 2020-03-25 11:17:06 +01:00
Patrick Pelissier 9affe3106c Add example of ALGO_FOR_EACH and ALGO_REDUCE 2020-03-25 11:16:19 +01:00
Patrick Pelissier eb9fd14e2c Fix documentation. 2020-03-25 10:19:43 +01:00
Patrick Pelissier c281a2c339 Update CI script to include VC++ 2020-03-02 18:09:53 +01:00
Patrick Pelissier cb109eb479 Add proper progression for special script 2020-03-02 14:35:49 +01:00
Patrick Pelissier 3c6d194974 Add script to launch the test suite with VC++ 2020-03-02 14:25:42 +01:00
Patrick Pelissier 653a0d9734 Fix build issue for systems where double==long double 2020-03-02 14:23:59 +01:00
Patrick Pelissier a5fbd8405c Avoid C99 construct incompatible with strict C++ compiler 2020-02-24 22:27:43 +01:00
Patrick Pelissier 70994d4f60 Update doc 2020-02-16 11:06:43 +01:00
Patrick Pelissier f15203afb2 Comment a little bit more the examples 2020-02-10 06:47:24 +01:00
Patrick Pelissier 0a0d707afd Document bitset 2020-02-08 23:39:30 +01:00
Patrick Pelissier e206c3fe48 Document SPSC buffer 2020-01-23 23:18:33 +01:00
Patrick Pelissier 7f5704d321 Document MPMC buffer 2020-01-09 22:52:02 +01:00
Patrick Pelissier 4f7b0b9455 Happy new year 2020 2020-01-04 15:41:06 +01:00
Patrick Pelissier f5f16015df In quiet mode, if the result of the bench is not assumed to be reliable, display -1 instead of the result. 2020-01-04 15:12:59 +01:00
Patrick Pelissier 935325e0cb Add bench of emilib 2020-01-04 15:06:24 +01:00
Patrick Pelissier 7b9530ac58 Fix name of bench 2020-01-04 15:05:12 +01:00
Patrick Pelissier a9fc259420 ALGO_EXTRACT func argument is now optional 2019-12-30 14:31:21 +01:00
Patrick Pelissier 6f603b52df Update comments 2019-12-30 14:11:41 +01:00
Patrick Pelissier aeb2a47952 Add comments to example 2019-12-30 13:44:03 +01:00
Patrick Pelissier ca7cea3fe3 Use of linear probing and the same hash function as other libraries 2019-12-30 00:12:05 +01:00
Patrick Pelissier f14aca8808 Port to new UDB2 protocol 2019-12-29 23:51:30 +01:00
Patrick Pelissier f1e5e9d9db Simplify code to use get_at method with its get & create semantic 2019-12-29 23:45:17 +01:00
Patrick Pelissier cecba9777a Update documentation on buffer/queues 2019-12-27 16:42:54 +01:00
Patrick Pelissier 4352267034 Update deprecated API 2019-12-27 16:42:00 +01:00
Patrick Pelissier 0c3730d9a3 Migrate version to 0.3.1 2019-12-27 16:41:42 +01:00
Patrick Pelissier 5111b0c726 Deprecated some buffer options since the _blocking functions are much more usefull 2019-12-27 16:39:42 +01:00
Patrick Pelissier 8ecd3f1592 Add best_within and variance 2019-12-23 23:05:48 +01:00
Patrick Pelissier 0a6f8851c9 Update list of bench to launch automatically 2019-12-20 21:37:51 +01:00
141 changed files with 30656 additions and 16617 deletions

No files matched your search

+87 -15
View File
@@ -1,6 +1,6 @@
name: C/C++ CI
on: [push]
on: [push, pull_request]
jobs:
build:
@@ -11,24 +11,96 @@ jobs:
steps:
- uses: actions/checkout@v1
- name: make
run: make
- name: make check
run: make check
- name: make check C99
run: make clean && make check -j 2 CC="cc -std=c99 -Wno-unknown-warning-option -Werror"
- name: make check C11
working-directory: ./tests
run: make clean && make check -j 2 CC="cc -std=c11 -Wno-unknown-warning-option -Werror"
- name: make check C++
working-directory: ./tests
run: make clean && make check -j 2 CC="c++ -std=c++11"
build_windows_mingw:
strategy:
matrix:
platform: [windows-latest]
runs-on: ${{ matrix.platform }}
build_linux32:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Install MINGW
run: choco install mingw --no-progress
- name: make
- name: update package list
run: sudo apt-get update
- name: install multilib
run: sudo apt-get install gcc-multilib g++-multilib
- name: make check C99 (32bits)
working-directory: ./tests
run: make clean && make check -j 2 CC="gcc -m32 -std=c99 -Wno-unknown-warning-option -Werror"
- name: make check C11 (32bits)
working-directory: ./tests
run: make clean && make check -j 2 CC="gcc -m32 -std=c11 -Wno-unknown-warning-option -Werror"
- name: make check C++ (32 bits)
working-directory: ./tests
run: make clean && make check -j 2 CC="g++ -m32 -std=c++11 -Wno-unknown-warning-option "
- name: make check against C++ STL
working-directory: ./tests
run: make clean && make check-stl -j 2
build_linux_tcc:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Clone TCC
shell: bash
run: mingw32-make CC="gcc -std=c99 -D__USE_MINGW_ANSI_STDIO=1"
run: git clone https://repo.or.cz/tinycc.git
- name: Configure, build & install TCC
shell: bash
run: cd tinycc && ./configure --prefix=/tmp/tcc && make && make install
- name: make depend
shell: bash
run: make depend
- name: make check
shell: bash
run: mingw32-make CC="gcc -std=c99 -D__USE_MINGW_ANSI_STDIO=1" check
run: make CC="/tmp/tcc/bin/tcc -std=c99" check
build_windows_mingw:
runs-on: windows-latest
steps:
- uses: actions/checkout@v1
- name: make check
shell: bash
run: mingw32-make -j 2 CC="gcc -std=c99 -D__USE_MINGW_ANSI_STDIO=1" check
build_windows_msys2:
runs-on: windows-latest
defaults:
run:
shell: msys2 {0}
steps:
- uses: actions/checkout@v2
- uses: msys2/setup-msys2@v2
with:
msystem: MINGW64
update: true
install: git mingw-w64-x86_64-toolchain make
- name: make check
run: make -j 2 CC="gcc -std=c99 -D__USE_MINGW_ANSI_STDIO=1" check
build_windows_visual:
runs-on: windows-latest
steps:
- uses: actions/checkout@v1
- name: make check
shell: cmd
working-directory: ./tests
run: Make-check-cl.bat cl
build_windows_clang_cl:
runs-on: windows-latest
steps:
- uses: actions/checkout@v1
- name: make check
shell: cmd
working-directory: ./tests
run: Make-check-cl.bat clang-cl
+53
View File
@@ -0,0 +1,53 @@
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
name: "CodeQL"
on:
push:
branches: [master]
pull_request:
# The branches below must be a subset of the branches above
branches: [master]
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
# Override automatic language detection by changing the below list
# Supported options are ['csharp', 'cpp', 'go', 'java', 'javascript', 'python']
language: ['cpp']
# Learn more...
# https://docs.github.com/en/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#overriding-automatic-language-detection
steps:
- name: Checkout repository
uses: actions/checkout@v2
with:
# We must fetch at least the immediate parents so that if this is
# a pull request then we can checkout the head.
fetch-depth: 2
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# queries: ./path/to/local/query, your-org/your-repo/queries@main
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
- name: Autobuild
working-directory: ./tests
run: make exe
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1
+5
View File
@@ -38,3 +38,8 @@ depend
other/
a*.dat
config
*.log
.vscode
.vs
tmp-serial.*
*~
+1 -1
View File
@@ -1,6 +1,6 @@
BSD 2-Clause License
Copyright (c) 2017-2019, Patrick Pelissier
Copyright (c) 2017-2021, Patrick Pelissier
All rights reserved.
Redistribution and use in source and binary forms, with or without
+48 -11
View File
@@ -1,6 +1,29 @@
# Copyright (c) 2017-2021, Patrick Pelissier
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# + Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# + Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# Environnement variable. To customize if needed.
RM=rm -f
MKDIR=mkdir -p
RMDIR=rmdir
INSTALL=install
INSTALL_PROGRAM=${INSTALL}
INSTALL_DATA=${INSTALL} -m 644
@@ -10,15 +33,15 @@ PREFIX=/usr/local
DESTDIR=
# Package name & version.
PACKAGE=m*lib-$(VERSION)
VERSION=0.3.0
PACKAGE=m_lib-$(VERSION)
VERSION=0.6.0
# Define the contain of the distribution tarball
HEADER=m-algo.h m-array.h m-atomic.h m-bitset.h m-bptree.h m-buffer.h m-c-mempool.h m-concurrent.h m-core.h m-deque.h m-dict.h m-genint.h m-i-list.h m-i-shared.h m-list.h m-mempool.h m-mutex.h m-prioqueue.h m-rbtree.h m-serial-bin.h m-serial-json.h m-shared.h m-snapshot.h m-string.h m-tuple.h m-variant.h m-worker.h
HEADER=m-algo.h m-array.h m-atomic.h m-bitset.h m-bptree.h m-buffer.h m-c-mempool.h m-concurrent.h m-core.h m-deque.h m-dict.h m-funcobj.h m-genint.h m-i-list.h m-i-shared.h m-list.h m-mempool.h m-mutex.h m-prioqueue.h m-rbtree.h m-serial-bin.h m-serial-json.h m-shared.h m-snapshot.h m-string.h m-tuple.h m-variant.h m-worker.h
DOC1=LICENSE README.md
DOC2=doc/API.txt doc/Container.html doc/Container.ods doc/depend.png doc/DEV.md doc/ISSUES.org doc/oplist.odp doc/oplist.png
EXAMPLE=example/ex-array00.c example/ex-array01.c example/ex-array02.c example/ex-array03.c example/ex-array04.c example/ex-bptree01.c example/ex-buffer01.c example/ex-dict01.c example/ex-dict02.c example/ex-dict03.c example/ex-dict04.c example/ex-grep01.c example/ex-json01.c example/ex-list01.c example/ex-mph.c example/ex-multi01.c example/ex-multi02.c example/ex-multi03.c example/ex-multi04.c example/ex-rbtree01.c example/ex-section.c example/Makefile
TEST=tests/test-malgo.c tests/test-marray.c tests/test-mbitset.c tests/test-mbptree.c tests/test-mbuffer.c tests/test-mcmempool.c tests/test-mconcurrent.c tests/test-mcore.c tests/test-mdeque.c tests/test-mdict.c tests/test-mgenint.c tests/test-milist.c tests/test-mlist.c tests/test-mmempool.c tests/test-mmutex.c tests/test-mprioqueue.c tests/test-mrbtree.c tests/test-mserial-bin.c tests/test-mserial-json.c tests/test-mshared.c tests/test-msnapshot.c tests/test-mstring.c tests/test-mtuple.c tests/test-mvariant.c tests/test-mworker.c tests/tgen-bitset.c tests/tgen-marray.c tests/tgen-mdict.c tests/tgen-mlist.c tests/tgen-mstring.c tests/tgen-openmp.c tests/tgen-queue.c tests/tgen-shared.c tests/wip-mregister.c tests/Makefile tests/coverage.h tests/test-obj.h tests/dict.txt
EXAMPLE=example/ex11-algo01.c example/ex11-algo02.c example/ex11-json01.c example/ex11-section.c example/ex-algo02.c example/ex-algo03.c example/ex-algo04.c example/ex-array00.c example/ex-array01.c example/ex-array02.c example/ex-array03.c example/ex-array04.c example/ex-array05.c example/ex-bptree01.c example/ex-buffer01.c example/ex-dict01.c example/ex-dict02.c example/ex-dict03.c example/ex-dict04.c example/ex-grep01.c example/ex-list01.c example/ex-mph.c example/ex-multi01.c example/ex-multi02.c example/ex-multi03.c example/ex-multi04.c example/ex-multi05.c example/ex-rbtree01.c example/ex11-algo02.json example/ex11-json01.json example/Makefile example/ex-defer01.c example/ex-string01.c example/ex-string02.c example/ex-astar.c example/ex-string03.c example/ex11-tstc.c
TEST=tests/test-malgo.c tests/test-marray.c tests/test-mbitset.c tests/test-mbptree.c tests/test-mbuffer.c tests/test-mcmempool.c tests/test-mconcurrent.c tests/test-mcore.c tests/test-mdeque.c tests/test-mdict.c tests/test-mfuncobj.c tests/test-mgenint.c tests/test-milist.c tests/test-mlist.c tests/test-mmempool.c tests/test-mmutex.c tests/test-mprioqueue.c tests/test-mrbtree.c tests/test-mserial-bin.c tests/test-mserial-json.c tests/test-mshared.c tests/test-msnapshot.c tests/test-mstring.c tests/test-mtuple.c tests/test-mvariant.c tests/test-mworker.c tests/tgen-bitset.c tests/tgen-marray.c tests/tgen-mdict.c tests/tgen-mlist.c tests/tgen-mstring.c tests/tgen-openmp.c tests/tgen-queue.c tests/tgen-shared.c tests/tgen-mserial.c tests/Makefile tests/coverage.h tests/test-obj.h tests/dict.txt tests/fail-chain-oplist.c tests/fail-incompatible.c tests/fail-no-oplist.c tests/test-mishared.c tests/check-array.cpp tests/check-deque.cpp tests/check-dplist.cpp tests/check-list.cpp tests/check-rbtree.cpp tests/check-uset.cpp tests/check-generic.hpp
.PHONY: all test check doc clean distclean depend install uninstall dist
@@ -35,10 +58,11 @@ checkall:
cd tests && $(MAKE) checkall
cd example && $(MAKE) all
html: doc
doc: README.md doc/depend.png
html: README.md
markdown < README.md > README.html
doc: html doc/depend.png
clean:
cd tests && $(MAKE) clean
cd example && $(MAKE) clean
@@ -58,7 +82,7 @@ doc/depend.png: $(HEADER)
dot -Tpng depend.dot -o doc/depend.png
optipng -o7 doc/depend.png
dist: $(HEADER) $(DOC1) $(DOC2) $(EXAMPLE) $(TEST) Makefile clean
dist: $(HEADER) $(DOC1) $(DOC2) $(EXAMPLE) $(TEST) Makefile clean versioncheck
$(MKDIR) '$(PACKAGE)'
$(MKDIR) '$(PACKAGE)/doc'
$(MKDIR) '$(PACKAGE)/tests'
@@ -73,9 +97,22 @@ dist: $(HEADER) $(DOC1) $(DOC2) $(EXAMPLE) $(TEST) Makefile clean
distcheck: dist
cd '$(PACKAGE)' && make check
versioncheck:
@if test "$(VERSION)." != `grep M_CORE_VERSION m-core.h |awk '{printf "%d.",$$3 } END {printf "\n"}'` ; then echo "ERROR: Version mismatch between Makefile & HEADERS" ; exit 2 ; fi
@for i in *.h ; do echo $(HEADER) | grep -q $$i ; if test $$? -ne 0 ; then echo "ERROR: Missing header $$i in Makefile" ; exit 3 ; fi ; done
@for i in doc/* ; do echo $(DOC2) | grep -q $$i ; if test $$? -ne 0 ; then echo "ERROR: Missing document $$i in Makefile" ; exit 4 ; fi ; done
@for i in tests/*.c tests/*.txt tests/*.h ; do echo $(TEST) | grep -q $$i ; if test $$? -ne 0 ; then echo "ERROR: Missing test $$i in Makefile" ; exit 5 ; fi ; done
@for i in example/*.c example/*.json ; do echo $(EXAMPLE) | grep -q $$i ; if test $$? -ne 0 ; then echo "ERROR: Missing example $$i in Makefile" ; exit 6 ; fi ; done
@for i in tests/*.cpp tests/*.hpp ; do echo $(TEST) | grep -q $$i ; if test $$? -ne 0 ; then echo "ERROR: Missing test $$i in Makefile" ; exit 7 ; fi ; done
install:
$(MKDIR) $(DESTDIR)$(PREFIX)/include
$(INSTALL_DATA) $(HEADER) $(DESTDIR)$(PREFIX)/include
$(MKDIR) $(DESTDIR)$(PREFIX)/include/m-lib
$(INSTALL_DATA) $(HEADER) $(DESTDIR)$(PREFIX)/include/m-lib
uninstall:
for i in $(HEADER) ; do $(RM) $(DESTDIR)$(PREFIX)/include/$$i ; done
for i in $(HEADER) ; do $(RM) $(DESTDIR)$(PREFIX)/include/m-lib/$$i ; done
$(RMDIR) $(DESTDIR)$(PREFIX)/include/m-lib/
format:
cd example && $(MAKE) ex-string01.exe
for i in $(HEADER) ; do ./example/ex-string01.exe $$i > tmp.h && mv tmp.h $$i ; done
+2661 -926
View File
File diff suppressed because it is too large. Load diff
+95 -23
View File
@@ -1,3 +1,25 @@
# Copyright (c) 2017-2021, Patrick Pelissier
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# + Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# + Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
CC=cc -std=c11
CXX=c++ -std=c++11
CFLAGS=-O2 -march=native -Wall
@@ -7,7 +29,7 @@ N=4
BENCH_DEF=
RM=rm -rf
.PHONY: all pgo container queue mempool string plain bench-mlib bench-mlib-mempool bench-stl bench-qt bench-glib bench-klib bench-libdynamic bench-sparsepp bench-collectionc bench-tommyds bench-flathashmap bench-hopscotchmap bench-mlib-thread bench-liblfds bench-concurrentqueue bench-boost bench-mempool bench-string bench-plain
.PHONY: all pgo container queue mempool string plain bench-mlib bench-mlib-mempool bench-stl bench-qt bench-glib bench-klib bench-libdynamic bench-sparsepp bench-collectionc bench-tommyds bench-flathashmap bench-emilib bench-hopscotchmap bench-mlib-thread bench-liblfds bench-concurrentqueue bench-boost bench-mempool bench-string bench-plain bench-rigtorp-mpmc-queue bench-cmc
all: container queue mempool string plain
@@ -17,10 +39,10 @@ pgo:
#########################################################################
container: bench-mlib bench-mlib-mempool bench-stl bench-qt bench-glib bench-klib bench-libdynamic bench-sparsepp bench-collectionc bench-tommyds bench-flathashmap bench-hopscotchmap
container: bench-mlib bench-mlib-mempool bench-stl bench-qt bench-glib bench-klib bench-libdynamic bench-cmc bench-sparsepp bench-densehashmap bench-collectionc bench-tommyds bench-flathashmap bench-emilib bench-hopscotchmap bench-uthash bench-qlibc bench-libsrt bench-nedtries bench-rigtorp-hashmap bench-ctl
@echo "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
queue: bench-mlib-thread bench-liblfds bench-concurrentqueue bench-boost
queue: bench-mlib-thread bench-liblfds bench-concurrentqueue bench-boost bench-rigtorp-mpmc-queue
@echo "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
mempool: bench-mempool
@@ -130,6 +152,16 @@ bench-klib0:
@./bench-klib.exe 41
@./bench-klib.exe 50
# CMC shall point to the directory where the CMC main header is
bench-cmc:
@if test -n "$${CMC}" ; then $(MAKE) bench-cmc0 ; else echo "Nothing to be done for CMC." ; fi
bench-cmc0:
$(CC) $(CFLAGS) $(XCFLAGS) $(CPPFLAGS) -I $${CMC} bench-cmc.c common.c -o bench-cmc.exe
@./bench-cmc.exe 20
@./bench-cmc.exe 30
@./bench-cmc.exe 40
# LIBDYNAMIC shall point to the the directory containing the file libdynamic.pc
bench-libdynamic:
@if test -n "$${LIBDYNAMIC}" ; then $(MAKE) bench-libdynamic0 ; else echo "Nothing to be done for LIBDYNAMIC." ; fi
@@ -160,12 +192,12 @@ bench-densehashmap0:
@./bench-densehashmap.exe 42
@./bench-densehashmap.exe 43
# COLLECTIONC shall point to the directory where the 'src' directory is.
# COLLECTIONC shall point to the directory where it is installed
bench-collectionc:
@if test -n "$${COLLECTIONC}" ; then $(MAKE) bench-collectionc0 ; else echo "Nothing to be done for COLLECTIONC." ; fi
bench-collectionc0:
$(CC) $(CFLAGS) $(XCFLAGS) $(CPPFLAGS) -I "$${COLLECTIONC}/include" -L "$${COLLECTIONC}" -static bench-collectionc.c common.c -lcollectc -o bench-collectionc.exe
$(CC) $(CFLAGS) $(XCFLAGS) $(CPPFLAGS) -I "$${COLLECTIONC}/include/collectc" bench-collectionc.c common.c "$${COLLECTIONC}/lib/libcollectc.a" -o bench-collectionc.exe
@./bench-collectionc.exe 10
@./bench-collectionc.exe 20
@./bench-collectionc.exe 30
@@ -196,6 +228,17 @@ bench-flathashmap0:
@./bench-flathashmap.exe 46
@./bench-flathashmap.exe 43
# EMILIB shall point to the directory where the headers are
bench-emilib:
@if test -n "$${EMILIB}" ; then $(MAKE) bench-emilib0 ; else echo "Nothing to be done for EMILIB." ; fi
bench-emilib0:
$(CXX) -std=c++14 $(CFLAGS) $(XCFLAGS) $(CPPFLAGS) -I "$${EMILIB}" bench-emilib.cpp common.c -o bench-emilib.exe
@./bench-emilib.exe 41
@./bench-emilib.exe 42
@./bench-emilib.exe 46
@./bench-emilib.exe 43
# HOPSCOTCHMAP shall point to the directory where the source are
bench-hopscotchmap:
@if test -n "$${HOPSCOTCHMAP}" ; then $(MAKE) bench-hopscotchmap0 ; else echo "Nothing to be done for HOPSCOTCHMAP." ; fi
@@ -214,9 +257,8 @@ bench-uthash0:
$(CC) $(CFLAGS) $(XCFLAGS) $(CPPFLAGS) -I "$${UTHASH}" bench-uthash.c common.c -o bench-uthash.exe
@./bench-uthash.exe 10
@./bench-uthash.exe 20
@./bench-uthash.exe 40
@./bench-uthash.exe 41
@./bench-uthash.exe 42
@./bench-uthash.exe 43
@./bench-uthash.exe 50
# QLIBC shall point to the directory where the library is installed.
@@ -228,21 +270,14 @@ bench-qlibc0:
@LD_LIBRARY_PATH="$${QLIBC}/lib:$${LD_LIBRARY_PATH}" ./bench-qlibc.exe 10
@LD_LIBRARY_PATH="$${QLIBC}/lib:$${LD_LIBRARY_PATH}" ./bench-qlibc.exe 20
@LD_LIBRARY_PATH="$${QLIBC}/lib:$${LD_LIBRARY_PATH}" ./bench-qlibc.exe 30
@LD_LIBRARY_PATH="$${QLIBC}/lib:$${LD_LIBRARY_PATH}" ./bench-qlibc.exe 42
@LD_LIBRARY_PATH="$${QLIBC}/lib:$${LD_LIBRARY_PATH}" ./bench-qlibc.exe 41
# LIBSRT shall point to the directory where the source are
# The library shall be built.
# LIBSRT shall point to the directory where it is installed
bench-libsrt:
@if test -n "$${LIBSRT}" ; then $(MAKE) bench-libsrt0 ; else echo "Nothing to be done for LIBSRT." ; fi
bench-libsrt0:
$(CC) $(CFLAGS) $(XCFLAGS) $(CPPFLAGS) -I "$${LIBSRT}/src" bench-libsrt.c common.c -o bench-libsrt.exe $${LIBSRT}/libsrt.a
@./bench-libsrt.exe 10
$(CC) $(CFLAGS) $(XCFLAGS) $(CPPFLAGS) -I "$${LIBSRT}/include/libsrt" bench-libsrt.c common.c -o bench-libsrt.exe $${LIBSRT}/lib/libsrt.a
@./bench-libsrt.exe 20
@./bench-libsrt.exe 41
@./bench-libsrt.exe 42
@./bench-libsrt.exe 43
@./bench-libsrt.exe 50
@@ -297,6 +332,40 @@ bench-rigtorp-hashmap0:
@./bench-rigtorp-hashmap.exe 41
@./bench-rigtorp-hashmap.exe 43
# RIGTORP_MPMC_QUEUE shall point to the directory where the headers are
bench-rigtorp-mpmc-queue:
@if test -n "$${RIGTORP_MPMC_QUEUE}" ; then $(MAKE) bench-rigtorp-mpmc-queue0 ; else echo "Nothing to be done for RIGTORP_MPMC_QUEUE." ; fi
bench-rigtorp-mpmc-queue0:
$(CXX) $(CFLAGS) $(XCFLAGS) $(CPPFLAGS) -I "$${RIGTORP_MPMC_QUEUE}" bench-rigtorp-mpmcqueue.cpp common.c -DMULTI_THREAD_MEASURE -o bench-mpmcqueue.exe -lpthread
@./bench-mpmcqueue.exe 60
# CTL shall point to the source directory (not where the headers are)
bench-ctl:
@if test -n "$${CTL}" ; then $(MAKE) bench-ctl0 ; else echo "Nothing to be done for CTL." ; fi
bench-ctl0:
$(CC) $(CFLAGS) $(XCFLAGS) $(CPPFLAGS) -I $${CTL} bench-ctl.c common.c -o bench-ctl.exe
@./bench-ctl.exe 10
@./bench-ctl.exe 20
@./bench-ctl.exe 30
@./bench-ctl.exe 40
@./bench-ctl.exe 50
############################################################################
bench-mlib-json: bench-mlib
@./bench-mlib.exe 110
@./bench-mlib.exe 111
@./bench-mlib.exe 112
bench-rapidjson:
@if test -n "$${RAPIDJSON}" ; then $(MAKE) bench-rapidjson0 ; else echo "Nothing to be done for RAPIDJSON." ; fi
bench-rapidjson0:
$(CXX) $(CFLAGS) $(XCFLAGS) $(CPPFLAGS) -I "$${RAPIDJSON}/" bench-rapidjson.cpp common.c -o bench-rapidjson.exe
@./bench-rapidjson.exe 110
@./bench-rapidjson.exe 111
@./bench-rapidjson.exe 112
############################################################################
bench-plain:
@@ -320,19 +389,16 @@ bench-maxdict:
############################################################################
# BSTRLIB shall point to the BSTRLIB sources
# LIBSRT shall point to the LIBSRT sources
# LIBSRT shall point to the LIBSRT install directory
bench-string:
@if test -n "$${BSTRLIB}" ; then $(MAKE) bench-string-step1 BENCH_DEF="-DBENCH_CAN_USE_BSTRLIB -I ${BSTRLIB} $${BSTRLIB}/obj/bstrlib.o $${BSTRLIB}/obj/bstraux.o $${BSTRLIB}/obj/bstrwrap.o" ; else $(MAKE) bench-string-step1 ; fi
bench-string-step1:
@if test -n "$${LIBSRT}" ; then $(MAKE) bench-string-step2 BENCH_DEF="$(BENCH_DEF) -DBENCH_CAN_USE_LIBSRT -I$${LIBSRT}/src $${LIBSRT}/libsrt.a" ; else $(MAKE) bench-string-step2 BENCH_DEF="$(BENCH_DEF)"; fi
@if test -n "$${LIBSRT}" ; then $(MAKE) bench-string-step2 BENCH_DEF="$(BENCH_DEF) -DBENCH_CAN_USE_LIBSRT -I$${LIBSRT}/include/libsrt $${LIBSRT}/lib/libsrt.a" ; else $(MAKE) bench-string-step2 BENCH_DEF="$(BENCH_DEF)"; fi
#NOTE: Need to build by hand sds.o since it is not build by default and sds.c is not compatible with C++
bench-string-step2:
@if test -n "$${SDS}" ; then $(MAKE) bench-string-step3 BENCH_DEF="$(BENCH_DEF) -fpermissive -DBENCH_CAN_USE_SDS -I$${SDS}/ $${SDS}/sds.o" ; else $(MAKE) bench-string-step3 BENCH_DEF="$(BENCH_DEF)"; fi
bench-string-step3:
@if test -n "$${RAPIDSTRING}" ; then $(MAKE) bench-string-step4 BENCH_DEF="$(BENCH_DEF) -DBENCH_CAN_USE_RAPIDSTRING -I$${RAPIDSTRING}/ " ; else $(MAKE) bench-string-step4 BENCH_DEF="$(BENCH_DEF)"; fi
@if test -n "$${SDS}" ; then $(MAKE) bench-string-step4 BENCH_DEF="$(BENCH_DEF) -fpermissive -DBENCH_CAN_USE_SDS -I$${SDS}/ $${SDS}/sds.o" ; else $(MAKE) bench-string-step4 BENCH_DEF="$(BENCH_DEF)"; fi
bench-string-step4:
@if test -n "$${GLIB}" ; then $(MAKE) bench-string-step5 BENCH_DEF="$(BENCH_DEF) -DBENCH_CAN_USE_GLIB $$(pkg-config --cflags --libs glib-2.0)" ; else $(MAKE) bench-string-step5 BENCH_DEF="$(BENCH_DEF)"; fi
@@ -344,7 +410,6 @@ bench-string-step5:
@./bench-string-2.exe 2000000 0
@./bench-string-2.exe 2000000 1
@./bench-string-2.exe 2000000 2
@./bench-string-2.exe 2000000 3
@./bench-string-2.exe 2000000 4
bench-string-pgo:
@@ -353,11 +418,18 @@ bench-string-pgo:
############################################################################
bench-find-sort:
g++ bench-find-sort.cpp -O2 -march=native -std=c++11 -I.. -g common.c -o bench-find-sort.exe
./bench-find-sort.exe 10000000
############################################################################
clean:
$(RM) *.o bench-*.exe
$(RM) bench-*.s *~ massif.out.*
$(RM) plot-*.dat
$(RM) pgo
$(RM) tmp-serial.*
cd nucleotide && $(MAKE) clean
############################################################################
+204
View File
@@ -0,0 +1,204 @@
#define NDEBUG
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include "macro_collections.h"
#include "common.h"
/********************************************************************************************/
// CMC list are dynamic array
#define MY_LIST_PARAMS (list_uint, list_uint_s, , , unsigned int)
C_MACRO_COLLECTIONS_EXTENDED(CMC, LIST, MY_LIST_PARAMS, (STR))
struct list_uint_s_fval list_fval = { .cmp = NULL,
.cpy = NULL,
.str = NULL,
.free = NULL,
.hash = NULL,
.pri = NULL };
static void test_array(size_t n)
{
struct list_uint_s *a1 = list_uint_new(1, &list_fval);
struct list_uint_s *a2 = list_uint_new(1, &list_fval);
for(size_t i = 0; i < n; i++) {
list_uint_push_back(a1, rand_get() );
list_uint_push_back(a2, rand_get() );
}
unsigned int s = 0;
for(unsigned long i = 0; i < n; i++) {
s += list_uint_get(a1, i ) * list_uint_get(a2, i );
}
g_result = s;
list_uint_free(a1);
list_uint_free(a2);
}
/********************************************************************************************/
#define my_cmp(a,b) ( (a) < (b) ? -1 : (a) > (b) )
#define MY_TMAP_PARAMS (tree_ulong, tree_ulong_s, , unsigned long, bool)
C_MACRO_COLLECTIONS_EXTENDED(CMC, TREEMAP, MY_TMAP_PARAMS, (STR))
int cmp_ulong(unsigned long a, unsigned long b) { return my_cmp(a,b); }
struct tree_ulong_s_fkey tree_fkey = { .cmp = cmp_ulong,
.cpy = NULL,
.str = NULL,
.free = NULL,
.hash = NULL,
.pri = NULL };
struct tree_ulong_s_fval tree_fval = { .cmp = NULL,
.cpy = NULL,
.str = NULL,
.free = NULL,
.hash = NULL,
.pri = NULL };
static void test_rbtree(size_t n)
{
struct tree_ulong_s *tree;
tree = tree_ulong_new(&tree_fkey, &tree_fval);
for (size_t i = 0; i < n; i++) {
unsigned long j = rand_get();
tree_ulong_insert(tree, j, true);
}
rand_init();
unsigned int s = 0;
for (size_t i = 0; i < n; i++) {
unsigned long j = rand_get();
if (tree_ulong_get_ref(tree, j) != 0)
s+= j;
}
g_result = s;
tree_ulong_free(tree);
}
/********************************************************************************************/
#define hash_func(a) kh_int64_hash_func(a)
size_t hash_ulong(unsigned long a)
{
return ( (a) >> 33 ) ^ (a) ^ ((a) << 11);
}
#define MY_DICT_PARAMS (hmap, hmap_s, , unsigned long, unsigned long)
C_MACRO_COLLECTIONS_EXTENDED(CMC, HASHMAP, MY_DICT_PARAMS, (STR))
struct hmap_s_fkey hmap_fkey = { .cmp = cmp_ulong,
.cpy = NULL,
.str = NULL,
.free = NULL,
.hash = hash_ulong,
.pri = NULL };
struct hmap_s_fval hmap_fval = { .cmp = NULL,
.cpy = NULL,
.str = NULL,
.free = NULL,
.hash = NULL,
.pri = NULL };
static void
test_dict(size_t n)
{
struct hmap_s *dict = hmap_new(16, 0.7, &hmap_fkey, &hmap_fval);
for (size_t i = 0; i < n; i++) {
hmap_insert(dict, rand_get(), rand_get());
}
rand_init();
unsigned int s = 0;
for (size_t i = 0; i < n; i++) {
unsigned long *val = hmap_get_ref(dict, rand_get());
if (val != 0)
s += *val;
}
g_result = s;
hmap_free(dict);
}
/********************************************************************************************/
#if 0 // Not working issue in using not integer types
typedef struct {
char a[256];
} char_array_t;
static inline int char_cmp (const char_array_t a, const char_array_t b) { return strcmp(a.a,b.a); }
static inline size_t char_hash(const char_array_t a) {
size_t hash = 0;
const char *s = a.a;
while (*s) hash = hash * 31421 + (*s++) + 6927;
return hash;
}
#define MY_DICTB_PARAMS (bhmap, bhmap_s, , char_array_t, char_array_t)
C_MACRO_COLLECTIONS_EXTENDED(CMC, HASHMAP, MY_DICT_PARAMS, (STR))
struct bhmap_s_fkey bhmap_fkey = { .cmp = char_cmp,
.cpy = NULL,
.str = NULL,
.free = NULL,
.hash = char_hash,
.pri = NULL };
struct bhmap_s_fval bhmap_fval = { .cmp = NULL,
.cpy = NULL,
.str = NULL,
.free = NULL,
.hash = NULL,
.pri = NULL };
static void
test_dict_big(size_t n)
{
struct bhmap_s *dict = bhmap_new(16, 0.7, &bhmap_fkey, &bhmap_fval);
for (size_t i = 0; i < n; i++) {
char_array_t s1, s2;
sprintf(s1.a, "%u", rand_get());
sprintf(s2.a, "%u", rand_get());
bhmap_insert(dict, s1, s2);
}
rand_init();
unsigned int s = 0;
for (size_t i = 0; i < n; i++) {
char_array_t s1;
sprintf(s1.a, "%u", rand_get() );
char_array_t *val = bhmap_get_ref(dict, s1);
if (val != 0)
s ++;
}
g_result = s;
bhmap_free(dict);
}
#endif
/********************************************************************************************/
const config_func_t table[] = {
{ 20, "Array", 100000000, 0, test_array, 0},
{ 30, "Rbtree", 1000000, 0, test_rbtree, 0},
{ 40, "dict", 1000000, 0, test_dict, 0},
//{ 41, "dictBig", 1000000, 0, test_dict_big, 0},
};
int main(int argc, const char *argv[])
{
test("CMC", numberof(table), table, argc, argv);
exit(0);
}
+182
View File
@@ -0,0 +1,182 @@
#define NDEBUG
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include "m-core.h"
#include "common.h"
typedef unsigned int uint;
typedef unsigned long ulong;
/********************************************************************************************/
#define POD
#define T uint
#include "ctl/vector.h"
static void test_array(size_t n)
{
vec_uint a1 = vec_uint_init();
vec_uint a2 = vec_uint_init();
for(size_t i = 0; i < n; i++) {
vec_uint_push_back(&a1, rand_get() );
vec_uint_push_back(&a2, rand_get() );
}
unsigned int s = 0;
for(unsigned long i = 0; i < n; i++) {
s += *vec_uint_at(&a1, i ) * *vec_uint_at(&a2, i );
}
g_result = s;
vec_uint_free(&a1);
vec_uint_free(&a2);
}
/********************************************************************************************/
#define POD
#define T uint
#include "ctl/forward_list.h"
static void test_list (size_t n)
{
slist_uint a1 = slist_uint_init();
slist_uint a2 = slist_uint_init();
for(size_t i = 0; i < n; i++) {
slist_uint_push_front(&a1, rand_get());
slist_uint_push_front(&a2, rand_get());
}
unsigned int s = 0;
slist_uint_it it1 = slist_uint_begin(&a1);
slist_uint_it it2 = slist_uint_begin(&a2);
for( ; !slist_uint_it_done(&it1) ;
slist_uint_it_next(&it1), slist_uint_it_next(&it2)) {
s += *slist_uint_it_ref(&it1) * *slist_uint_it_ref(&it2);
}
g_result = s;
slist_uint_free(&a1);
slist_uint_free(&a2);
}
/********************************************************************************************/
#define POD
#define T ulong
#include "ctl/set.h"
static inline int
int_cmp(ulong *a, ulong *b) {
return *a < *b;
}
static void test_rbtree(size_t n)
{
set_ulong tree = set_ulong_init (int_cmp);
for (size_t i = 0; i < n; i++) {
set_ulong_insert (&tree, rand_get() );
}
rand_init();
unsigned int s = 0;
for (size_t i = 0; i < n; i++) {
unsigned long j = rand_get();
if (set_ulong_find_node(&tree, j) != NULL)
s+= j;
}
g_result = s;
set_ulong_free(&tree);
}
/********************************************************************************************/
typedef struct {
unsigned long key;
unsigned long value;
} pair_ulong;
// Use of M*LIB hash function
static inline size_t
pair_ulong_hash(pair_ulong *a)
{
return M_HASH_DEFAULT(a->key);
}
static inline int
pair_ulong_equal(pair_ulong *a, pair_ulong *b)
{
return a->key == b->key;
}
static inline void
pair_ulong_free(pair_ulong *a) {
(void) a;
}
static inline pair_ulong
pair_ulong_copy(pair_ulong *self) {
return (pair_ulong) { .key = self->key, .value = self->value };
}
#define T pair_ulong
#include <ctl/unordered_map.h>
// It seems broken: it doesn't output the expected result.
static void
test_dict(size_t n)
{
umap_pair_ulong dict = umap_pair_ulong_init(pair_ulong_hash, pair_ulong_equal);
for (size_t i = 0; i < n; i++) {
umap_pair_ulong_insert(&dict, (pair_ulong) { rand_get(), rand_get() });
}
rand_init();
unsigned int s = 0;
for (size_t i = 0; i < n; i++) {
umap_pair_ulong_it it = umap_pair_ulong_find(&dict, (pair_ulong) { rand_get() , 0 } );
if (!umap_pair_ulong_it_done(&it) )
s += it.ref->value;
}
g_result = s;
umap_pair_ulong_free(&dict);
}
/********************************************************************************************/
#define POD
#define T float
#include "ctl/vector.h"
static void test_sort(size_t n)
{
vec_float a1 = vec_float_init();
for(size_t i = 0; i < n; i++) {
vec_float_push_back(&a1, rand_get());
}
vec_float_sort(&a1);
g_result = *vec_float_at(&a1, 0);
vec_float_free(&a1);
}
/********************************************************************************************/
const config_func_t table[] = {
{ 10, "List", 10000000, 0, test_list, 0},
{ 20, "Array", 100000000, 0, test_array, 0},
{ 30, "Rbtree", 1000000, 0, test_rbtree, 0},
{ 40, "dict", 1000000, 0, test_dict, 0},
{ 50, "Sort", 10000000, 0, test_sort, 0},
};
int main(int argc, const char *argv[])
{
test("CTL", numberof(table), table, argc, argv);
exit(0);
}
+138
View File
@@ -0,0 +1,138 @@
#define NDEBUG
#include <vector>
#include <list>
#include <iterator>
#include <map>
#include <set>
#include <unordered_map>
#include <algorithm>
#include <string>
#include <sstream>
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include "emilib/hash_map.hpp"
using namespace emilib;
using namespace std;
#include "common.h"
/********************************************************************************************/
static void
test_dict2(size_t n)
{
HashMap<unsigned long, unsigned long> dict;
for (size_t i = 0; i < n; i++) {
dict[rand_get()] = rand_get();
}
rand_init();
unsigned int s = 0;
for (size_t i = 0; i < n; i++) {
HashMap<unsigned long, unsigned long>::iterator it = dict.find(rand_get());
if (it != dict.end())
s += it->second;
}
g_result = s;
}
static void
test_dict2_linear(size_t n)
{
HashMap<unsigned long, unsigned long> dict;
for (size_t i = 0; i < n; i++) {
dict[i] = rand_get();
}
rand_init();
unsigned int s = 0;
for (size_t i = 0; i < n; i++) {
HashMap<unsigned long, unsigned long>::iterator it = dict.find(i);
if (it != dict.end())
s += it->second;
}
g_result = s;
}
/********************************************************************************************/
struct char_array_s {
char a[256];
char_array_s () { a[0] = 0 ; }
char_array_s ( const char_array_s & other) { strcpy(a, other.a); }
bool operator==(const char_array_s &other) const { return strcmp(a, other.a) == 0; }
};
namespace std {
template <> struct hash<char_array_s> {
std::size_t operator()(const char_array_s &k) const {
size_t hash = 0;
const char *s = k.a;
while (*s) hash = hash * 31421 + (*s++) + 6927;
return hash;
};
};
}
static void
test_dict_big(size_t n)
{
HashMap<char_array_s, char_array_s> dict;
for (size_t i = 0; i < n; i++) {
char_array_s s1, s2;
sprintf(s1.a, "%u", rand_get());
sprintf(s2.a, "%u", rand_get());
dict[s1] = s2;
}
rand_init();
unsigned int s = 0;
for (size_t i = 0; i < n; i++) {
char_array_s s1;
sprintf(s1.a, "%u", rand_get());
HashMap<char_array_s, char_array_s>::iterator it = dict.find(s1);
if (it != dict.end())
s ++;
}
g_result = s;
}
/********************************************************************************************/
static void
test_dict_str(size_t n)
{
HashMap<string, string> dict;
for (size_t i = 0; i < n; i++) {
string s1 = static_cast<ostringstream*>( &(ostringstream() << rand_get()) )->str();
string s2 = static_cast<ostringstream*>( &(ostringstream() << rand_get()) )->str();
dict[s1] = s2;
}
rand_init();
unsigned int s = 0;
for (size_t i = 0; i < n; i++) {
string s1 = static_cast<ostringstream*>( &(ostringstream() << rand_get()) )->str();
HashMap<string, string>::iterator it = dict.find(s1);
if (it != dict.end())
s ++;
}
g_result = s;
}
/********************************************************************************************/
const config_func_t table[] = {
{ 41, "dictBig", 1000000, 0, test_dict_big, 0},
{ 42,"dict", 1000000, 0, test_dict2, 0},
{ 43, "DictStr", 1000000, 0, test_dict_str, 0},
{ 46, "DictLinear", 1000000, 0, test_dict2_linear, 0}
};
int main(int argc, const char *argv[])
{
test("EMILIB", numberof(table), table, argc, argv);
exit(0);
}
+101
View File
@@ -0,0 +1,101 @@
// program to find longest contiguous subsequence
// based on https://www.geeksforgeeks.org/longest-consecutive-subsequence/
#include <iostream>
#include <unordered_set>
using namespace std;
// Returns length of the longest contiguous subsequence
int cpp_find_longest(int arr[], int n)
{
unordered_set<int> S;
int ans = 0;
// Hash all the array elements
for (int i = 0; i < n; i++)
S.insert(arr[i]);
// check each possible sequence from
// the start then update optimal length
for (int i = 0; i < n; i++) {
// if current element is the starting
// element of a sequence
if (S.find(arr[i] - 1) == S.end()) {
// Then check for next elements
// in the sequence
int j = arr[i] + 1;
while (S.find(j) != S.end())
j++;
// update optimal length if
// this length is more
ans = max(ans, j - arr[i]);
}
}
return ans;
}
#include "m-dict.h"
static inline bool oor_equal_p(int a, unsigned char c) { return a == ((c == 0) ? INT_MIN : INT_MAX); }
static inline void oor_set(int *a, unsigned char c) { *a = ((c == 0) ? INT_MIN : INT_MAX); }
DICT_OASET_DEF(dict_int, int, M_OPEXTEND(M_DEFAULT_OPLIST, OOR_EQUAL(oor_equal_p), OOR_SET(oor_set M_IPTR)))
// Returns length of the longest contiguous subsequence
int mlib_find_longest(int arr[], int n)
{
dict_int_t S;
int ans = 0;
dict_int_init(S);
// Hash all the array elements
for (int i = 0; i < n; i++)
dict_int_push(S, arr[i]);
// check each possible sequence from
// the start then update optimal length
for (int i = 0; i < n; i++) {
// if current element is the starting
// element of a sequence
int *p = dict_int_get(S, arr[i]-1);
if (p == NULL) {
// Then check for next elements
// in the sequence
int j = arr[i] + 1;
while (dict_int_get(S, j) != NULL)
j++;
// update optimal length if
// this length is more
ans = M_MAX(ans, j - arr[i]);
}
}
dict_int_clear(S);
return ans;
}
#include "common.h"
int main(int argc, const char *argv[])
{
int n = argc == 1 ? 10000 : atoi(argv[1]);
int *arr = (int*) malloc(n * sizeof(int));
for(int i = 0; i < n; i++)
arr[i] = rand_get();
unsigned long long t0 = cputime();
cout << "Length of the Longest contiguous subsequence is "
<< cpp_find_longest(arr, n) << endl;
unsigned long long t1 = cputime();
cout << "Length of the Longest contiguous subsequence is "
<< mlib_find_longest(arr, n) << endl;
unsigned long long t2 = cputime();
cout << "Time C++: " << (t1-t0) << " Time M*LIB: " << (t2-t1) << endl;
return 0;
}
+1 -1
View File
@@ -134,6 +134,6 @@ const config_func_t table[] = {
int main(int argc, const char *argv[])
{
test("DENSE-HASPMAP", numberof(table), table, argc, argv);
test("FLAT-HASPMAP", numberof(table), table, argc, argv);
exit(0);
}
+3
View File
@@ -7,6 +7,9 @@
#include <stdint.h>
#include <unistd.h>
// Needed due to compilation error in pool.h
#include <pthread.h>
#include "dynamic.h"
#include "common.h"
+3 -13
View File
@@ -14,8 +14,8 @@
static void test_array(size_t n)
{
sv_t *a1 = sv_alloc ( sizeof (unsigned int), 16, NULL);
sv_t *a2 = sv_alloc ( sizeof (unsigned int), 16, NULL);
srt_vector *a1 = sv_alloc ( sizeof (unsigned int), 16, NULL);
srt_vector *a2 = sv_alloc ( sizeof (unsigned int), 16, NULL);
for(size_t i = 0; i < n; i++) {
unsigned int value = rand_get();
@@ -48,7 +48,7 @@ static int cmp_float (const void *a, const void *b)
static void test_sort(size_t n)
{
sv_t *a1 = sv_alloc(sizeof(float), 16, cmp_float);
srt_vector *a1 = sv_alloc(sizeof(float), 16, cmp_float);
for(size_t i = 0; i < n; i++) {
unsigned int value = rand_get();
sv_push(&a1, &value );
@@ -72,13 +72,3 @@ int main(int argc, const char *argv[])
exit(0);
}
int main(int argc, const char *argv[])
{
int n = (argc > 1) ? atoi(argv[1]) : 0;
if (n == 20)
test_function("Array", 100000000, test_array);
if (n == 50)
test_function("Sort", 10000000, test_sort);
exit(0);
}
+221 -2
View File
@@ -8,6 +8,7 @@
#include "m-list.h"
#include "m-rbtree.h"
#include "m-bptree.h"
#include "m-deque.h"
#include "m-dict.h"
#include "m-algo.h"
#include "m-mempool.h"
@@ -16,6 +17,9 @@
#include "m-mutex.h"
#include "m-deque.h"
#include "m-concurrent.h"
#include "m-tuple.h"
#include "m-serial-bin.h"
#include "m-serial-json.h"
#include "common.h"
@@ -40,6 +44,30 @@ static void test_array(size_t n)
/********************************************************************************************/
DEQUE_DEF(deque_uint, unsigned int)
static void test_deque(size_t n)
{
M_LET(a1, a2, DEQUE_OPLIST(deque_uint)) {
for(size_t i = 0; i < n; i++) {
deque_uint_push_back(a1, rand_get() );
deque_uint_push_back(a2, rand_get() );
}
unsigned int s = 0;
deque_uint_it_t it1, it2;
deque_uint_it(it1, a1);
deque_uint_it(it2, a2);
while (!deque_uint_end_p(it1)) {
s += *deque_uint_cref(it1 ) * *deque_uint_cref(it2 );
deque_uint_next(it1);
deque_uint_next(it2);
}
g_result = s;
}
}
/********************************************************************************************/
// Two benched mode: with or without mempool
#ifdef USE_MEMPOOL
LIST_DEF(list_uint, unsigned int, (MEMPOOL( list_mpool), MEMPOOL_LINKAGE(static)))
@@ -719,7 +747,6 @@ static void test_queue_single_bulk(size_t n)
/********************************************************************************************/
DEQUE_DEF(deque_uint, unsigned int)
CONCURRENT_DEF(cdeque_uint, deque_uint_t, M_OPEXTEND(DEQUE_OPLIST(deque_uint, M_DEFAULT_OPLIST), PUSH(deque_uint_push_front)))
DEQUE_DEF(deque_ull, unsigned long long)
@@ -837,12 +864,198 @@ static void test_core_hash(size_t n)
}
/********************************************************************************************/
ARRAY_DEF(vector_string, string_t)
vector_string_t vstring;
vector_string_t vstring2;
static void
bench_vector_string_init(size_t n)
{
vector_string_init(vstring);
for(size_t i = 0; i < n; i++)
{
M_LET( (s, "%zu", i, i, i, i), string_t) {
vector_string_push_back(vstring, s);
}
}
vector_string_init(vstring2);
}
static void
bench_vector_string_init_big(size_t n)
{
vector_string_init(vstring);
for(size_t i = 0; i < n; i++)
{
M_LET( (s, "%zu%zu%zu%zu%zu%zu", i, i, i, i, i, i), string_t) {
vector_string_push_back(vstring, s);
}
}
vector_string_init(vstring2);
}
static void
bench_vector_string_bin_run(size_t n)
{
if (vector_string_size(vstring) != n) {
printf("Size are different!\n");
abort();
}
FILE *f = fopen("tmp-serial.dat", "wb");
if (!f) abort();
M_LET( (serial, f), m_serial_bin_write_t) {
vector_string_out_serial(serial, vstring);
}
fclose(f);
f = fopen("tmp-serial.dat", "rb");
if (!f) abort();
M_LET( (serial, f), m_serial_bin_read_t) {
vector_string_in_serial(vstring2, serial);
}
fclose(f);
if (vector_string_size(vstring2) != n) {
printf("Size are different!\n");
abort();
}
}
static void
bench_vector_string_json_run(size_t n)
{
if (vector_string_size(vstring) != n) {
printf("Size are different!\n");
abort();
}
FILE *f = fopen("tmp-serial.json", "wt");
if (!f) abort();
M_LET( (serial, f), m_serial_json_write_t) {
vector_string_out_serial(serial, vstring);
}
fclose(f);
f = fopen("tmp-serial.json", "rt");
if (!f) abort();
M_LET( (serial, f), m_serial_json_read_t) {
vector_string_in_serial(vstring2, serial);
}
fclose(f);
if (vector_string_size(vstring2) != n) {
printf("Size are different!\n");
abort();
}
}
static void
bench_vector_string_clear(void)
{
if (!vector_string_equal_p(vstring, vstring2)) {
printf("Array are different!\n");
abort();
}
vector_string_clear(vstring);
vector_string_clear(vstring2);
}
/********************************************************************************************/
ARRAY_DEF(vector_ulong, unsigned long)
vector_ulong_t vulong;
vector_ulong_t vulong2;
static void
bench_vector_ulong_init(size_t n)
{
vector_ulong_init(vulong);
for(size_t i = 0; i < n; i++)
{
vector_ulong_push_back(vulong, i*i);
}
vector_ulong_init(vulong2);
}
static void
bench_vector_ulong_bin_run(size_t n)
{
if (vector_ulong_size(vulong) != n) {
printf("Size are different!\n");
abort();
}
FILE *f = fopen("tmp-serial.dat", "wb");
if (!f) abort();
M_LET( (serial, f), m_serial_bin_write_t) {
vector_ulong_out_serial(serial, vulong);
}
fclose(f);
f = fopen("tmp-serial.dat", "rb");
if (!f) abort();
M_LET( (serial, f), m_serial_bin_read_t) {
vector_ulong_in_serial(vulong2, serial);
}
fclose(f);
if (vector_ulong_size(vulong2) != n) {
printf("Size are different!\n");
abort();
}
}
static void
bench_vector_ulong_json_run(size_t n)
{
if (vector_ulong_size(vulong) != n) {
printf("Size are different!\n");
abort();
}
FILE *f = fopen("tmp-serial.json", "wt");
if (!f) abort();
M_LET( (serial, f), m_serial_json_write_t) {
vector_ulong_out_serial(serial, vulong);
}
fclose(f);
f = fopen("tmp-serial.json", "rt");
if (!f) abort();
M_LET( (serial, f), m_serial_json_read_t) {
vector_ulong_in_serial(vulong2, serial);
}
fclose(f);
if (vector_ulong_size(vulong2) != n) {
printf("Size are different!\n");
abort();
}
}
static void
bench_vector_ulong_clear(void)
{
if (!vector_ulong_equal_p(vulong, vulong2)) {
printf("Array are different!\n");
abort();
}
vector_ulong_clear(vulong);
vector_ulong_clear(vulong2);
}
/********************************************************************************************/
const config_func_t table[] = {
{ 10, "List", 10000000, 0, test_list, 0},
{ 11, "DPList", 10000000, 0, test_dlist, 0},
{ 20, "Array", 100000000, 0, test_array, 0},
{ 21, "Deque", 100000000, 0, test_deque, 0},
{ 30, "Rbtree", 1000000, 0, test_rbtree, 0},
{ 31, "B+tree", 1000000, 0, test_bptree, 0},
{ 40, "dict", 1000000, 0, test_dict, 0},
@@ -861,7 +1074,13 @@ const config_func_t table[] = {
{ 65,"Queue Concurrent", 1000000, 0, test_queue_concurrent, 0},
{ 66,"Queue SPSC(Bulk)", 1000000, 0, test_queue_single_bulk, 0},
{ 70,"M_HASH", 100000000, test_hash_prepare, test_hash, test_hash_final},
{ 71,"Core Hash", 100000000, test_hash_prepare, test_core_hash, test_hash_final}
{ 71,"Core Hash", 100000000, test_hash_prepare, test_core_hash, test_hash_final},
{100, "serial-bin STR", 10000000, bench_vector_string_init, bench_vector_string_bin_run, bench_vector_string_clear},
{101, "serial-bin STR.big", 10000000, bench_vector_string_init_big, bench_vector_string_bin_run, bench_vector_string_clear},
{102, "serial-bin INT", 10000000, bench_vector_ulong_init, bench_vector_ulong_bin_run, bench_vector_ulong_clear},
{110, "serial-json STR", 10000000, bench_vector_string_init, bench_vector_string_json_run, bench_vector_string_clear},
{111, "serial-json STR.big", 10000000, bench_vector_string_init_big, bench_vector_string_json_run, bench_vector_string_clear},
{112, "serial-json INT", 10000000, bench_vector_ulong_init, bench_vector_ulong_json_run, bench_vector_ulong_clear}
};
int main(int argc, const char *argv[])
+185
View File
@@ -0,0 +1,185 @@
#define NDEBUG
#define RAPIDJSON_HAS_STDSTRING 1
#include "rapidjson/reader.h"
#include "rapidjson/document.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/filereadstream.h"
#include "rapidjson/filewritestream.h"
#include "rapidjson/encodedstream.h"
#include "rapidjson/error/en.h"
#include <stdio.h>
#include <string>
#include <vector>
#include "common.h"
using namespace std;
/********************************************************************************************/
vector<string> vstring;
vector<string> vstring2;
static void
bench_vector_string_init(size_t n)
{
for(size_t i = 0; i < n; i++)
{
char buff[100];
snprintf(buff, sizeof(buff), "%zu", i);
std::string s(buff);
vstring.push_back(s);
}
}
static void
bench_vector_string_init_big(size_t n)
{
for(size_t i = 0; i < n; i++)
{
char buff[100];
snprintf(buff, sizeof(buff), "%zu%zu%zu%zu%zu%zu", i, i, i, i, i, i);
std::string s(buff);
vstring.push_back(s);
}
}
static void
bench_vector_string_json_run(size_t n)
{
if (vstring.size() != n) {
printf("Size are different!\n");
abort();
}
FILE *f = fopen("tmp-serial.json", "wt");
if (!f) abort();
{
// Prepare writer and output stream.
char writeBuffer[65536];
typedef rapidjson::AutoUTFOutputStream<unsigned, rapidjson::FileWriteStream> OutputStream;
rapidjson::FileWriteStream os(f, writeBuffer, sizeof(writeBuffer));
OutputStream eos(os, rapidjson::kUTF8, false);
rapidjson::PrettyWriter<OutputStream, rapidjson::UTF8<>, rapidjson::AutoUTF<unsigned> > writer(eos);
writer.StartArray();
for(size_t i = 0; i < n; i++){
writer.String(vstring[i]);
}
writer.EndArray();
}
fclose(f);
f = fopen("tmp-serial.json", "rt");
if (!f) abort();
{
char readBuffer[65536];
rapidjson::FileReadStream is(f, readBuffer, sizeof(readBuffer));
rapidjson::Document d;
d.ParseStream(is);
for(size_t i = 0; i < d.Size(); i++) {
rapidjson::Value& s = d[i];
vstring2.push_back(s.GetString());
}
}
fclose(f);
if (vstring2.size() != n) {
printf("Size are different!\n");
abort();
}
}
static void
bench_vector_string_clear(void)
{
if (vstring != vstring2) {
printf("Array are different!\n");
abort();
}
}
/********************************************************************************************/
vector<unsigned long> vulong;
vector<unsigned long> vulong2;
static void
bench_vector_ulong_init(size_t n)
{
for(size_t i = 0; i < n; i++)
{
vulong.push_back(i*i);
}
}
static void
bench_vector_ulong_json_run(size_t n)
{
if (vulong.size() != n) {
printf("Size are different!\n");
abort();
}
FILE *f = fopen("tmp-serial.json", "wt");
if (!f) abort();
{
// Prepare writer and output stream.
char writeBuffer[65536];
typedef rapidjson::AutoUTFOutputStream<unsigned, rapidjson::FileWriteStream> OutputStream;
rapidjson::FileWriteStream os(f, writeBuffer, sizeof(writeBuffer));
OutputStream eos(os, rapidjson::kUTF8, false);
rapidjson::PrettyWriter<OutputStream, rapidjson::UTF8<>, rapidjson::AutoUTF<unsigned> > writer(eos);
writer.StartArray();
for(size_t i = 0; i < n; i++){
writer.Int64(vulong[i]);
}
writer.EndArray();
}
fclose(f);
f = fopen("tmp-serial.json", "rt");
if (!f) abort();
{
char readBuffer[65536];
rapidjson::FileReadStream is(f, readBuffer, sizeof(readBuffer));
rapidjson::Document d;
d.ParseStream(is);
for(size_t i = 0; i < d.Size(); i++) {
rapidjson::Value& s = d[i];
vulong2.push_back(s.GetInt64());
}
}
fclose(f);
if (vulong2.size() != n) {
printf("Size are different!\n");
abort();
}
}
static void
bench_vector_ulong_clear(void)
{
if (vulong != vulong2) {
printf("Array are different!\n");
abort();
}
}
/********************************************************************************************/
const config_func_t table[] = {
{110, "serial-json STR", 10000000, bench_vector_string_init, bench_vector_string_json_run, bench_vector_string_clear},
{111, "serial-json STR.big", 10000000, bench_vector_string_init_big, bench_vector_string_json_run, bench_vector_string_clear},
{112, "serial-json INT", 10000000, bench_vector_ulong_init, bench_vector_ulong_json_run, bench_vector_ulong_clear}
};
int main(int argc, const char *argv[])
{
test("RAPIDJSON", numberof(table), table, argc, argv);
exit(0);
}
+96
View File
@@ -0,0 +1,96 @@
#define NDEBUG
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <rigtorp/MPMCQueue.h>
#include "common.h"
/********************************************************************************************/
rigtorp::MPMCQueue<unsigned int> g_buff(4*64);
rigtorp::MPMCQueue<unsigned long long> g_final(4*64);
static void final(void *arg)
{
size_t *p_n = (size_t*) arg;
size_t n = *p_n;
unsigned long long j, s = 0;
for(unsigned int i = 0; i < n;i++) {
g_final.pop(j);
s += j;
}
g_result = s;
}
static void conso(void *arg)
{
unsigned int j;
size_t *p_n = (size_t*)arg;
size_t n = *p_n;
unsigned long long s = 0;
for(unsigned int i = 0; i < n;i++) {
g_buff.pop(j);
s += j;
}
g_final.push(s);
}
static void prod(void *arg)
{
size_t *p_n = (size_t*)arg;
size_t n = *p_n;
size_t r = n;
for(unsigned int i = 0; i < n;i++) {
g_buff.push(r);
r = r * 31421U + 6927U;
}
}
static void test_queue(size_t n)
{
const int cpu_count = get_cpu_count();
const int prod_count = cpu_count/2;
const int conso_count = cpu_count - prod_count;
if (cpu_count < 2) {
fprintf(stderr, "WARNING: Can not measure Buffer performance.\n");
return;
}
rand_get();
// Create thread
m_thread_t idx_p[prod_count];
m_thread_t idx_c[conso_count];
m_thread_t idx_final;
for(int i = 0; i < prod_count; i++) {
m_thread_create (idx_p[i], prod, &n);
}
for(int i = 0; i < conso_count; i++) {
m_thread_create (idx_c[i], conso, &n);
}
size_t n2 = conso_count;
m_thread_create(idx_final, final, &n2);
// Wait for jobs to be done.
for(int i = 0; i < prod_count; i++) {
m_thread_join(idx_p[i]);
}
for(int i = 0; i < conso_count; i++) {
m_thread_join(idx_c[i]);
}
m_thread_join(idx_final);
}
/********************************************************************************************/
const config_func_t table[] = {
{ 60, "Queue MPMC", 1000000, 0, test_queue, 0}
};
int main(int argc, const char *argv[])
{
test("RIGTORP-MPMC-QUEUE", numberof(table), table, argc, argv);
exit(0);
}
+19
View File
@@ -1,6 +1,7 @@
#define NDEBUG
#include <vector>
#include <deque>
#include <list>
#include <iterator>
#include <map>
@@ -53,6 +54,23 @@ static void test_array(size_t n)
/********************************************************************************************/
static void test_deque(size_t n)
{
deque<unsigned int> a1, a2;
for(size_t i = 0; i < n; i++) {
a1.push_back(rand_get() );
a2.push_back(rand_get() );
}
unsigned int s = 0;
for(auto it1 = a1.cbegin(), it2 = a2.cbegin();
it1 != a1.cend() ;it1++, it2++) {
s += *it1 * *it2;
}
g_result = s;
}
/********************************************************************************************/
static void test_rbtree(size_t n)
{
set<unsigned long> tree;
@@ -241,6 +259,7 @@ static void test_stable_sort(size_t n)
const config_func_t table[] = {
{ 10, "List", 10000000, 0, test_list, 0},
{ 20, "Array", 100000000, 0, test_array, 0},
{ 21, "Deque", 100000000, 0, test_deque, 0},
{ 30, "Rbtree", 1000000, 0, test_rbtree, 0},
{ 40, "dict(m)", 1000000, 0, test_dict1, 0},
{ 41, "dictBig", 1000000, 0, test_dict_big, 0},
+46 -126
View File
@@ -1,7 +1,7 @@
/*
* M*LIB - String Bench
*
* Copyright (c) 2017-2019, Patrick Pelissier
* Copyright (c) 2017-2021, Patrick Pelissier
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
@@ -37,10 +37,6 @@ extern "C" {
};
#endif
#ifdef BENCH_CAN_USE_RAPIDSTRING
#include "rapidstring.h"
#endif
#ifdef BENCH_CAN_USE_BSTRLIB
#include "bstrlib.h"
#include "bstrwrap.h"
@@ -77,6 +73,17 @@ void random_permutation(unsigned n)
using namespace std;
static void replace_all_stl(string &str, const char pattern[], const char replace[])
{
size_t pos = 0;
do {
pos = str.find(pattern, pos);
if (pos != string::npos) {
str.replace (pos, strlen(pattern), replace);
}
} while (pos != string::npos);
}
size_t bench_stl(unsigned n)
{
vector<string> tab;
@@ -89,21 +96,8 @@ size_t bench_stl(unsigned n)
str += tab[permutation_tab[i]];
}
size_t pos = 0;
do {
pos = str.find("1234", pos);
if (pos != string::npos) {
str.replace (pos, 4, "WELL");
}
} while (pos != string::npos);
pos = 0;
do {
pos = str.find("56789", pos);
if (pos != string::npos) {
str.replace (pos, 5, "DONE");
}
} while (pos != string::npos);
replace_all_stl(str, "1234", "WELL");
replace_all_stl(str, "56789", "DONE");
return str.length();
}
@@ -124,15 +118,8 @@ size_t bench_mlib(unsigned n)
string_cat(str, tab[permutation_tab[i]]);
}
// P3
size_t i = 0;
do {
i = string_replace_str(str, "1234", "WELL", i);
} while (i != STRING_FAILURE);
// P4
i = 0;
do {
i = string_replace_str(str, "56789", "DONE", i);
} while (i != STRING_FAILURE);
string_replace_all_str(str, "1234", "WELL");
string_replace_all_str(str, "56789", "DONE");
size_t length = string_size(str);
// Clean
string_clear(str);
@@ -145,6 +132,18 @@ size_t bench_mlib(unsigned n)
#ifdef BENCH_CAN_USE_BSTRLIB
static void replace_all_bstrlib(CBString &str, const char pattern[], const char replace[])
{
size_t pos = 0;
do {
pos = str.find(pattern, pos);
if (pos != string::npos) {
str.replace (pos, strlen(pattern), replace);
}
} while (pos != string::npos);
}
size_t bench_bstrlib(unsigned n)
{
vector<CBString> tab;
@@ -160,21 +159,8 @@ size_t bench_bstrlib(unsigned n)
str += tab[permutation_tab[i]];
}
size_t pos = 0;
do {
pos = str.find("1234", pos);
if (pos != string::npos) {
str.replace (pos, 4, "WELL");
}
} while (pos != string::npos);
pos = 0;
do {
pos = str.find("56789", pos);
if (pos != string::npos) {
str.replace (pos, 5, "DONE");
}
} while (pos != string::npos);
replace_all_bstrlib(str, "1234", "WELL");
replace_all_bstrlib(str, "56789", "DONE");
return str.length();
}
@@ -191,6 +177,19 @@ sds SDS_replace_at(sds str, size_t pos, size_t len, const char str2[])
return a;
}
sds replace_all_sds(sds str, const char pattern[], const char replace[])
{
size_t pos = 0;
do {
char *p = strstr(&str[pos], pattern);
pos = p == NULL ? -1U : (p - str);
if (pos != -1U) {
str = SDS_replace_at(str, pos, strlen(pattern), replace);
}
} while (pos != -1U);
return str;
}
size_t bench_sds(unsigned n)
{
sds *tab = (sds*) malloc (n * sizeof (sds));
@@ -205,25 +204,10 @@ size_t bench_sds(unsigned n)
str = sdscat(str, tab[permutation_tab[i]]);
}
// P3
size_t pos = 0;
do {
char *p = strstr(&str[pos], "1234");
pos = p == NULL ? -1U : (p - str);
if (pos != -1U) {
str = SDS_replace_at(str, pos, 4, "WELL");
}
} while (pos != -1U);
// P4
pos = 0;
do {
char *p = strstr(&str[pos], "56789");
pos = p == NULL ? -1U : (p - str);
if (pos != -1U) {
str = SDS_replace_at(str, pos, 5, "DONE");
}
} while (pos != -1U);
size_t length = sdslen(str);
str = replace_all_sds(str, "1234", "WELL");
str = replace_all_sds(str, "56789", "DONE");
// Clean
size_t length = sdslen(str);
sdsfree(str);
for(unsigned i = 0; i < n; i++) {
sdsfree(tab[i]);
@@ -233,63 +217,6 @@ size_t bench_sds(unsigned n)
}
#endif
#ifdef BENCH_CAN_USE_RAPIDSTRING
void RAPIDSTRING_replace_at(rapidstring *str, size_t pos, size_t len, const char str2[])
{
// simple implementation as replace is not available
rapidstring a;
rs_init_w_n(&a, rs_data(str), pos);
rs_cat(&a, str2);
rs_cat(&a, &rs_data(str)[pos+len] );
rs_free(str);
*str = a;
}
size_t bench_rapidstring(unsigned n)
{
rapidstring *tab = (rapidstring*) malloc (n * sizeof (rapidstring));
assert (tab != 0);
// P1
for(unsigned i = 0; i < n; i++) {
char tmp[10];
sprintf(tmp, "%u", rand_get());
rs_init_w(&tab[i], tmp);
}
// P2
rapidstring str;
rs_init(&str);
for(unsigned i = 0; i < n; i++) {
rs_cat_rs(&str, &tab[permutation_tab[i]]);
}
// P3
size_t pos = 0;
do {
char *p = strstr(&rs_data(&str)[pos], "1234");
pos = p == NULL ? -1U : (p - rs_data(&str));
if (pos != -1U) {
RAPIDSTRING_replace_at(&str, pos, 4, "WELL");
}
} while (pos != -1U);
// P4
pos = 0;
do {
char *p = strstr(&rs_data(&str)[pos], "56789");
pos = p == NULL ? -1U : (p - rs_data(&str));
if (pos != -1U) {
RAPIDSTRING_replace_at(&str, pos, 5, "DONE");
}
} while (pos != -1U);
size_t length = rs_len(&str);
// Clean
rs_free(&str);
for(unsigned i = 0; i < n; i++) {
rs_free(&tab[i]);
}
free(tab);
return length;
}
#endif
int main(int argc, const char *argv[])
{
@@ -315,12 +242,6 @@ int main(int argc, const char *argv[])
name = "SDS";
break;
#endif
#ifdef BENCH_CAN_USE_RAPIDSTRING
case 3:
length = bench_rapidstring(n);
name = "RAPID";
break;
#endif
#ifdef BENCH_CAN_USE_BSTRLIB
case 4:
length = bench_bstrlib(n);
@@ -335,4 +256,3 @@ int main(int argc, const char *argv[])
return 0;
}
+2 -153
View File
@@ -35,8 +35,8 @@
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* Update of integrating M*LIB, LIBSRT, SDS, RAPIDSTRING & GLIB
Copyright (c) 2018-2019 Patrick Pelissier
/* Update of integrating M*LIB, LIBSRT, SDS & GLIB
Copyright (c) 2018-2021 Patrick Pelissier
*/
/*
@@ -79,11 +79,6 @@ extern "C" {
#include <string>
#endif
#if defined (BENCH_CAN_USE_RAPIDSTRING)
#include "rapidstring.h"
#endif
#if defined(BENCH_CAN_USE_GLIB)
#include "gmodule.h"
#endif
@@ -682,121 +677,6 @@ int testSDS_replace (int count) {
#endif
#ifdef BENCH_CAN_USE_RAPIDSTRING
int testRAPIDSTRING_emptyCtor (int count) {
int i, c = 0;
for (c=i=0; i < count; i++) {
rapidstring b;
rs_init(&b);
BARRIER(&b);
c += rs_len(&b) ^i;
rs_free(&b);
}
return c;
}
int testRAPIDSTRING_nonemptyCtor (int count) {
int i, c = 0;
for (c=i=0; i < count; i++) {
rapidstring b;
rs_init_w(&b, TESTSTRING1);
BARRIER(&b);
c += rs_len(&b) ^i;
rs_free(&b);
}
return c;
}
int testRAPIDSTRING_smallnonemptyCtor (int count) {
int i, c = 0;
for (c=i=0; i < count; i++) {
rapidstring b;
rs_init_w(&b, SMALLTESTSTRING1);
BARRIER(&b);
c += rs_len(&b) ^i;
rs_free(&b);
}
return c;
}
int testRAPIDSTRING_cstrAssignment (int count) {
int i, c = 0;
rapidstring b;
rs_init(&b);
for (c=i=0; i < count; i++) {
rs_cpy(&b, TESTSTRING1);
BARRIER(&b);
c += rs_len(&b) ^i;
}
rs_free(&b);
return c;
}
int testRAPIDSTRING_extraction (int count) {
int i, c = 0;
rapidstring b;
rs_init_w(&b, TESTSTRING1);
for (c=i=0; i < count; i++) {
c += rs_data_c(&b)[i & 7];
c += rs_data_c(&b)[(i & 7) ^ 8];
c += rs_data_c(&b)[(i & 7) ^ 4] ^i;
BARRIER(&b);
}
rs_free(&b);
return c;
}
int testRAPIDSTRING_concat (int count) {
int i, j, c = 0;
rapidstring a, accum;
rs_init_w(&a, TESTSTRING1);
rs_init (&accum);
for (j=0; j < count; j++) {
rs_cpy(&accum, "");
for (i=0; i < 250; i++) {
rs_cat_rs(&accum, &a);
rs_cat(&accum, "!!");
BARRIER(&accum);
c += rs_len(&accum) ^i;
}
}
rs_free(&a);
rs_free(&accum);
return c;
}
void RAPIDSTRING_replace_at(rapidstring *str, size_t pos, size_t len, const char str2[])
{
// simple implementation as replace is not available
rapidstring a;
rs_init_w_n(&a, rs_data(str), pos);
rs_cat(&a, str2);
rs_cat(&a, &rs_data(str)[pos+len] );
rs_free(str);
*str = a;
}
int testRAPIDSTRING_replace (int count) {
int j, c = 0;
rapidstring a;
rs_init_w(&a, TESTSTRING1);
for (j=0; j < count; j++) {
RAPIDSTRING_replace_at(&a, 11, 4, "XXXXXX");
RAPIDSTRING_replace_at(&a, 23, 2, "XXXXXX");
RAPIDSTRING_replace_at(&a, 4, 8, "XX");
BARRIER(&a);
c += rs_len(&a) ^j;
}
rs_free(&a);
return c;
}
#endif
#ifdef BENCH_CAN_USE_GLIB
int testGLIB_emptyCtor (int count) {
@@ -1088,37 +968,6 @@ int benchTest (const struct flags * runflags) {
}
#endif
#ifdef BENCH_CAN_USE_RAPIDSTRING
if (runflags->runtest[0]) {
c += timeTest (cps, testRAPIDSTRING_emptyCtor, 100000);
print ("RAPIDSTRING", "empty constructor", cps);
}
if (runflags->runtest[1]) {
c += timeTest (cps, testRAPIDSTRING_nonemptyCtor, 100000);
print ("RAPIDSTRING", "non-empty constructor", cps);
}
if (runflags->runtest[2]) {
c += timeTest (cps, testRAPIDSTRING_smallnonemptyCtor, 100000);
print ("RAPIDSTRING", "small non-empty constructor", cps);
}
if (runflags->runtest[3]) {
c += timeTest (cps, testRAPIDSTRING_cstrAssignment, 100000);
print ("RAPIDSTRING", "char * assignment", cps);
}
if (runflags->runtest[4]) {
c += timeTest (cps, testRAPIDSTRING_extraction, 100000);
print ("RAPIDSTRING", "char extraction", cps);
}
if (runflags->runtest[6]) {
c += timeTest (cps, testRAPIDSTRING_concat, 10);
print ("RAPIDSTRING", "concatenation", cps * 250);
}
if (runflags->runtest[7]) {
c += timeTest (cps, testRAPIDSTRING_replace, 10);
print ("RAPIDSTRING", "replace", cps);
}
#endif
#ifdef BENCH_CAN_USE_GLIB
if (runflags->runtest[0]) {
c += timeTest (cps, testGLIB_emptyCtor, 100000);
+2 -2
View File
@@ -1,4 +1,5 @@
#define NDEBUG
#define _GNU_SOURCE
#include <stdlib.h>
#include <stdio.h>
@@ -202,9 +203,8 @@ static void test_sort(size_t n)
const config_func_t table[] = {
{ 10, "List", 10000000, 0, test_list, 0},
{ 20, "Array", 100000000, 0, test_array, 0},
{ 30, "Rbtree", 1000000, 0, test_rbtree, 0},
{ 40, "dict", 1000000, 0, test_dict, 0},
{ 41, "dictBig", 1000000, 0, test_dict_big, 0}
{ 41, "dictBig", 1000000, 0, test_dict_big, 0},
{ 50, "sort", 10000000, 0, test_sort, 0}
};
+123 -15
View File
@@ -1,7 +1,7 @@
/*
* M*LIB - common functions for bench module
*
* Copyright (c) 2017-2019, Patrick Pelissier
* Copyright (c) 2017-2021, Patrick Pelissier
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
@@ -26,6 +26,9 @@
#include <string.h>
#include "common.h"
// Maximum supported value for repeat argument
#define MAX_REPEAT 10000
// The global result
unsigned long g_result;
@@ -46,8 +49,9 @@ void compiler_barrier(void *p)
struct parse_opt_s {
int test_function;
double from, to, step, grow;
double within;
unsigned repeat;
bool graph, best, average, quiet;
bool graph, best, best_within, average, quiet;
};
static void
@@ -62,9 +66,11 @@ parse_config(struct parse_opt_s *opt, int argc, const char *argv[])
opt->grow = 1.1;
opt->graph = false;
opt->best = false;
opt->best_within = false;
opt->average = false;
opt->quiet = false;
opt->repeat = 1;
opt->within = .05;
for(int i = 1; i < argc ; i++)
{
@@ -88,14 +94,23 @@ parse_config(struct parse_opt_s *opt, int argc, const char *argv[])
} else if (strcmp(argv[i], "--repeat") == 0) {
i++;
opt->repeat = strtol(argv[i], &end, 10);
opt->repeat = (opt->repeat > MAX_REPEAT) ? MAX_REPEAT : opt->repeat;
} else if (strcmp(argv[i], "--graph") == 0) {
opt->graph = true;
} else if (strcmp(argv[i], "--best") == 0) {
opt->best = true;
opt->average = false;
opt->best_within = false;
} else if (strcmp(argv[i], "--best-within") == 0) {
opt->best_within = true;
opt->best = false;
opt->average = false;
i++;
opt->within = strtod(argv[i], &end) / 100.0;
} else if (strcmp(argv[i], "--average") == 0) {
opt->average = true;
opt->best = false;
opt->best_within = false;
} else if (strcmp(argv[i], "--quiet") == 0) {
opt->quiet = true;
} else {
@@ -131,14 +146,78 @@ select_config(int func, size_t n, const config_func_t functions[])
for(size_t i = 0; i < n;i++) {
fprintf(stderr, " %d: %s\n", functions[i].num, functions[i].funcname);
}
fprintf(stderr, "USAGE: FUNC_NUMBER [--from number --to number (--grow number | --step number)] [--best|--average] [--quiet|--graph]\n");
fprintf(stderr,
"USAGE: FUNC_NUMBER [--from number --to number (--grow number | --step number)] [--grapĥ]\n"
"[--repeat number] [--best|--average|--best-within] [--quiet]\n");
exit(-1);
}
// Utility function for qsort
static int cmp_double(const void *pa, const void *pb)
{
const double *a = (const double *) pa, *b = (const double *)pb;
return (*a < *b) ? -1 : *a > *b;
}
/* Get the longest sequence of values within 'f'% */
static int
get_sequence(int i, int n, double tab[], double f)
{
int j;
for(j = i + 1; j < n; j++) {
if (tab[j] > f * tab[i])
break;
}
return j-i;
}
/* Return the minimum of the longest sequence of values with 'f'% */
static double
get_best_within(int n, double tab[], double f)
{
qsort(tab, n, sizeof(double), cmp_double);
int best_i = 0;
int best_seq = get_sequence(0, n, tab, f);
for(int i = 1; i < n && (n-i) > best_seq ; i++) {
int seq = get_sequence(i, n, tab, f);
if (seq > best_seq) {
best_i = i;
best_seq = seq;
}
}
return tab[best_i];
}
// Integer sqrt function (to avoid depending on libm)
static unsigned integer_sqrt(unsigned n)
{
// Find greatest shift.
int shift = 2;
unsigned nShifted = n >> shift;
// We check for nShifted being n, since some implementations
// perform shift operations modulo the word size.
while (nShifted != 0 && nShifted != n){
shift += 2;
nShifted = n >> shift;
}
shift -= 2;
// Find digits of result.
unsigned result = 0;
while (shift >= 0) {
result = result << 1;
unsigned candidateResult = result + 1;
if (candidateResult*candidateResult <= n >> shift) {
result = candidateResult;
}
shift -= 2;
}
return result;
}
void
test(const char library[], size_t n, const config_func_t functions[], int argc, const char *argv[])
{
// options
// Init & parse arguments
// NUMBER
// --from NUMBER --to NUMBER --step NUMBER --grow NUMBER
// --graph --best --average --quiet
@@ -146,8 +225,10 @@ test(const char library[], size_t n, const config_func_t functions[], int argc,
struct parse_opt_s arg;
parse_config(&arg, argc, argv);
int i = select_config(arg.test_function, n, functions);
double from = arg.from == 0 ? functions[i].default_n : arg.from;
double to = arg.from == 0 ? functions[i].default_n : arg.to;
double from = (arg.from == 0) ? functions[i].default_n : arg.from;
double to = (arg.to == 0) ? functions[i].default_n : arg.to;
// Open plot file if needed
FILE *graph_file = NULL;
if (arg.graph) {
char filename[100];
@@ -159,32 +240,59 @@ test(const char library[], size_t n, const config_func_t functions[], int argc,
}
fprintf(graph_file, "# plotting %s-%d : %s\n# N T", library, arg.test_function, functions[i].funcname);
}
// Do the bench
for(double n = from; n <= to ; n = (arg.grow == 0 ? n + arg.step : n * arg.grow))
for(double n = from; n <= to ; n = ((arg.grow == 0) ? n + arg.step : n * arg.grow))
{
double best = (1.0/0.0);
double avg = 0.0;
double variance = 0.0;
static double measure[MAX_REPEAT];
double ba = 0.0;
if (functions[i].init != NULL)
functions[i].init(n);
// Measure the time of the test_function
for(unsigned r = 0; r < arg.repeat; r++) {
double t0 = test_function(arg.graph|arg.best|arg.average|arg.quiet ? NULL : functions[i].funcname, (size_t) n, functions[i].func);
best = t0 < best ? t0 : best;
double t0 = test_function( (arg.graph|arg.best|arg.average|arg.quiet) ? NULL : functions[i].funcname, (size_t) n, functions[i].func);
best = (t0 < best) ? t0 : best;
avg += t0;
variance += t0 * t0;
measure[r] = t0;
}
// Closure of the tests
if (functions[i].clear != NULL)
functions[i].clear();
avg /= arg.repeat;
// Finish computing the different times
if (arg.repeat > 1) {
avg /= arg.repeat;
variance = (variance - arg.repeat * avg * avg) / (arg.repeat - 1);
ba = get_best_within(arg.repeat, measure, 1. + arg.within);
}
// The average value shall be around best_within (and greater)
// otherwise the result doesn't seem reliable.
bool reliable = (ba <= avg && ba * (1.0+arg.within/2) + 0.5 > avg);
// Print the result
if (arg.graph) {
fprintf(graph_file, "%f %f\n", n, arg.average ? avg : best);
fprintf(graph_file, "%f %f\n", n, arg.average ? avg : arg.best ? best : ba);
} else if (arg.quiet) {
printf("%lu\n", (unsigned long)(arg.average ? avg : best));
printf("%ld\n", (long)(arg.average ? avg : arg.best ? best : reliable ? ba : -1));
} else if (arg.repeat > 1) {
if (arg.average == false)
if (arg.average == false && arg.best_within == false)
printf ("%20.20s time %lu ms for n = %lu *** BEST ***\n", functions[i].funcname, (unsigned long) best, (unsigned long) n);
if (arg.best == false)
printf ("%20.20s time %lu ms for n = %lu *** AVERAGE ***\n", functions[i].funcname, (unsigned long) avg, (unsigned long) n);
if (arg.best == false && arg.best_within == false)
printf ("%20.20s time %lu ms +/- %u ms for n = %lu *** AVERAGE ***\n", functions[i].funcname, (unsigned long) avg, 2*integer_sqrt(variance), (unsigned long) n);
if (arg.best == false && arg.average == false)
printf ("%20.20s time %lu ms for n = %lu *** BEST within %d%% *** %s\n", functions[i].funcname, (unsigned long) ba, (unsigned long) n, (int)(100*arg.within), reliable ? "" : "(unreliable result)");
}
}
// Close the FILE if needed
if (arg.graph) {
fclose(graph_file);
printf("File plot-%s-%d.dat generated.\n"
+1 -1
View File
@@ -1,7 +1,7 @@
/*
* M*LIB - common functions for bench module
*
* Copyright (c) 2017-2019, Patrick Pelissier
* Copyright (c) 2017-2021, Patrick Pelissier
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
+1 -1
View File
@@ -1,7 +1,7 @@
/*
* MLIB - TEST module
*
* Copyright (c) 2017-2019, Patrick Pelissier
* Copyright (c) 2017-2021, Patrick Pelissier
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
+1 -2
View File
@@ -35,10 +35,9 @@ static inline size_t my_hash(uint64_t key)
{
return ((key) ^ (key)>>7);
}
static inline void update_val(uint32_t *p, uint32_t v) { *p += v;}
DICT_OA_DEF2(dict_oligonucleotide,
uint64_t, M_OPEXTEND(M_DEFAULT_OPLIST, HASH(my_hash), OOR_EQUAL(my_oor_equal_p), OOR_SET(my_oor_set M_IPTR)),
uint32_t, M_OPEXTEND(M_DEFAULT_OPLIST, UPDATE(update_val M_IPTR)))
uint32_t, M_DEFAULT_OPLIST)
#define M_OPL_dict_oligonucleotide_t() DICT_OPLIST(dict_oligonucleotide, M_OPEXTEND(M_DEFAULT_OPLIST, HASH(my_hash), OOR_EQUAL(my_oor_equal_p), OOR_SET(my_oor_set M_IPTR)), M_DEFAULT_OPLIST)
// Define a B*TREE-21 of uint32_t --> uint64_t and register its oplist
+2 -7
View File
@@ -1,8 +1,3 @@
#ifndef NDEBUG
#define NDEBUG
#endif
#undef NDEBUG
#include <string.h>
#include "benchmark.h"
@@ -48,7 +43,7 @@ int test_int(int N, const unsigned *data)
if (dict_int_get (h, data[i]) == NULL) {
dict_int_set_at (h, data[i], i);
} else {
dict_int_remove(h, data[i]);
dict_int_erase(h, data[i]);
}
}
ret = (int)dict_int_size(h);
@@ -64,7 +59,7 @@ int test_str(int N, char * const *data)
if (dict_str_get (h, data[i]) == NULL) {
dict_str_set_at (h, data[i], i);
} else {
dict_str_remove(h, data[i]);
dict_str_erase(h, data[i]);
}
}
ret = (int)dict_str_size(h);
+4 -4
View File
@@ -4,10 +4,10 @@
#include "m-dict.h"
#include "m-mempool.h"
DICT_DEF2(dict_int,
DICT_STOREHASH_DEF2(dict_int,
int, M_OPEXTEND(M_DEFAULT_OPLIST, MEMPOOL(mpool_int), MEMPOOL_LINKAGE(static)),
int, M_DEFAULT_OPLIST)
DICT_DEF2(dict_str,
DICT_STOREHASH_DEF2(dict_str,
const char *, M_OPEXTEND (M_CSTR_OPLIST, MEMPOOL(mpool_str), MEMPOOL_LINKAGE(static)),
int, M_DEFAULT_OPLIST)
@@ -20,7 +20,7 @@ int test_int(int N, const unsigned *data)
if (dict_int_get (h, data[i]) == NULL) {
dict_int_set_at (h, data[i], i);
} else {
dict_int_remove(h, data[i]);
dict_int_erase(h, data[i]);
}
}
ret = (int)dict_int_size(h);
@@ -38,7 +38,7 @@ int test_str(int N, char * const *data)
if (dict_str_get (h, data[i]) == NULL) {
dict_str_set_at (h, data[i], i);
} else {
dict_str_remove(h, data[i]);
dict_str_erase(h, data[i]);
}
}
ret = (int)dict_str_size(h);
+8 -5
View File
@@ -1,4 +1,5 @@
#include "../common.c"
#define M_USE_DICT_OA_PROBING(s) 1
#include "m-dict.h"
static inline bool oor_equal_p(unsigned int k, unsigned char n)
@@ -11,10 +12,10 @@ static inline void oor_set(unsigned int *k, unsigned char n)
}
DICT_OA_DEF2(dict_oa_uint,
unsigned int, M_OPEXTEND(M_DEFAULT_OPLIST, OOR_EQUAL(oor_equal_p), OOR_SET(oor_set M_IPTR)),
unsigned int, M_OPEXTEND(M_DEFAULT_OPLIST, HASH(hash_fn), OOR_EQUAL(oor_equal_p), OOR_SET(oor_set M_IPTR)),
unsigned int, M_DEFAULT_OPLIST)
void test_int(uint32_t n, uint32_t x0)
uint32_t test_int(uint32_t n, uint32_t x0)
{
uint32_t i, x, z = 0;
dict_oa_uint_t h;
@@ -22,10 +23,12 @@ void test_int(uint32_t n, uint32_t x0)
for (i = 0, x = x0; i < n; ++i) {
x = hash32(x);
unsigned int key = get_key(n, x);
unsigned int *ptr = dict_oa_uint_get(h, key);
if (ptr) { (*ptr)++; z+= *ptr; }
else { dict_oa_uint_set_at(h, key, 1); z+=1; }
unsigned int *ptr = dict_oa_uint_get_at(h, key);
(*ptr)++;
z += *ptr;
}
fprintf(stderr, "# unique keys: %d; checksum: %u\n", (int) dict_oa_uint_size(h), z);
z = dict_oa_uint_size(h);
dict_oa_uint_clear(h);
return z;
}
+34
View File
@@ -38,4 +38,38 @@ V0.2.*: * worker_start takes a 'worker_t' as an additional parameter
V0.3.*: * Remove B+TREE _remove method as it has been deprecated (use _erase instead)
* Remove DICT _remove method as it has been deprecated (use _erase instead)
* Make _it_to_p method of B+TREE / RB-TREE as deprecated (uses _it_until_p instead ).
* Deprecated buffer options BUFFER_BLOCKING* and BUFFER_UNBLOCKING*
as the _push_blocking and _pop_blocking functions can do the same and are more versatil.
* Iteration over the items of a dictionnary/tree returns const iterators for access through
OPLIST (impact: algorithm & M_EACH) as the IT_REF operator is no longer exported.
The _it_ref method is still defined and can be used, so you can still modify the values
but it won't be automatically used anymore (as the keys CANNOT be modified).
(Previously it generates incorrect algorithm when used with m-dict).
V0.4.*: * The order of a list initialized using M_LET is reversed
to match what is done for ARRAY (and the C++ forward_list).
* Rename M_SKIP, M_KEEP & M_MID into M_SKIP_ARGS, M_KEEP_ARGS & M_MID_ARGS
due to conflict with glibc malloc.h (that defines M_KEEP for compatibility).
* Method write_string of m_serial expects a new argument (number of characters).
* Method _init_set2 of m-i-shared is removed.
* Operator _it_insert updates it_insertion iterator to reference the inserted element.
* Dereference Type of an iterator of a dict / B+Tree is suffixed by _itref_t instead of _type_t.
* Rename TUPLE _init_set2 in _init_emplace & _set2 in _emplace.
* Rename Priority Queue method _update_further in _update.
V0.5.*: * M_INVERT is renamed into M_REVERSE to be more coherent with the REVERSE operator.
M_INVERT is marked as obsolete.
* Remove _it_to_p method of B+TREE / RB-TREE as it has been deprecated.
* Remove ALGO_INIT_VA & M_ALG0_LET_INIT_VAI of m-algo as it has been deprecated (Use of M_LET instead).
* Some Internal name of user modifiable macros have been renamed to be properly
customizable by the user.
* Rename M_HASH_SEED into M_USE_HASH_SEED (as it is a user macro).
* M_LET: for initialization of variable with arguments, if there is only one argument,
it will default to use INIT_SET instead of INIT_WITH.
==> Encapsulate the argument between () to force use of INIT_WITH.
* Remove of UPDATE operator. Use of SET for RBTREE or ADD for DICT instead.
* Make the _clean suffix for reseting the container to empty deprecated. Use new _reset suffix instead.
* Make the _get_at suffix for always getting a value deprecated. Use new _safe_get suffix instead.
* Rename CLEAN operator in RESET operator.
* Rename GET_SET_KEY operator in SAFE_GET_KEY operator.
BIN
View File
Binary file not shown.
+70 -15
View File
@@ -17,17 +17,35 @@ How to make a release?
In case of problem, open a problem report.
List of tested systems
=======================
List of automatically tested systems
====================================
* gcc 4.9, 7 & 8 on linux/x86-64
* clang 3.5, 4 & 6 on linux/x86-64
* g++ 7 & 8 on linux/x86-64
* gcc on linux/x86-64 (32 bits and 64 bits)
* g++ on linux/x86-64 (32 bits and 64 bits)
* clang on macos/x86-64
* clang++ on macos/x86-64
* tcc on linux/x86-64
* gcc 7 on windows/x86-64
* gcc 4.9 on linux/powerpc
* gcc 6 on linux/armv7l
* clang 3.8 on linux/armv7l
* gcc on windows/x86-64 (mingw)
* msvc on windows/x86-64
* clang on windows/x86-64
List of manually tested systems
===============================
* clang on linux/x86-64
* clang on linux/armv7l
* gcc on linux/powerpc
* gcc on linux/armv7l
Atomic library
==============
For the targets armel, m68k, mips, mipsel, powerpc, powerpcspe or sh4,
you may need to run the test suite by adding the atomic library:
make check LDFLAGS="-pthread -latomic"
since 'atomic' library is not automatically included for 32 bits systems.
Cross compilation
@@ -35,7 +53,7 @@ Cross compilation
There is no need to cross compile the library as it is a header only library.
However if you want to run the test with a cross-compiler, do like the following
However if you want to run the tests with a cross-compiler, do like the following
command. It performs a cross-compilation of the test suite from linux to windows
and run the test suite with wine:
@@ -47,9 +65,8 @@ Handling issues
Issues are opened in the bug tracker of the project (typically https://github.com/P-p-H-d/mlib/issues )
If the issue cannot be closed and taken into account in less than (typically) one month,
or before a release,
it shall be moved into the long term issues included in the repository:
If the issue cannot be taken into account quickly and are long term,
it should be moved into the long term issues included in the repository:
https://github.com/P-p-H-d/mlib/blob/master/doc/ISSUES.org
This is a file in ORG mode: the issues are created with the proper tags.
@@ -65,7 +82,7 @@ its state shall be changed to DONE (the issue shall not be removed).
Debugging
===============
=========
Debugging the library can be quite difficult
as it performs heavy preprocessing expansion
@@ -76,7 +93,7 @@ Different strategy for debugging the library itself are still possible:
Add printf of interresting values in the debugged function.
2) Preprocess the library and then compile the preprocessed file:
2) Preprocess the library and then compile the preprocessed file like this:
cc -std=c99 -E test-file.c > test-file.i
perl -pi -e 's/;/;\n/g' test-file.i
@@ -99,3 +116,41 @@ Run the wave driver:
./wave ex-array01.c -I .. --c99 -t test.trace
The different expansion performed by the library are described in test.trace
Coding rules
============
* Use of non standard C shall be protected under a specific compiler test,
so that the library remains compatible with a strict C99 compiler.
* C11 features shall be optional.
* Use 'make format' to format the header files properly.
* External types shall be suffixed by _t and in lower case
but shall be optional if the user doesn't want then.
* Internal types shall be suffixed by _ct and in lower case
(as confidential types)
* External / Internal functions shall be in lower case.
* External / Internal macros shall be in upper case.
* Internal macros / functions shall be prefixed by m_<container>
with container is the name of the container with one letter transformed:
o --> 0
e --> 3
i --> 1
y --> 4
This prevents the automatic completion to work when the user starts writing its function.
* Test functions shall be predicated and be suffixed by '_p'
Misc
====
To put a breakpoint for the thread sanitizer in case of error, in gdb add:
$ set env TSAN_OPTIONS=halt_on_error=1,abort_on_error=1
+103 -45
View File
@@ -1,4 +1,3 @@
*Long term issues*
------------------
@@ -6,41 +5,104 @@
Specialize Hashmap for huge objects on supported hardware:
based on OA hash map of taggued pointer (needs space for tagging)
low bits = low bits of hash
Based on OA hash map with taggued pointer (needs space for tagging):
low bits = high bits of hash
pointer to object { key, hash, value }
Can detect collision without dereferencing object with 1/2^lowbits chances.
Reduce cache usage ==> Shall be faster.
Can solve collision without dereferencing object with 1/2^lowbits chances.
NB: hash may be uneeded due to the small chances of collision.
Reduce cache usage ==> Should be faster.
Increase cache usage for very small object (integer).
Use of pointer to avoid moving object on GC.
On AMD64, only 48 bits of 64 bits are really used for addressing data.
==> lowbits= 16
Empty representation= 0 (hash can be 0. pointer cannot be it).
Deleted representation = 1 (pointer cannot be zero)
<---- PTR ----><-HASH->
#+BEGIN_SRC C
#define LOW_BITS 16
#define ALIGNED_BITS 2
void *get_ptr(int64_t x) {
return (void*) ((x >> LOW_BITS) << ALIGNED_BITS);
}
unsigned get_small_hash(int64_t x) {
return x & ((1<<LOW_BITS)-1);
}
#+END_SRC
* TODO #25 : Support of error code model for error handling. :ENHANCEMENT:
Find a way to support error return code for the API in case of allocation
failure.
==> Any service that returns void shall return a "int".
==> In case of allocation failure, it shall return an error.
==> M_CALL macro shall stop its execution if the service returns an error code
Any service that returns void shall return a "int".
In case of allocation failure, it shall return an error.
M_CALL macro shall stop its execution if the service returns an error code
and the error code represents an error (avoid rewritting everything)
and throw back the error code (stopping the execution flow).
services returning already something shall not be modified.
Services returning already something shall not be modified.
This model should be applied at the container level only and not globally.
Different containers may need different levels of error handling.
4 combinaison to take into account:
New operator: ERROR_MODEL which value is 0 (abort on error), 1 (throw on error)
or 2 (return code on error).
==> ABORT on container / ABORT on used type: The current model
==> ABORT on container / RETCODE on used type: Needs to abort on reported error.
==> RETCODE on container / ABORT on used type: Nothing particular to note.
==> RETCODE on container / RETCODE on used type: Forward retcode to caller.
Find a way to make it while not making the code too complex
(try to keep as simple as possible).
Using a specialized oplist for such containers (_OPLIST_RETCODE)
using a specialized API for retcode:
* TODO #24 : Add MIN-MAX-HEAP container :ENHANCEMENT:
API_RET_*: that expands to
if (func(args) == 0) goto handler_exit_failure;
Adding at the end of each service:
M_END_FUNCTION(cleanup_code) that expands to different cases:
M_END_FUNCTION_VALUE(cleanup_code, return_success, return_failure) that expands to different cases:
ABORT/ABORT:
handler_exit_success:
handler_exit_failure:
return;
ABORT/RETCODE:
handler_exit_success:
return;
handler_exit_failure:
RAISE_FATAL_ERROR
RETCODE/ABORT
handler_exit_success:
return SUCESS;
handler_exit_failure:
cleanup_code
return FAILURE;
RETCODE/RETCODE
handler_exit_success:
return SUCESS;
handler_exit_failure:
cleanup_code
return FAILURE;
If really needed, the macro can be avoided and code can be hand written.
Open points:
- How to handle warnings on unused labels?
- What about M_LET/ M_EACH?
* TODO #24 : New: Add MIN-MAX-HEAP container :ENHANCEMENT:
See https://en.wikipedia.org/wiki/Min-max_heap
as DPRIORITY_QUEUE_DEF ?
@@ -48,7 +110,7 @@ as DPRIORITY_QUEUE_DEF ?
NOTE: Needs for such container?
* TODO #23: Force MOVE semantic :ENHANCEMENT:
* TODO #23: Strict MOVE semantic to clarify :ENHANCEMENT:
Some type may need to have a force MOVE semantic (for example, they can store
pointer to themselves). Currently the INIT_MOVE & MOVE operators are more
@@ -83,7 +145,7 @@ operators as it uses MOVE_DEFAULT which is not (fully compatible).
==> Analyse limitation and possible constraint usages.
* TODO #20: Bucket priority queue :ENHANCEMENT:
* TODO #20: New: Bucket priority queue :ENHANCEMENT:
Add a new kind of priority queue.
See https://en.wikipedia.org/wiki/Bucket_queue
@@ -100,7 +162,7 @@ Check if we can use BITSET, or introduce fixed size BITSET or use ad-hock
implementation.
* TODO #19: Intrusive Red Black Tree :ENHANCEMENT:
* TODO #19: New: Intrusive Red Black Tree :ENHANCEMENT:
Add intrusive red black tree.
Look also for AVL tree (NOTE: Is there a performance difference between the two?)
@@ -113,9 +175,9 @@ See the cells in yellow here:
http://htmlpreview.github.io/?https://github.com/P-p-H-d/mlib/blob/master/doc/Container.html
* TODO #17: Ressource handler :ENHANCEMENT:
* TODO #17: New: Ressource handler :ENHANCEMENT:
A ressouce handler which shall associated a unique handle to a ressource.
A global 'ressouce handler' which shall associated a unique handle to a ressource.
The handle shall be unique for the ressource and shall not be reused.
It is typically a 64 bits integers always incremented (even if the program
creates one billion ressources per second, the counter won't overflow
@@ -144,7 +206,7 @@ http://htmlpreview.github.io/?https://github.com/P-p-H-d/mlib/blob/master/doc/Co
* embedded the type in the ressource handler: more work, API more complex. Memory usage seems better.
* TODO #16: Lock Free List :ENHANCEMENT:
* TODO #16: New: Lock Free List :ENHANCEMENT:
Implement a lock free list. Most of the difficulty is the memory reclamation part.
Typically this lock free list shall be compatible with RCU method.
@@ -186,8 +248,9 @@ then unstack all to push instead the root object (which recursively remove them)
See also http://freetype.sourceforge.net/david/reliable-c.html#cseh
How to handle like allocation of the object?
How to avoid calling the destructor multiple times? (It is needed?)
- How to handle like allocation of the object?
- How to avoid calling the destructor multiple times? (It is needed?)
- How the code can be factorized with RETCODE needs?
* TODO #14: Memory allocation enhancement :ENHANCEMENT:
@@ -225,7 +288,7 @@ Needs some formal operator in the oplist to support it fully and an example.
It is a kind of object inheritance where the container inherits some extra data from its base.
* TODO #12: Atomic shared pointer :ENHANCEMENT:
* TODO #12: New: Atomic shared pointer :ENHANCEMENT:
Add an extension to the SHARED_PTR API:
@@ -301,11 +364,14 @@ Other implementation seems to have it hard to be lock-free: cf. https://github.c
* TODO #5: Concurrent dictionary Container :ENHANCEMENT:
* TODO #5: New: Concurrent dictionary Container :ENHANCEMENT:
Implement a more efficient dictionary than lock + std dictionary for all operations when dealing with threads.
See https://msdn.microsoft.com/en-us/library/dd287191(v=vs.110).aspx
The best parallel algorithm is still when there is as few synchronization as possible. A concurrent dictionary will fail at this and will result in average performance at best.
The typical best case will be in RCU context (a lot of readers, few writers), so the interface shall be compatible with such structure.
** Multiple locks within the dictionnary
A potential implementation may be to request at initialization time the number of concurrent thread N.
@@ -326,33 +392,25 @@ See also https://github.com/simonhf/sharedhashfile
** Lock Free dictionnary
Evaluate also lock-free dictionary (easier with open addressing).
It needs a complete rewrite of the inner loop through. The hard part is the dynamic resizing of the internal array (see http://preshing.com/20160222/a-resizable-concurrent-map/ for a potential solution and http://www.cs.toronto.edu/~tomhart/papers/tomhart_thesis.pdf for memory reclamation techniques). See also https://www.research.ibm.com/people/m/michael/spaa-2002.pdf
https://www.kernel.org/pub/linux/kernel/people/paulmck/perfbook/perfbook.2017.11.22a.pdf persents different techniques used by linux kernel.
It needs a complete rewrite of the inner loop through. The hard part is the dynamic resizing of the internal array.
Ssee http://preshing.com/20160222/a-resizable-concurrent-map/ for a potential solution
and http://www.cs.toronto.edu/~tomhart/papers/tomhart_thesis.pdf for memory reclamation techniques).
and https://www.research.ibm.com/people/m/michael/spaa-2002.pdf
https://www.kernel.org/pub/linux/kernel/people/paulmck/perfbook/perfbook.2017.11.22a.pdf presents different techniques used by linux kernel.
It needs before lock-free list: http://www.cse.yorku.ca/~ruppert/papers/lfll.pdf http://www.cse.yorku.ca/~ruppert/Mikhail.pdf
** Context
The best parallel algorithm is still when there is as few synchronization as possible. A concurrent dictionary will fail at this and will result in average performance at best.
The typical best case will be in RCU context (a lot of readers, few writers), so the interface shall be compatible with such structure.
** Linked list
Another solution is to create a huge list of items which is:
- atomically updated,
- in reverse order of the hash (bit 0 is highest bit, Bit 63 is the lowest bit).
Hash table will only give quick access to items to this list. Expanding the table won't change the order of the list (so the items will remain at the same place and always accessible by other threads) but just add sentinel in the sentinel at the right place (there won't be any reallocation of the list). Inserting will need to insert an item at the right place.
Not sure it will really help. To analyse.
Concurrent dictionary is possible now with CONCURRENT_DEF + DICT_DEF.
But it uses a global lock for all dictionary access.
** Open Addressing Indirect Table with a lock free node pool used as transaction pool.
A good way maybe Open Addessing table used only for indirection and a freelist memory reclamation container for handle the entries
(like a transaction).
Solution?
--------
Use of the concurrent pool (m-c-mempool) to allocate items.
The big table will only store pointers (+ part of hash in unused bits?) to such allocate items.
Atomic update is done by allocating a new node, update it, and atomicaly store it in the dict, putting the old one as logically deleted and to reclaim later.
(Other threads may still read its data so we cannot free immediatly).
* DONE #22: Enhanced services for SPSC Queue :ENHANCEMENT:
Add services:
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 99 KiB

After

Width:  |  Height:  |  Size: 102 KiB

BIN
View File
Binary file not shown.
+25 -2
View File
@@ -1,5 +1,27 @@
# Copyright (c) 2017-2021, Patrick Pelissier
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# + Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# + Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
CC=cc -std=c99
CFLAGS=-Wall -W -pedantic -Wshadow -Wpointer-arith -Wcast-qual -Wstrict-prototypes -Wmissing-prototypes -Wswitch-default -Wswitch-enum -Wcast-align -Wpointer-arith -Wbad-function-cast -Wstrict-overflow=5 -Wstrict-prototypes -Winline -Wundef -Wnested-externs -Wcast-qual -Wshadow -Wunreachable-code -Wlogical-op -Wstrict-aliasing=2 -Wredundant-decls -Wold-style-definition -Wno-unused-function
CFLAGS=-Wall -W -pedantic -Wshadow -Wpointer-arith -Wcast-qual -Wstrict-prototypes -Wmissing-prototypes -Wswitch-default -Wswitch-enum -Wcast-align -Wpointer-arith -Wbad-function-cast -Wstrict-overflow=5 -Wstrict-prototypes -Winline -Wundef -Wnested-externs -Wcast-qual -Wshadow -Wunreachable-code -Wlogical-op -Wstrict-aliasing=2 -Wredundant-decls -Wold-style-definition -Wno-unused-function -g
GMP_DIR=
CPPFLAGS=-I..
LDFLAGS=-pthread
@@ -12,11 +34,12 @@ RM=rm -f
all: config
$(MAKE) `ls ex-*.c|sed -e 's/\.c/\.exe/g'`
if test "$(CC)" = "cc -std=c99" ; then $(MAKE) `ls ex11-*.c|sed -e 's/\.c/\.exe/g'` CC="cc -std=c11" ; fi
config:
printf "#include <gmp.h>\nint main(void){mpz_t z; mpz_init(z); return 0;}\n" > config-test.c
$(CC) $(CFLAGS) $(CPPFLAGS) $(LDFLAGS) -I$(GMP_DIR)/include -L$(GMP_DIR)/lib -lgmp config-test.c -o config-test.exe 2> /dev/null && echo "-DHAVE_GMP=1 -I$(GMP_DIR)/include -L$(GMP_DIR)/lib -lgmp" > config || echo "-DHAVE_GMP=0" > config
$(RM) config-test.*
$(RM) config-test.c config-test.exe
clean:
$(RM) *.exe *.s *~ *.o ./a.dat config
+68
View File
@@ -0,0 +1,68 @@
#include <stdio.h>
#include "m-array.h"
#include "m-algo.h"
/* Define a dynamic array of int */
ARRAY_DEF(vector_int, int)
/* Register the oplist of this dynamic array globally */
#define M_OPL_vector_int_t() ARRAY_OPLIST(vector_int)
/* Define some standards algorithms on this dynamic array */
ALGO_DEF(vector_int, vector_int_t)
/* Define a dynamic array of bool */
ARRAY_DEF(vector_bool, bool, M_BOOL_OPLIST)
/* Register the oplist of this dynamic array globally */
#define M_OPL_vector_bool_t() ARRAY_OPLIST(vector_bool, M_BOOL_OPLIST)
/* Define some standards algorithms on this dynamic array */
ALGO_DEF(vector_bool, vector_bool_t)
/* ID function */
static bool id(bool x) { return x ; }
int main(void)
{
// Define, init (& later clear) myvector & tmp as vector_int_t
M_LET(myvector, tmp, vector_int_t) {
// Fill myvector with 3 int equal to 20
vector_int_fill_n(myvector, 3, 20);
// Fill tmp with 3 int equal to 33
vector_int_fill_n(tmp, 3, 33);
// Append all tmp in myvector
vector_int_splice(myvector, tmp);
// Fill tmp with 2 int equal to 10
vector_int_fill_n(tmp, 2, 10);
// Append all tmp in myvector
vector_int_splice(myvector, tmp);
// Display the result
printf("myvector contains:");
// In C11, the for loop can be simplified as :
#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L)
ALGO_FOR_EACH(myvector, vector_int_t, M_PRINT, " ");
#else
for M_EACH(it, myvector, vector_int_t) {
printf(" %d", *it);
}
#endif
printf("\n");
}
// Same thing but with booleans
M_LET(myvector, tmp, vector_bool_t) {
vector_bool_fill_n(myvector, 3, false);
vector_bool_fill_n(tmp, 3, true);
vector_bool_splice(myvector, tmp);
vector_bool_fill_n(tmp, 2, false);
vector_bool_splice(myvector, tmp);
printf("myvector contains:");
for M_EACH(it, myvector, vector_bool_t) {
printf(" %d", (int)*it);
}
printf("\n");
printf ("ALL: %d ANY: %d NONE: %d\n",
vector_bool_all_of_p(myvector, id),
vector_bool_any_of_p(myvector, id),
vector_bool_none_of_p(myvector, id) );
}
return 0;
}
+42
View File
@@ -0,0 +1,42 @@
#include "m-dict.h"
#include "m-array.h"
#include "m-algo.h"
#include "m-string.h"
/* Define a dictionnary (or hash_map or undordered_map)
* from a string_t to int */
DICT_DEF2(dict, string_t, int)
/* Register the oplist of this dictionnary globally */
#define M_OPL_dict_t() DICT_OPLIST(dict, STRING_OPLIST, M_DEFAULT_OPLIST)
/* Define an array of integer */
ARRAY_DEF(vector_int, int)
/* Register the oplist of this array of integer globally */
#define M_OPL_vector_int_t() ARRAY_OPLIST(vector_int)
/* Micro macro to detect if a string starts with the given pattern */
#define start_with(pattern, item) \
string_start_with_str_p((item).key, (pattern))
/* Micro macro to get the value of a pair of (key, value) */
#define get_value(out, item) ((out) = (item).value)
int main(void)
{
int s;
// Init keys as a vector_int_t, initialize it (and prepare its destruction)
M_LET(keys, vector_int_t)
// Initialize m as a dictionnary and initialize it with the given database
// Initialize tmp as a dictionanry
M_LET( (m, (STRING_CTE("foo"), 1), (STRING_CTE("bar"), 42), (STRING_CTE("bluez"), 7), (STRING_CTE("stop"), 789) ), tmp, dict_t) {
/* Extract all elements of 'm' that starts with 'b' */
ALGO_EXTRACT(tmp, dict_t, m, dict_t, start_with, "b");
/* Extract the values of theses elements */
ALGO_TRANSFORM(keys, vector_int_t, tmp, dict_t, get_value);
/* Sum theses values */
ALGO_REDUCE(s, keys, vector_int_t, sum);
printf("Sum of elements starting with 'b' is: %d\n", s);
}
return 0;
}
+38
View File
@@ -0,0 +1,38 @@
#include "m-algo.h"
#include "m-array.h"
#include "m-string.h"
/* Define an array of int */
ARRAY_DEF(vector_int, int)
/* Register the oplist of this array of int globally */
#define M_OPL_vector_int_t() ARRAY_OPLIST(vector_int)
/* Set s (string_t) to the integer i */
#define str_ui(s, i) string_printf(s, "%d", i)
/* Concat two strings by insertion a '-' within them */
#define str_cat(s1, s2) (string_cat_str(s1, "-"), string_cat(s1, s2))
int main(void)
{
// Let s be a string_t and initilize it.
M_LET(s, string_t)
// Let v be a vector of integer and initialize it.
M_LET( (v, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10), vector_int_t) {
int sum, product;
// Compute the sum of theses integers.
ALGO_REDUCE(sum, v, vector_int_t, add);
// Compute the product of theses integers.
ALGO_REDUCE(product, v, vector_int_t, mul);
/* Example of reduction with a transformation of the type from int to string_t */
ALGO_REDUCE( (s, string_t), v, vector_int_t, str_cat, str_ui);
printf ("sum: %d\n"
"product: %d\n"
"dash str: %s\n", sum, product, string_get_cstr(s));
}
return 0;
}
+2 -2
View File
@@ -1,14 +1,14 @@
#include <stdlib.h>
#include "m-array.h"
// Let's define an array of 'int' named 'int'
// Let's define an array of 'int' named 'array_int'
ARRAY_DEF(array_int, int)
const int n = 100000;
int main(void)
{
// Declare and initilize the array
// Declare and initialize the array
array_int_t x;
array_int_init(x);
+42 -4
View File
@@ -4,12 +4,14 @@
/* This example show how to use complex structure with array
embedding another library */
/* This is a trivial library */
/* This is a typical trivial library with its interface */
typedef struct lib_ext_struct {
int id;
// Other data
// Other data may be added
} lib_ext_struct;
/* Method to create a duplicate of the object.
The new object is heap allocated */
static lib_ext_struct *lib_ext_struct_Duplicate(const lib_ext_struct *obj)
{
lib_ext_struct *p = malloc(sizeof(lib_ext_struct));
@@ -18,6 +20,7 @@ static lib_ext_struct *lib_ext_struct_Duplicate(const lib_ext_struct *obj)
return p;
}
/* Method to delete any object */
static void lib_ext_struct_Delete(lib_ext_struct *obj)
{
free(obj);
@@ -30,6 +33,11 @@ typedef struct {
lib_ext_struct* properties;
} data_node;
/* This method shall initialize the object data_node to
the init state.
It takes as first argument the object to initialize,
and since it takes by reference through a pointer,
it is compatible with 'API_2' convention for oplist */
static void data_node_init(data_node *obj)
{
obj->id = 0;
@@ -37,6 +45,12 @@ static void data_node_init(data_node *obj)
obj->properties = NULL;
}
/* This method shall initialize the object data_node to
the same state as the 'src' object (creating a copy, a duplicate) .
It takes as first argument the object to initialize,
and as second argument the source object.
It takes both object by reference through pointers,
as such it is compatible with 'API_6' convention for oplist */
static void data_node_init_set(data_node *obj, const data_node *src)
{
obj->id = src->id;
@@ -47,6 +61,13 @@ static void data_node_init_set(data_node *obj, const data_node *src)
obj->properties = NULL;
}
/* This method shall set the object data_node to
the same state as the 'src' object (creating a copy, a duplicate) .
THe object was already initialized.
It takes as first argument the object to initialize,
and as second argument the source object.
It takes both object by reference through pointers,
as such it is compatible with 'API_6' convention for oplist */
static void data_node_set(data_node *obj, const data_node *src)
{
obj->id = src->id;
@@ -59,6 +80,11 @@ static void data_node_set(data_node *obj, const data_node *src)
obj->properties = NULL;
}
/* This method shall clear the object data_node to
the cleared state (aka it shall free any resource).
It takes as first argument the object to initialize,
and since it takes by reference through a pointer,
it is compatible with 'API_2' convention for oplist */
static void data_node_clear(data_node *obj)
{
string_clear(obj->type);
@@ -66,13 +92,25 @@ static void data_node_clear(data_node *obj)
lib_ext_struct_Delete(obj->properties);
}
/* Create a dynamic array of 'data_node' named array_data_node_t
and gives the minimum oplist allowing M*LIB to handle
properly the object 'data_node' with the API convention
to respect for calling the methods.
*/
ARRAY_DEF(/* the array prefix */ array_data_node,
/* the object type */ data_node,
/* the object oplist */ (INIT(API_2(data_node_init)),
SET(API_6(data_node_set)),
INIT_SET(API_6(data_node_init_set)),
CLEAR(API_2(data_node_clear))))
ARRAY_DEF(array_data_node, data_node, (INIT(API_2(data_node_init)),SET(API_6(data_node_set)),INIT_SET(API_6(data_node_init_set)),CLEAR(API_2(data_node_clear))))
/* Define a global array with the created type */
array_data_node_t global_array;
int main(void)
{
/* Call the created method */
array_data_node_init(global_array);
/* Do stuff... */
array_data_node_clear(global_array);
}
+119
View File
@@ -0,0 +1,119 @@
//
// -- An A* pathfinder inspired by the tutorial at Red Blob Games --
// https://www.redblobgames.com/pathfinding/a-star/introduction.html
// Code based on:
// https://github.com/glouw/ctl/blob/master/examples/astar.c
#include <stdio.h>
#include "m-array.h"
#include "m-string.h"
#include "m-tuple.h"
#include "m-prioqueue.h"
#include "m-dict.h"
// Create a tuple of point, but don't use its priority field for comparison.
TUPLE_DEF2( point, (x, int), (y, int), (priority, int, M_OPEXTEND( M_OPL_int(), CMP(0), HASH(0), EQUAL(0) ) ) )
#define M_OPL_point_t() TUPLE_OPLIST(point, M_OPL_int(), M_OPL_int(), M_OPL_int())
static inline int point_cmp_prio(const point_t a, const point_t b)
{
return a->priority < b->priority ? -1 : a->priority > b->priority;
}
PRIOQUEUE_DEF(prio_point, point_t, M_OPEXTEND(M_OPL_point_t(), CMP(point_cmp_prio) ) )
#define M_OPL_prio_point_t() PRIOQUEUE_OPLIST(prio_point, M_OPL_point_t() )
ARRAY_DEF(array_point, point_t)
#define M_OPL_array_point_t() ARRAY_OPLIST(array_point, M_OPL_point_t() )
DICT_DEF2(cost_point, point_t, int)
#define M_OPL_cost_point_t() DICT_OPLIST(cost_point, M_OPL_point_t(), M_OPL_int())
DICT_DEF2(step_point, point_t, point_t)
#define M_OPL_step_point_t() DICT_OPLIST(step_point, M_OPL_point_t(), M_OPL_point_t())
static inline int point_index(const point_t p, int width)
{
return p->x + width * p->y;
}
static inline void point_set_from(point_t p, const string_t maze, int width, const char pattern[])
{
size_t s = string_search_str(maze, pattern);
point_emplace(p, s % width, s / width , 0);
}
static void astar(array_point_t path, const string_t maze, int width)
{
M_LET(front, prio_point_t)
M_LET(from, step_point_t)
M_LET(costs, cost_point_t)
M_LET(start, goal, current, next, point_t)
{
point_set_from(start, maze, width, "@");
point_set_from(goal, maze, width, "!");
cost_point_set_at(costs, start, 0);
prio_point_push(front, start);
while (!prio_point_empty_p(front)) {
prio_point_pop(&current, front);
if (point_equal_p(current, goal))
break;
const struct { int x; int y; } deltas[] = {
{ -1, +1 }, { 0, +1 }, { 1, +1 },
{ -1, 0 }, /* ~ ~ */ { 1, 0 },
{ -1, -1 }, { 0, -1 }, { 1, -1 },
};
for (size_t i = 0; i < 8; i++) {
point_emplace(next, current->x + deltas[i].x, current->y + deltas[i].y, 0);
if (string_get_char(maze, point_index(next, width)) != '#') {
int *new_cost = cost_point_get(costs, current);
int *cost = cost_point_get(costs, next);
if (cost == NULL || *new_cost < *cost) {
cost_point_set_at(costs, next, *new_cost);
next->priority = *new_cost + abs(goal->x - next->x) + abs(goal->y - next->y);
prio_point_push(front, next);
step_point_set_at(from, next, current);
}
}
}
}
point_set(current, goal);
while (!point_equal_p(current, start)) {
array_point_push_back(path, current);
point_set(current, *step_point_get(from, current));
}
array_point_push_back(path, start);
}
}
int main(void)
{
M_LET( (maze,
("#########################################################################\n"
"# # # # # # #\n"
"# # ######### # ##### ######### ##### ##### ##### # ! #\n"
"# # # # # # # # # #\n"
"######### # ######### ######### ##### # # # ######### #\n"
"# # # # # # # # # # #\n"
"# # ############# # # ######### ##### # ######### # #\n"
"# # # # # # # # # #\n"
"# ############# ##### ##### # ##### ######### # ##### #\n"
"# # # # # # # # # #\n"
"# ##### ##### # ##### # ######### # # # #############\n"
"# # # # # # # # # # # #\n"
"############# # # # ######### # ##### # ##### ##### #\n"
"# # # # # # # # # #\n"
"# ##### # ######### ##### # ##### ##### ############# #\n"
"# # # # # # # # # #\n"
"# # ######### # ##### ######### # # ############# # #\n"
"# # # # # # # # # # #\n"
"# ######### # # # ##### ######### ######### # #########\n"
"# # # # # # # # # #\n"
"# @ # ##### ##### ##### ######### ##### # ######### # #\n"
"# # # # # # #\n"
"#########################################################################\n")), string_t)
M_LET(path, array_point_t)
{
int width = string_search_str(maze, "\n") + 1;
astar(path, maze, width);
for M_EACH(it, path, array_point_t) {
string_set_char(maze, point_index(*it, width), 'x');
}
printf("%s", string_get_cstr(maze));
}
}
+12 -7
View File
@@ -1,12 +1,16 @@
#include "m-bptree.h"
#include "m-string.h"
// Define a map int -> string
// Define a map int -> string named map_employee_id
// The number 5 is the number of elements in a node of the B+TREE
BPTREE_DEF2(map_employee_id, 5, int, string_t)
// Register the oplist of this map globally.
#define M_OPL_map_employee_id_t() BPTREE_OPLIST2(map_employee_id, M_DEFAULT_OPLIST, STRING_OPLIST)
// Define a map string -> int
// Define a map string -> int named map_employee_name
// The number 5 is the number of elements in a node of the B+TREE
BPTREE_DEF2(map_employee_name, 5, string_t, int)
// Register the oplist of this map globally.
#define M_OPL_map_employee_name_t() BPTREE_OPLIST2(map_employee_name, STRING_OPLIST, M_DEFAULT_OPLIST)
int main(void)
@@ -14,7 +18,7 @@ int main(void)
map_employee_id_t Employees;
map_employee_id_init(Employees);
// Assign
// Assign the map with some data
map_employee_id_set_at(Employees, 17425, STRING_CTE("Mike"));
map_employee_id_set_at(Employees, 7147, STRING_CTE("Tango"));
map_employee_id_set_at(Employees, 841, STRING_CTE("Charlie"));
@@ -30,11 +34,13 @@ int main(void)
map_employee_id_it_t it;
for(map_employee_id_it(it, Employees); !map_employee_id_end_p(it); map_employee_id_next(it)) {
// Get a pointer to this employee from the iterator
const map_employee_id_type_t *e = map_employee_id_cref(it);
const map_employee_id_itref_t *e = map_employee_id_cref(it);
// Print it
printf ("%d: %s\n", *(e->key_ptr), string_get_cstr(*(e->value_ptr)));
}
// Now, let's go using some macros!
// Let's create a reverse map
M_LET(Employees_r, map_employee_name_t) {
@@ -51,9 +57,8 @@ int main(void)
}
// Print
printf("\nElisabeth has id = %d\n", *map_employee_name_get(Employees_r, STRING_CTE("Elisabeth")));
}
printf("\nElisabeth has id = %d\n", *map_employee_name_get(Employees_r, STRING_CTE("Elisabeth")));
} /* Employees_r is cleared beyond this point */
map_employee_id_clear(Employees);
return 0;
+36
View File
@@ -0,0 +1,36 @@
#include "m-core.h"
// Stubs defined for the example. Real code will use soundio library.
struct SoundIo { int x; };
struct SoundIoDevice { int x; };
struct SoundIoOutStream { int x; };
static struct SoundIo *soundio_create(void) { return (struct SoundIo *) malloc(sizeof(struct SoundIo)); }
static void soundio_destroy(struct SoundIo *s) { free(s); }
static struct SoundIoDevice *soundio_get_device(struct SoundIo *io, int def) { (void) io; (void) def; return (struct SoundIoDevice *) malloc(sizeof(struct SoundIoDevice)); }
static void soundio_device_unref(struct SoundIoDevice *s) { free(s); }
static struct SoundIoOutStream *soundio_outstream_create(struct SoundIoDevice *device) { (void) device ; return (struct SoundIoOutStream *) malloc(sizeof(struct SoundIoOutStream)); }
static void soundio_outstream_destroy(struct SoundIoOutStream *s) { free(s); }
static bool soundio_wait_events(struct SoundIo *s) { (void) s; return false; }
// End of stubs
int main(void)
{
int err = 1;
/* Example of using M_LET_IF macro to simplify writing error handling code.
The following code creates some object, test if the object creation succeeds, register the destructor, and print an error if something went wrong
*/
M_LET_IF( struct SoundIo *soundio = soundio_create(), soundio != 0 , soundio_destroy(soundio) , fprintf(stderr, "out of memory for soundio\n") )
M_LET_IF(struct SoundIoDevice *device = soundio_get_device(soundio, -1), device != 0, soundio_device_unref(device), fprintf(stderr, "out of memory for device\n"))
M_LET_IF(struct SoundIoOutStream *outstream = soundio_outstream_create(device), outstream != 0, soundio_outstream_destroy(outstream), fprintf(stderr, "out of memory for stream\n")) {
err = 0;
bool cont = true;
while (cont)
cont = soundio_wait_events(soundio);
}
return err;
}
+1 -1
View File
@@ -5,7 +5,7 @@
#include "m-string.h"
// Define a dictionnary of string --> int
// named 'str'
// named 'dict_str'
DICT_DEF2(dict_str, string_t, STRING_OPLIST, int, M_DEFAULT_OPLIST)
int main(void)
+5 -4
View File
@@ -5,8 +5,9 @@
#include "m-dict.h"
#include "m-string.h"
DICT_DEF2(dict_map, char, M_DEFAULT_OPLIST, int, M_DEFAULT_OPLIST)
// Define a dictionary (hashmap) from 'char' to 'int'
DICT_DEF2(dict_map, char, int)
int main(void)
{
dict_map_t mp;
@@ -81,7 +82,7 @@ int main(void)
}
break;
case 7:
case 6:
dict_map_clear(mp);
string_clear (str);
exit(0);
@@ -89,7 +90,7 @@ int main(void)
default:
printf("Wrong Choice\n");
break;
}
}
}
+11 -2
View File
@@ -5,14 +5,23 @@
/* program that reads text from standard-input,
and prints the total number of distinct words found in the text.
*/
/* Definition of a set (hashset) of unique string_t */
DICT_SET_DEF(dict_str, string_t, STRING_OPLIST)
int main(void)
{
// Define word as a string_t
M_LET(word, STRING_OPLIST)
M_LET(wordcount, DICT_SET_OPLIST(dict_str, STRING_OPLIST)) {
while (string_fget_word(word, " \t\n,.!;:?", stdin))
// Define wordcount as a set of string_t
M_LET(wordcount, DICT_SET_OPLIST(dict_str, STRING_OPLIST)) {
// Read a word from the standard input
while (string_fget_word(word, " \t\n,.!;:?", stdin)) {
// Push this word in the set.
// Do nothing if it already exists.
dict_str_push(wordcount, word);
}
// Print the number of words of the standard input.
printf ("Words: %zu\n", dict_str_size(wordcount));
}
}
+42 -18
View File
@@ -3,30 +3,54 @@
#include "m-array.h"
#include "m-dict.h"
// Define an array of size_t
ARRAY_DEF(array_size, size_t)
// Register the oplist of this array globaly
#define M_OPL_array_size_t() ARRAY_OPLIST(array_size)
// Define a dictionary (hashmap) of string_t to array of size_t
DICT_DEF2(map_pos, string_t, array_size_t)
// Register the oplist of this dictionary (hashmap)
#define M_OPL_map_pos_t() DICT_OPLIST(map_pos, STRING_OPLIST, ARRAY_OPLIST(array_size))
int main(int argc, const char *argv[])
{
if (argc == 2) {
M_LET(word, string_t)
M_LET(positions, map_pos_t) {
FILE *f = fopen(argv[1], "rt");
if (!f) return 1;
while (string_fget_word(word, " \t\n\r\"(),=", f)) {
array_size_t *array = map_pos_get_at(positions, word);
array_size_push_back(*array, (size_t)ftell(f) - string_size(word));
}
fclose(f);
for M_EACH(pair, positions, map_pos_t) {
string_fputs(stdout, pair->key);
for M_EACH(pos, pair->value, array_size_t)
printf(" %zu", *pos);
printf("\n");
}
}
if (argc != 2) {
printf("USAGE: %s filename\n", argv[0]);
exit(0);
}
// Define word as a string_t
M_LET(word, string_t)
// Define positions as a map of string_t-->array of size_t
M_LET(positions, map_pos_t) {
// Open the file
FILE *f = fopen(argv[1], "rt");
if (!f) {
fprintf(stderr, "ERROR: Cannot open %s.\n", argv[1]);
return 1;
}
// While it reads some word from the file
while (string_fget_word(word, " \t\n\r\"(),=", f)) {
// Get the reference to the array of this word in the dictionnary (or create it if needed)
array_size_t *array = map_pos_safe_get(positions, word);
// Push the new offset to this word in the associated array
array_size_push_back(*array, (size_t)ftell(f) - string_size(word));
}
// Close the file
fclose(f);
// Print the words and where they are:
for M_EACH(pair, positions, map_pos_t) {
string_fputs(stdout, pair->key);
for M_EACH(pos, pair->value, array_size_t) {
printf(" %zu", *pos);
}
printf("\n");
}
} // All created objects are destroyed beyond this point
return 0;
}
+18 -9
View File
@@ -24,22 +24,25 @@
/* Define the needed data structure : */
// Define a dictionnary of constant string --> integer
// Define a dictionnary of constant string --> integer and register it.
DICT_DEF2(dict_mph, const char *, M_CSTR_OPLIST, uint32_t, M_DEFAULT_OPLIST)
#define M_OPL_dict_mph_t() DICT_OPLIST(dict_mph, M_CSTR_OPLIST, M_DEFAULT_OPLIST)
// Defin an array of integer
// Define an array of integer to store the value and register it.
ARRAY_DEF(array_value, uint32_t) // Start from 1. 0 is 'None'
#define M_OPL_array_value_t() ARRAY_OPLIST(array_value)
// Defin an array of integer
// Define an array of integer to store the seed and register it.
ARRAY_DEF(array_seed, int32_t)
#define M_OPL_array_seed_t() ARRAY_OPLIST(array_seed)
// Define algorithms on array_seed
ALGO_DEF(array_seed, array_seed_t)
// Define an array of constant string that are ordered by their size.
ARRAY_DEF(array_cstr, const char *, M_CSTR_OPLIST)
// Register it globally but with a custom CMP operator
static inline int array_cstr_cmp(const array_cstr_t a, const array_cstr_t b) {
// We compare only the size
size_t sa = array_cstr_size(a);
size_t sb = array_cstr_size(b);
return (sa > sb) ? -1 : (sa < sb);
@@ -121,7 +124,7 @@ CreateMinimalPerfectHash2(array_seed_t seed, array_value_t value,
enought. */
for(bool cont = true; cont ; ) {
cont = false;
array_seed_clean(slots);
array_seed_reset(slots);
for M_EACH(it, *b, array_cstr_t) {
size_t s = hash(d, *it) % size;
if (*array_value_get(value, s) != 0 || array_seed_contain_p(slots, s)){
@@ -191,7 +194,11 @@ static void
dict_read_from_file(dict_mph_t dict, array_string_t arr, const char filename[])
{
FILE *f = fopen(filename, "rt");
if (!f) abort();
if (!f) {
fprintf(stderr, "ERROR: Cannot open %s\n", filename);
exit(2);
}
uint32_t line = 1;
M_LET(str, string_t) {
while (!feof(f) && !ferror(f)) {
@@ -234,12 +241,14 @@ test(array_seed_t seed, array_value_t value, dict_mph_t dict)
int main(int argc, const char *argv[])
{
// Create arr as array_string_t, dict as dist_mph_t and seed as array_seed_t
M_LET(arr, array_string_t) M_LET(dict, dict_mph_t) M_LET(seed, array_seed_t)
// and value as array_value_t
M_LET(value, array_value_t) {
const char *filename = (argc > 1) ? argv[1] :"/usr/share/dict/words";
dict_read_from_file(dict, arr, filename);
CreateMinimalPerfectHash(seed, value, dict);
test(seed, value, dict);
const char *filename = (argc > 1) ? argv[1] :"/usr/share/dict/words";
dict_read_from_file(dict, arr, filename);
CreateMinimalPerfectHash(seed, value, dict);
test(seed, value, dict);
}
return 0;
+9 -4
View File
@@ -4,6 +4,7 @@
#include "m-array.h"
#include "m-string.h"
// Define an array of integer
ARRAY_DEF(array_int, int)
typedef struct {
@@ -25,7 +26,7 @@ static void tape_devance(tape_t tape) { if (tape->pos > 0) tape->pos--; }
typedef struct {
string_t code;
array_int_t bracket_map; // Should use map when possible.
array_int_t bracket_map;
} program_t[1];
static void program_init(program_t p, string_t text) {
@@ -47,8 +48,8 @@ static void program_init(program_t p, string_t text) {
int left;
array_int_pop_back(&left, leftstack);
int right = pc;
*array_int_get_at (p->bracket_map, left) = right;
*array_int_get_at (p->bracket_map, right) = left;
*array_int_safe_get (p->bracket_map, left) = right;
*array_int_safe_get (p->bracket_map, right) = left;
}
pc++;
@@ -98,7 +99,11 @@ static void program_run(program_t p){
static void read_file(string_t str, const string_t filename) {
FILE *f = fopen(string_get_cstr(filename), "rt");
if (!f) abort();
if (!f) {
fprintf(stderr, "ERROR: Cannot open %s\n", string_get_cstr(filename));
exit(2);
}
// Read the full FILE in the string
string_fgets (str, f, STRING_READ_FILE);
fclose(f);
}
+2 -2
View File
@@ -52,11 +52,11 @@ int main(void)
// Dictionary iterator are pair (key,value)
if (my_integer_n_p(p->value)) {
printf ("It is a long long, value = %lld\n",
*my_integer_get_n(p->value));
*my_integer_cget_n(p->value));
}
if (my_integer_z_p(p->value)) {
printf ("It is a mpz_t, value =");
mpz_out_str(stdout, 10, *my_integer_get_z(p->value));
mpz_out_str(stdout, 10, *my_integer_cget_z(p->value));
printf("\n");
}
}
+1 -1
View File
@@ -4,7 +4,7 @@
/* Register a dynamic seed to M*LIB hash function.
This shall be done before any M*LIB header inclusion. */
unsigned long long rand_seed;
#define M_HASH_SEED rand_seed
#define M_USE_HASH_SEED rand_seed
#include "m-array.h"
#include "m-dict.h"
+4
View File
@@ -51,6 +51,9 @@ TUPLE_DEF2(mlib_points, (first_ref, mlib_point_ptr, M_PTR_OPLIST),
static void let2(void)
{
// Initialize p1 as mlib_point_t with (4,4)
// and p2 as mlib_point_t with (5,5)
// and pair as mlib_point_t with default value
M_LET((p1, 4, 4), (p2, 5, 5), mlib_point_t) {
M_LET(pair, mlib_points_t) {
pair->first_ref = p1;
@@ -68,6 +71,7 @@ static void let2(void)
static void let(void)
{
// Let's initialize all the declared types
M_LET(s, symbol_t)
M_LET(l, symbol_list_t)
M_LET(r,record_t)
+31
View File
@@ -0,0 +1,31 @@
#include <stdio.h>
#include "m-array.h"
#include "m-string.h"
// Let's create an array of string_t and register it globaly
ARRAY_DEF(vector_string, string_t)
#define M_OPL_vector_string_t() ARRAY_OPLIST(vector_string, STRING_OPLIST)
int main(void)
{
// Let's define a new string named str
M_LET(str, string_t)
// Let's define msg as a vector_array_t
M_LET( (msg, STRING_CTE("Hello"), STRING_CTE("C"), STRING_CTE("World!"), STRING_CTE("Let's"), STRING_CTE("discover"), STRING_CTE("M*LIB!")), vector_string_t) {
// Iterate over all words of the array msg
for M_EACH(word, msg, vector_string_t) {
// Cat the current word into the target string
string_cat(str, *word);
// Also add a space character
string_push_back(str, ' ');
}
// Let's define another string and set it to a formatted value.
M_LET( (count, "\nTo display this it uses \"vector\" of %zu strings!", vector_string_size(msg)), string_t) {
string_cat(str, count);
}
// Print the result
printf("%s\n", string_get_cstr(str) );
}
return 0;
}
+10 -8
View File
@@ -4,6 +4,15 @@
#include "m-rbtree.h"
// Let's define one utility function.
void *xmalloc(size_t n);
void *xmalloc(size_t n)
{
void *p = malloc (n);
if (!p) abort();
return p;
}
// Let's define a new type.
typedef struct {
int key;
@@ -12,7 +21,7 @@ typedef struct {
#define SIZE 256
void *xmalloc(size_t n);
// Let's define the prototypes of the methods of this new type.
void my_type_init(my_type_t x);
void my_type_clear(my_type_t x);
void my_type_init_set(my_type_t x, const my_type_t y);
@@ -24,13 +33,6 @@ void my_type_out_str(FILE *f, const my_type_t x);
bool my_type_in_str(my_type_t x, FILE *f);
void my_type_rand(my_type_t x);
void *xmalloc(size_t n)
{
void *p = malloc (n);
if (!p) abort();
return p;
}
// Let's define its constructor
void my_type_init(my_type_t x)
{
+53
View File
@@ -0,0 +1,53 @@
#include <stdio.h>
#include <string.h>
#include "m-string.h"
#define MAX_COLUMN 80
static void format(FILE *f)
{
string_t s;
string_init(s);
while (string_fgets(s, f, STRING_READ_PURE_LINE) == true)
{
size_t n = string_size(s);
if (n > 0 && string_get_char(s, n-1) == '\\' && n < MAX_COLUMN) {
string_left(s, n-1);
while (n < MAX_COLUMN-1) {
string_push_back(s, ' ');
n++;
}
string_push_back(s, '\\');
}
if (n >= MAX_COLUMN && string_get_char(s, n-1) == '\\') {
n--;
string_left(s, n);
while (n >= MAX_COLUMN-2 && string_get_char(s, n-1) == ' ') {
n--;
string_left(s, n);
}
string_push_back(s, ' ');
string_push_back(s, '\\');
}
printf("%s\n", string_get_cstr(s));
}
string_clear(s);
}
int main(int argc, const char *argv[])
{
if (argc < 2)
{
fprintf(stderr, "ERROR: Missing argument filename.\nUSAGE: %s filename.h\n", argv[0]);
exit(1);
}
FILE *f = fopen(argv[1], "rt");
if (!f) {
fprintf(stderr, "ERROR: Cannot open filename '%s' .h\n", argv[1]);
exit(2);
}
format(f);
fclose(f);
exit(0);
}
+97
View File
@@ -0,0 +1,97 @@
#include "m-array.h"
#include "m-string.h"
// Define an array of string_t. Since the oplist of string_t is registered globaly
// there is no need to give it to this definition.
ARRAY_DEF(str_array, string_t)
// First the verbose way and (nearly) macro free:
static void main_macrofree(void)
{
str_array_t tab_name;
str_array_init(tab_name);
// Push some elements in the array (long way)
str_array_push_back(tab_name, STRING_CTE("My"));
str_array_push_back(tab_name, STRING_CTE("CD"));
str_array_push_back(tab_name, STRING_CTE("IS"));
str_array_push_back(tab_name, STRING_CTE("OUT"));
// Overwrite element 1 of the array.
str_array_set_at(tab_name, 1, STRING_CTE("DVD"));
// Finaly rewrite 1 element of the array
string_set_str(*str_array_get(tab_name, 1), "BLU-RAY");
// Format some strings and push them back in the array
string_t format;
string_init_printf(format, "There are %d elements", str_array_size(tab_name));
str_array_push_back(tab_name, format);
string_printf(format, "There is a capacty of %d", str_array_capacity(tab_name));
string_replace_all_str(format, "capacty", "capacity");
str_array_push_back(tab_name, format);
string_printf(format, "The third element is '%s'", string_get_cstr(*str_array_get(tab_name, 2)));
str_array_push_back(tab_name, format);
string_clear(format);
// Display the content of the array.
str_array_it_t it;
int i = 0;
for (str_array_it(it, tab_name) ; !str_array_end_p(it); str_array_next(it)) {
printf("item[%d] = '%s'\n", i, string_get_cstr(*str_array_cref(it)) );
i++;
}
// Clear the array
str_array_clear(tab_name);
}
// Then the short version with macros.
// For this we need to register the oplist of the array of string globally.
#define M_OPL_str_array_t() ARRAY_OPLIST(str_array, STRING_OPLIST)
static void main_macro(void)
{
// Define and fill an array of string with some elements in it:
M_LET( (tab_name, STRING_CTE("My"), STRING_CTE("CD"), STRING_CTE("IS"), STRING_CTE("OUT")), str_array_t) {
// Overwrite element 1 of the array.
str_array_set_at(tab_name, 1, STRING_CTE("DVD"));
// Finaly rewrite 1 element of the array
string_set_str(*str_array_get(tab_name, 1), "BLU-RAY");
// Format some strings and push them back in the array
M_LET(format, string_t) {
string_printf(format, "There are %d elements", str_array_size(tab_name));
str_array_push_back(tab_name, format);
string_printf(format, "There is a capacty of %d", str_array_capacity(tab_name));
string_replace_all_str(format, "capacty", "capacity");
str_array_push_back(tab_name, format);
string_printf(format, "The third element is '%s'", string_get_cstr(*str_array_get(tab_name, 2)));
str_array_push_back(tab_name, format);
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
// Set format to a formated string
// In C11, we can mix string_t and char *.
// We can also use M_CSTR to create a printf formated string.
string_sets(format, "FILE=", getenv("PWD"), "/", *str_array_get(tab_name, 2), M_CSTR("-%zu.txt", str_array_size(tab_name) ));
str_array_push_back(tab_name, format);
#endif
} // beyond this point format is cleared
// Display the content of the array.
int i = 0;
for M_EACH(item, tab_name, str_array_t) {
printf("item[%d] = '%s'\n", i, string_get_cstr(*item) );
i++;
}
} // beyond this point tab_name is cleared
}
int main(void)
{
printf("Version macrofree:\n");
main_macrofree();
printf("Version macro:\n");
main_macro();
return 0;
}
+44
View File
@@ -0,0 +1,44 @@
#include <stdio.h>
#include "m-string.h"
#include "m-dict.h"
#include "m-array.h"
/* Definition of an associative map string_t --> size_t */
DICT_DEF2(dict_str, string_t, size_t)
#define M_OPL_dict_str_t() DICT_OPLIST(dict_str, STRING_OPLIST, M_DEFAULT_OPLIST)
/* Definition of an array of string_t */
ARRAY_DEF(vector_str, string_t)
#define M_OPL_vector_str_t() ARRAY_OPLIST(vector_str, STRING_OPLIST)
int main(void)
{
// Construct an array of string, performing a convertion of the C const char *
// into a proper string_t at real time and push then into a dynamic array
// that is declared, initialized and cleared.
M_LET( (words, ("This"), ("is"), ("a"), ("useless"), ("sentence"), ("."),
("It"), ("is"), ("used"), ("a"), ("bit"), ("to"), ("count"), ("words"), (".") ),
vector_str_t) {
// Print the arrays.
printf("The words are: ");
vector_str_out_str(stdout, words);
printf("\n");
// Count the words.
M_LET(map, dict_str_t) {
// Count the words:
for M_EACH(w, words, vector_str_t) {
(*dict_str_safe_get(map, *w)) ++;
}
// Print the count:
for M_EACH(p, map, dict_str_t) {
#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L)
M_PRINT(p->value, " occurences of ", p->key, "\n");
#else
printf ("%zu occurences of %s\n", p->value, string_get_cstr(p->key));
#endif
}
}
}
}
+37
View File
@@ -0,0 +1,37 @@
/* Based on https://en.cppreference.com/w/cpp/algorithm/for_each
Need to be built in C11 mode */
#include <stdio.h>
#include "m-array.h"
#include "m-algo.h"
/* Define a dynamic array of int */
ARRAY_DEF(vector_int, int)
#define M_OPL_vector_int_t() ARRAY_OPLIST(vector_int)
/* Define operator increment on int */
#define INC(n) (n)++
int main(void)
{
M_LET( (nums, 3, 4, 2, 8, 15, 267), vector_int_t) {
// Print the array before
printf ("before:");
ALGO_FOR_EACH(nums, vector_int_t, M_PRINT, " ");
printf ("\n");
// Increment each element of the array
ALGO_FOR_EACH(nums, vector_int_t, INC);
// Print the array after
printf ("after: ");
ALGO_FOR_EACH(nums, vector_int_t, M_PRINT, " ");
printf ("\n");
// Sum the elements of the array
int sum = 0;
ALGO_REDUCE(sum, nums, vector_int_t, add);
M_PRINT("sum = ", sum, "\n");
}
return 0;
}
+89
View File
@@ -0,0 +1,89 @@
#include "m-tuple.h"
#include "m-array.h"
#include "m-algo.h"
#include "m-funcobj.h"
#include "m-serial-json.h"
#include "m-string.h"
/* Define the employee class */
TUPLE_DEF2(employee,
(name, string_t),
(age, int),
(idnum, int))
/* Register globaly the employee_t oplist */
#define M_OPL_employee_t() TUPLE_OPLIST(employee, STRING_OPLIST, M_DEFAULT_OPLIST, M_DEFAULT_OPLIST)
/* Define an array of employee, register the oplist and define further algorithms on it */
ARRAY_DEF(vector_employee, employee_t)
#define M_OPL_vector_employee_t() ARRAY_OPLIST(vector_employee, M_OPL_employee_t())
ALGO_DEF(vector_employee, vector_employee_t)
/* Define the function object to select the sort order.
* It is named 'compare_by' and is an instance of the interface
* 'vector_employee_cmp_obj' created by ALGO_DEF.
*/
FUNC_OBJ_INS_DEF(compare_by /* name of the instance */,
vector_employee_cmp_obj /* name of the interface */,
(a, b) /* name of the input parameters of the function like object. The type are inherited from the interface. */, {
/* code of the function object */
if (string_equal_str_p(self->sort_field, "name"))
return string_cmp(a->name, b->name);
else if (string_equal_str_p(self->sort_field, "age"))
return a->age < b->age ? -1 : a->age > b->age;
else
return a->idnum < b->idnum ? -1 : a->idnum > b->idnum;
},
/* Additional fields stored in the function object */
(sort_field, string_t) )
#define M_OPL_compare_by_t() FUNC_OBJ_INS_OPLIST(compare_by, STRING_OPLIST)
// Let's read an array of person from the given JSON file
static void read(vector_employee_t base, const char filename[])
{
m_serial_return_code_t ret;
// Open the file
FILE *f = fopen(filename, "rt");
if (!f) {
// Handle errors
fprintf(stderr, "ERROR: Cannot open file '%s'.\n", filename);
exit(2);
}
// Initialize the JSON serializer with this file
M_LET( (in,f), m_serial_json_read_t)
// Read the JSON file and fill in 'base' with it.
ret = vector_employee_in_serial(base, in);
// Let's handle serialization error
if (ret != M_SERIAL_OK_DONE) {
fprintf(stderr, "ERROR: Cannot read JSON data from file '%s'.\nParsing stops at:\n", filename);
while (!feof(f)) { fputc(fgetc(f), stdout); }
fclose(f);
exit(2);
}
// Close the FILE
fclose(f);
}
int main(void)
{
M_LET(emps, vector_employee_t) {
/* Code to populate database from JSON */
read(emps, "ex11-algo02.json");
// Sort the database by employee ID number
M_LET( (cmp, STRING_CTE("idnum")), compare_by_t )
vector_employee_sort_fo(emps, compare_by_as_interface(cmp));
M_PRINT("Employees sorted by idnum are: ", (emps, vector_employee_t), "\n" );
// Sort the database by employee name
M_LET( (cmp, STRING_CTE("name")), compare_by_t )
vector_employee_sort_fo(emps, compare_by_as_interface(cmp));
M_PRINT("Employees sorted by name are: ", (emps, vector_employee_t), "\n" );
// End
}
return 0;
}
+9
View File
@@ -0,0 +1,9 @@
[
{ "name": "John Doe", "age": 32, "idnum": 14528},
{ "name": "Clint Smith", "age": 31, "idnum": 14529},
{ "name": "Linda Cameron", "age": 20, "idnum": 14527},
{ "name": "Cameron Carrey", "age": 25, "idnum": 14526},
{ "name": "Marty Brown", "age": 26, "idnum": 14525},
{ "name": "Donald Cow", "age": 45, "idnum": 14520}
]
+10 -14
View File
@@ -2,19 +2,18 @@
#include "m-tuple.h"
#include "m-array.h"
// Serial json is not supported for standard types if not C11
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
// Let's define a 'person' composed of several fields.
TUPLE_DEF2(person,
(surname, string_t),
(age, int),
(present, bool)
)
// Register the oplist of this tuple globaly
#define M_OPL_person_t() TUPLE_OPLIST(person, M_DEFAULT_OPLIST, STRING_OPLIST, M_DEFAULT_OPLIST )
// Let's define an array of person
ARRAY_DEF(base, person_t)
// Register the oplist of this array globaly
#define M_OPL_base_t() ARRAY_OPLIST(base, M_OPL_person_t())
// Let's read an array of person from the given JSON file
@@ -29,6 +28,7 @@ static void read(base_t base, const char filename[])
fprintf(stderr, "ERROR: Cannot open file '%s'.\n", filename);
exit(2);
}
// Initialize the serializer with the file
m_serial_json_read_init(in, f);
// Read the array
@@ -44,21 +44,17 @@ static void read(base_t base, const char filename[])
int main(void)
{
// Let's have base as a base_t
M_LET(base, base_t) {
read(base, "ex-json01.json");
// Read the JSON file and fill-in base
read(base, "ex11-json01.json");
// Print the contents of base:
printf ("List of presents:\n");
for M_EACH(el, base, base_t) {
if ((*el)->present) {
printf("%s\n", string_get_cstr((*el)->surname));
}
if ((*el)->present) {
printf("%s\n", string_get_cstr((*el)->surname));
}
}
}
exit(0);
}
#else
int main(void)
{
exit(0);
}
#endif
File renamed without changes.
@@ -1,5 +1,3 @@
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
#include <stdio.h>
#include "m-array.h"
@@ -7,12 +5,15 @@
#include "m-dict.h"
#include "m-string.h"
// Let's define a tuple composed of (offset, value) and register it
TUPLE_DEF2(symbol, (offset, long), (value, long))
#define M_OPL_symbol_t() TUPLE_OPLIST(symbol, M_DEFAULT_OPLIST, M_DEFAULT_OPLIST)
// Let's define an array of such tuple and register it
ARRAY_DEF(array_symbol, symbol_t)
#define M_OPL_array_symbol_t() ARRAY_OPLIST(array_symbol, M_OPL_symbol_t())
// Let's define a dictionnary associating a string_t to such an array and register it
DICT_DEF2(sections, string_t, array_symbol_t)
#define M_OPL_sections_t() DICT_OPLIST(sections, STRING_OPLIST, M_OPL_array_symbol_t())
@@ -20,13 +21,21 @@ int main(int argc, const char *argv[])
{
if (argc < 2) abort();
FILE *f = fopen(argv[1], "rt");
if (!f) abort();
if (!f) {
fprintf(stderr, "ERROR: Cannot open %s\n", argv[1]);
return 2;
}
// Create & initialize sc as sections_t
M_LET(sc, sections_t) {
// Read the section from the FILE
sections_in_str(sc, f);
// Get the section named .text
array_symbol_t *a = sections_get(sc, STRING_CTE(".text"));
if (a == NULL) {
printf("There is no .text section.");
} else {
// Print its content
printf("Section .text is :");
array_symbol_out_str(stdout, *a);
printf("\n");
@@ -34,7 +43,3 @@ int main(int argc, const char *argv[])
}
return 0;
}
#else
int main(void) { return 0; }
#endif
+88
View File
@@ -0,0 +1,88 @@
/* Based on the example of STC https://github.com/tylov/STC */
#include "m-dict.h"
#include "m-array.h"
#include "m-deque.h"
#include "m-list.h"
#include "m-rbtree.h"
#include "m-algo.h"
#include "m-tuple.h"
// NOTE: After each definition of a container, we register its oplist
// It is not mandatory, but it makes the code easier to write and read.
// Define a basic structure (POD structure) using a tuple to get the default functions
TUPLE_DEF2(Point, (x, float), (y, float))
#define M_OPL_Point_t() TUPLE_OPLIST(Point, M_DEFAULT_OPLIST, M_DEFAULT_OPLIST)
// NOTE: array, list, deque don't have a native find function.
// We'll use the algorithm header to create a find function for such containers.
// Define a set of int & register its oplist
DICT_SET_DEF(cset_i, int)
#define M_OPL_cset_i_t() DICT_SET_OPLIST(cset_i, M_DEFAULT_OPLIST)
// Define an array of Point, register its oplist & include some basic algorithms
ARRAY_DEF(cvec_p, Point_t)
#define M_OPL_cvec_p_t() ARRAY_OPLIST(cvec_p, M_OPL_Point_t())
ALGO_DEF(cvec_p, cvec_p_t)
// Define a deque of int, including some basic algorithms
DEQUE_DEF(cdeq_i, int)
#define M_OPL_cdeq_i_t() DEQUE_OPLIST(cdeq_i, M_DEFAULT_OPLIST)
ALGO_DEF(cdeq_i, cdeq_i_t)
// Define a backward list, including some basic algorithms
LIST_DEF(clist_i, int)
#define M_OPL_clist_i_t() LIST_OPLIST(clist_i, M_DEFAULT_OPLIST)
ALGO_DEF(clist_i, clist_i_t)
// Define an unordered map of int to int
DICT_DEF2(csmap_i, int, int)
#define M_OPL_csmap_i_t() DICT_OPLIST(csmap_i, M_DEFAULT_OPLIST, M_DEFAULT_OPLIST)
int main(void)
{
// Define, init & set the different containers.
M_LET( (set, 10, 20, 30), cset_i_t)
M_LET( (vec, (10, 1), (20, 2), (30, 3) ), cvec_p_t)
M_LET( (deq, 10, 20, 30), cdeq_i_t)
M_LET( (lst, 10, 20, 30), clist_i_t)
M_LET( (map, (20, 2), (10, 1), (30,3) ), csmap_i_t) {
// add one more element to each container
cset_i_push(set, 40);
cvec_p_push_back(vec, (Point_t) {{40, 4}} );
cdeq_i_push_front(deq, 5);
clist_i_push_back(lst, 5);
csmap_i_set_at(map, 40, 4);
M_PRINT("vec= ", (vec, cvec_p_t));
// Find an element (either native or through the algo header)
int *i1 = cset_i_get(set, 20);
cvec_p_it_t i2; cvec_p_find(i2, vec, (Point_t) {{20, 2}});
cdeq_i_it_t i3; cdeq_i_find(i3, deq, 20);
clist_i_it_t i4; clist_i_find(i4, lst, 20);
int *i5 = csmap_i_get(map, 20);
printf("\nFound: %d, (%g, %g), %d, %d, [%d: %d]\n",
*i1,
(*cvec_p_ref(i2))->x, (*cvec_p_ref(i2))->y,
*cdeq_i_ref(i3),
*clist_i_ref(i4),
20, *i5);
// Erase the elements found (through key or through iterators)
cset_i_erase(set, *i1);
cvec_p_remove(vec, i2);
cdeq_i_remove(deq, i3);
clist_i_remove(lst, i4);
csmap_i_erase(map, *i5);
// Display everything in one call by using the registered print functions of the different types.
M_PRINT("After erasing elements found:\n",
"set: ", (set, cset_i_t), "\n",
"vec: ", (vec, cvec_p_t), "\n",
"deq: ", (deq, cdeq_i_t), "\n",
"map: ", (map, csmap_i_t), "\n");
}
}
+1112 -814
View File
File diff suppressed because it is too large. Load diff
+1046 -952
View File
File diff suppressed because it is too large. Load diff
+115 -60
View File
@@ -1,7 +1,7 @@
/*
* M*LIB - Thin stdatomic wrapper for C++ compatibility
*
* Copyright (c) 2017-2019, Patrick Pelissier
* Copyright (c) 2017-2021, Patrick Pelissier
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
@@ -26,14 +26,17 @@
#define MSTARLIB_ATOMIC_H
/* NOTE: Due to the C++ not having recognized stdatomic.h officialy,
it is hard to use this header directly with a C++ compiler like
g++ or MSVC.
(See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=60932 ).
clang has no issue with this header.
GCC 4.9 doesn't have a working implementation of 'atomic'
it is hard to use this header directly with a C++ compiler.
See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=60932
clang++ has no issue with this header but if someone includes
atomic from C++, there is incompatibility between atomic & stdatomic.
Moreover some compilers lack a working stdatomic header.
GCC 4.9 doesn't have a working implementation of 'atomic'.
APPLE Clang defines __GNUC__ to be only 4 despite having full support
for atomic.
*/
#if defined(__cplusplus) && __cplusplus >= 201103L \
&& !defined(__clang__) && !(defined(__GNUC__) && __GNUC__ < 5)
#if defined(__cplusplus) && __cplusplus >= 201103L \
&& !(defined(__GNUC__) && __GNUC__ < 5 && !defined(__APPLE__))
/* NOTE: This is what the stdatomic.h header shall do in C++ mode. */
#include <atomic>
@@ -96,14 +99,38 @@ using std::memory_order_release;
using std::memory_order_acq_rel;
using std::memory_order_seq_cst;
/* CLANG provides a warning on defining _Atomic as it sees it
* as a reserved system macro. It is true. However, the goal of this
* header is to provide stdatomic semantic, so it needs to define
* _Atomic macro.
*
* So, this warning has to be ignored.
*
* It cannot use M_BEGIN_PROTECTED_CODE as this header is normally
* independent of m-core.h
*/
#if defined(__clang__) && __clang_major__ >= 4
_Pragma("clang diagnostic push")
_Pragma("clang diagnostic ignored \"-Wreserved-id-macro\"")
#endif
#define _Atomic(T) std::atomic< T >
#elif (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L) \
|| ( defined(__GNUC__) && !defined(__clang__) && !defined(__cplusplus) && (__GNUC__*100 + __GNUC_MINOR__) >= 409) \
|| (defined(__clang__) && __clang_major__ >= 4)
#if defined(__clang__) && __clang_major__ >= 4
_Pragma("clang diagnostic pop")
#endif
/* C11 with working stdatomic
STDATOMIC doesn't work with C++ except for clang but is incompatible with atomic.
GCC < 4.9 doesn't provide a compliant stdatomic.h
CLANG 3.5 has issues with GCC's stdatomic.h and doesn't provide its own
ICC < 18 doesn't provide a compliant stdatomic.h
*/
#elif (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_ATOMICS__) ) \
|| (defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER) && !defined(__cplusplus) && (__GNUC__*100 + __GNUC_MINOR__) >= 409) \
|| (defined(__clang__) && (__clang_major__ * 100 + __clang_minor__) >= 308) \
|| (defined(__INTEL_COMPILER) && __INTEL_COMPILER >= 1800)
/* CLANG 3.5 has issues with GCC's stdatomic.h
and doesn't provide its own stdatomic.h */
#include <stdatomic.h>
/* MSYS2 has a conflict between cdefs.h which defines a _Atomic macro (if not C11)
@@ -118,32 +145,38 @@ using std::memory_order_seq_cst;
# undef _Atomic
#endif
#else
/* Non working atomic.h, nor working stdatomic.h found.
/* Non working C++ atomic header, nor working stdatomic.h found.
Write a compatible layer using mutex as slin as possible.
Supports only up to 64-bits atomic (sizeof long long to be more precise).
The locks are never properly cleared and remain active until
the end of the program.
We also assume that the call to the atomic_* interface is "clean".
We also assume that the call to the atomic_* interface is "macro clean".
*/
#include "m-mutex.h"
#else
/* The structure is quite large:
#include "m-mutex.h"
#include "m-core.h"
M_BEGIN_PROTECTED_CODE
/* _Atomic qualifier for a type (emulation).
The structure is quite large:
_val : value of the atomic type,
_zero : zero value of the atomic type (constant),
_previous: temporary value used within the mutex lock,
_lock : the mutex lock.
Support up to sizeof (long long) type.
*/
#define _Atomic(T) \
struct { \
T volatile _val; \
T _zero; \
T _previous; \
m_mutex_t _lock; \
#define _Atomic(T) \
struct { \
T volatile _val; \
T _zero; \
T _previous; \
m_mutex_t _lock; \
}
/* Even if memory order is defined, only the strongest constraint is used */
/* Define the supported memory order.
Even if memory order is defined, only the strongest constraint is used */
typedef enum {
memory_order_relaxed,
memory_order_consume,
@@ -184,76 +217,96 @@ typedef _Atomic(ptrdiff_t) atomic_ptrdiff_t;
#endif
/* Detect if stdint.h was included */
#if (defined (INTMAX_C) && defined (UINTMAX_C) && !defined(__cplusplus)) || \
defined (_STDINT_H) || defined (_STDINT_H_) || defined (_STDINT) || \
#if (defined (INTMAX_C) && defined (UINTMAX_C) && !defined(__cplusplus)) || \
defined (_STDINT_H) || defined (_STDINT_H_) || defined (_STDINT) || \
defined (_SYS_STDINT_H_)
/* Define additional atomic types */
typedef _Atomic(intmax_t) atomic_intmax_t;
typedef _Atomic(uintmax_t) atomic_uintmax_t;
#endif
/* Unlock the mutex and return the given value */
/* (INTERNAL) Unlock the mutex and return the given value */
static inline long long atomic_fetch_unlock (m_mutex_t *lock, long long val)
{
m_mutex_unlock (*lock);
return val;
}
/* This is the heart of the wrapper:
/* (INTERNAL) This is the heart of the wrapper:
lock the atomic value, read it and returns the value.
In order to avoid any compiler extension, we need to transform the
atomic type into 'long long' then convert it back to its value.
This is because _previous can't be read after the lock, and we can't
generate temporary variable within a macro.
The trick is computing _val - _zero within the lock, then
returns retvalue + _zero after the lock.
returns retvalue + _zero after the release of the lock.
*/
#define atomic_fetch_op(ptr, val, op) \
(m_mutex_lock((ptr)->_lock), \
(ptr)->_previous = (ptr)->_val, \
(ptr)->_val op (val), \
atomic_fetch_unlock(&(ptr)->_lock, (ptr)->_previous-(ptr)->_zero)+(ptr)->_zero)
#define atomic_fetch_op(ptr, val, op) \
(m_mutex_lock((ptr)->_lock), \
(ptr)->_previous = (ptr)->_val, \
(ptr)->_val op (val), \
atomic_fetch_unlock(&(ptr)->_lock, (long long)((ptr)->_previous-(ptr)->_zero))+(ptr)->_zero)
/* Perform an atomic add (EMULATION) */
#define atomic_fetch_add(ptr, val) atomic_fetch_op(ptr, val, +=)
/* Perform an atomic sub (EMULATION) */
#define atomic_fetch_sub(ptr, val) atomic_fetch_op(ptr, val, -=)
/* Perform an atomic or (EMULATION) */
#define atomic_fetch_or(ptr, val) atomic_fetch_op(ptr, val, |=)
/* Perform an atomic xor (EMULATION) */
#define atomic_fetch_xor(ptr, val) atomic_fetch_op(ptr, val, ^=)
/* Perform an atomic and (EMULATION) */
#define atomic_fetch_and(ptr, val) atomic_fetch_op(ptr, val, &=)
/* Perform an atomic exchange (EMULATION) */
#define atomic_exchange(ptr, val) atomic_fetch_op(ptr, val, =)
/* Initialize an atomic GLOBAL variable */
#define ATOMIC_VAR_INIT(val) { val, 0, 0, M_MUTEXI_INIT_VALUE }
#define atomic_init(ptr, val) \
/* Initialize an atomic variable */
#define atomic_init(ptr, val) \
(m_mutex_init((ptr)->_lock), (ptr)->_val = val, (ptr)->_zero = 0)
#define atomic_load_lock(ptr) \
(m_mutex_lock((ptr)->_lock), \
(ptr)->_previous = (ptr)->_val, \
atomic_fetch_unlock(&(ptr)->_lock, (ptr)->_previous-(ptr)->_zero)+(ptr)->_zero)
/* (INTERNAL) Load an atomic variable within a lock
(needed for variable greater than CPU atomic size) */
#define atomic_load_lock(ptr) \
(m_mutex_lock((ptr)->_lock), \
(ptr)->_previous = (ptr)->_val, \
atomic_fetch_unlock(&(ptr)->_lock, (long long) ((ptr)->_previous-(ptr)->_zero))+(ptr)->_zero)
#define atomic_store_lock(ptr, val) \
(m_mutex_lock((ptr)->_lock), \
(ptr)->_val = (val), \
/* (INTERNAL) Store an atomic variable within a lock
(needed for variable greater than CPU atomic size) */
#define atomic_store_lock(ptr, val) \
(m_mutex_lock((ptr)->_lock), \
(ptr)->_val = (val), \
m_mutex_unlock((ptr)->_lock))
#define atomic_load(ptr) \
( sizeof ((ptr)->_val) <= ATOMICI_MIN_RW_SIZE \
? (ptr)->_val \
/* Atomic load of a variable (EMULATION)
If the atomic type size is not greater than the CPU atomic size,
we can perform a direct read of the variable (much faster) */
#define atomic_load(ptr) \
( sizeof ((ptr)->_val) <= ATOMICI_MIN_RW_SIZE \
? (ptr)->_val \
: atomic_load_lock(ptr))
#define atomic_store(ptr, val) do { \
if ( sizeof ((ptr)->_val) <= ATOMICI_MIN_RW_SIZE) { \
(ptr)->_val = (val); \
} else { \
long long _offset = (val) - (ptr)->_zero; \
atomic_store_lock(ptr, (ptr)->_zero + _offset); \
} \
/* Atomic store of a variable (EMULATION)
If the atomic type size is not greater than the CPU atomic size,
we can perform a direct write of the variable (much faster) */
#define atomic_store(ptr, val) do { \
if ( sizeof ((ptr)->_val) <= ATOMICI_MIN_RW_SIZE) { \
(ptr)->_val = (val); \
} else { \
long long _offset = (long long) ((val) - (ptr)->_zero); \
atomic_store_lock(ptr, (ptr)->_zero + _offset); \
} \
} while (0)
#define atomic_compare_exchange_strong(ptr, exp, val) \
(m_mutex_lock((ptr)->_lock), \
atomic_fetch_unlock(&(ptr)->_lock, \
(ptr)->_val == *(exp) \
? ((ptr)->_val = (val), true) \
/* Perform a CAS (Compare and swap) operation (EMULATION) */
#define atomic_compare_exchange_strong(ptr, exp, val) \
(m_mutex_lock((ptr)->_lock), \
atomic_fetch_unlock(&(ptr)->_lock, \
(ptr)->_val == *(exp) \
? ((ptr)->_val = (val), true) \
: (*(exp) = (ptr)->_val, false)))
@@ -273,7 +326,9 @@ static inline long long atomic_fetch_unlock (m_mutex_t *lock, long long val)
#define atomic_compare_exchange_weak_explicit(ptr, exp, val, mem1, mem2) atomic_compare_exchange_strong(ptr, exp, val)
#define atomic_compare_exchange_weak(ptr, exp, val) atomic_compare_exchange_strong(ptr, exp, val)
/* TODO: Missing atomic_flag. Problem: it needs to be lock free! */
/* TODO: Missing atomic_flag. Problem: it is supposed to be lock free! */
M_END_PROTECTED_CODE
#endif
+405 -256
View File
File diff suppressed because it is too large. Load diff
+1368 -1190
View File
File diff suppressed because it is too large. Load diff
+1154 -930
View File
File diff suppressed because it is too large. Load diff
+480 -475
View File
File diff suppressed because it is too large. Load diff
+811 -686
View File
File diff suppressed because it is too large. Load diff
+1803 -613
View File
File diff suppressed because it is too large. Load diff
+1048 -928
View File
File diff suppressed because it is too large. Load diff
+1800 -1630
View File
File diff suppressed because it is too large. Load diff
+399
View File
@@ -0,0 +1,399 @@
/*
* M*LIB - Function Object module
*
* Copyright (c) 2017-2021, Patrick Pelissier
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* + Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* + Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef MSTARLIB_FUNCOBJ_H
#define MSTARLIB_FUNCOBJ_H
#include "m-core.h"
/* Define a function object interface of name 'name'
* with a function like retcode, type of param1, type of param 2, ...
* USAGE:
* FUNC_OBJ_ITF_DEF(name, retcode type, type of param1, type of param 2, ...)
*/
#define FUNC_OBJ_ITF_DEF(name, ...) \
FUNC_OBJ_ITF_DEF_AS(name, M_C(name,_t), __VA_ARGS__)
/* Define a function object interface of name 'name'
* as the given name name_t
* USAGE:
* FUNC_OBJ_ITF_DEF_AS(name, name_t, retcode type, type of param1, type of param 2, ...)
*/
#define FUNC_OBJ_ITF_DEF_AS(name, name_t, ...) \
M_BEGIN_PROTECTED_CODE \
M_IF_NARGS_EQ1(__VA_ARGS__)(M_FUNC0BJ_ITF_NO_PARAM_DEF, M_FUNC0BJ_ITF_PARAM_DEF)(name, name_t, __VA_ARGS__) \
M_END_PROTECTED_CODE
/* Define a function object instance of name 'name' based on the interface 'base_name'
* The function is defined using:
* - the prototype of the inherited interface
* - the parameters of the function are named as per the list param_list
* - the core of the function given in 'callback_core'
* - optionals member attributes of the function object can be defined after the core
* (just like for tuple & variant: (name, type [, oplist])
*
* In the core of the function, parameters are accessible just like a normal function.
* A special variable named 'self' that refers to the function object itself
* can be used to access member attributes using the syntax self->param1, ...
*
* There shall be **exactly** the same number of parameters in 'param_list' than
* the number of parameters of the interface 'base_name'
*
* USAGE/EXAMPLE:
* FUNC_OBJ_INS_DEF(name, base_name, (param1, ...), { return param1 * self->member1 }, (member1, int), ...)
*/
#define FUNC_OBJ_INS_DEF(name, base_name, param_list, ...) \
FUNC_OBJ_INS_DEF_AS(name, M_C(name,_t), base_name, param_list, __VA_ARGS__)
/* Define a function object instance of name 'name' based on the interface 'base_name'
* as the given name name_t.
* See FUNC_OBJ_INS_DEF for additional details.
*
* USAGE/EXAMPLE:
* FUNC_OBJ_INS_DEF_AS(name, name_t, base_name, (param1, ...), { return param1 * self->member1 }, (member1, int), ...)
*/
#define FUNC_OBJ_INS_DEF_AS(name, name_t, base_name, param_list, ...) \
M_BEGIN_PROTECTED_CODE \
M_IF_NARGS_EQ1(__VA_ARGS__)(M_FUNC0BJ_INS_NO_ATTR_DEF, M_FUNC0BJ_INS_ATTR_DEF)(name, name_t, base_name, param_list, __VA_ARGS__) \
M_END_PROTECTED_CODE
/* OPLIST of the instanced function object
* USAGE:
* FUNC_OBJ_INS_OPLIST(name, oplist of the attr1, ...)
*/
#define FUNC_OBJ_INS_OPLIST(...) \
M_IF_NARGS_EQ1(__VA_ARGS__)(M_FUNC0BJ_INS_NO_ATTR_OPLIST, M_FUNC0BJ_INS_ATTR_OPLIST_P1)( __VA_ARGS__)
/********************************************************************************/
/********************************** INTERNAL ************************************/
/********************************************************************************/
/* To be used by M_IF_FUNCOBJ macro defined in m-core.
NOTE: It is reversed (0 instead of 1) so that it can be used in M_IF reliabely.
*/
#define M_FUNCOBJ_IS_NOT_DEFINED 0
/* Design Constraints:
* callback SHALL be the first member of the structures in all the definitions.
*
* Structure definitions are specialized in function of the presence or not
* of parameters and/or attributes
* FIXME: How to factorize reasonnably well between the definitions?
*/
/* Specialization of the OPLIST in function if there is at least one member or not */
#define M_FUNC0BJ_INS_NO_ATTR_OPLIST(name) ( \
NAME(name), \
TYPE(M_C(name, _ct)), \
CLEAR(M_C(name, _clear)), \
INIT(M_C(name,_init)) \
)
/* Validate the oplist before going further */
#define M_FUNC0BJ_INS_ATTR_OPLIST_P1(name, ...) \
M_IF(M_REDUCE(M_OPLIST_P, M_AND, __VA_ARGS__))(M_FUNC0BJ_INS_ATTR_OPLIST_P3, M_FUNC0BJ_INS_ATTR_OPLIST_FAILURE)(name, __VA_ARGS__)
/* Prepare a clean compilation failure */
#define M_FUNC0BJ_INS_ATTR_OPLIST_FAILURE(name, ...) \
((M_LIB_ERROR(ONE_ARGUMENT_OF_FUNC_OBJ_INS_OPLIST_IS_NOT_AN_OPLIST, name, __VA_ARGS__)))
/* Define the oplist of the instance */
#define M_FUNC0BJ_INS_ATTR_OPLIST_P3(name, ...) ( \
NAME(name), \
TYPE(M_C(name, _ct)), \
INIT_WITH(M_C(name, _init_with)), \
CLEAR(M_C(name, _clear)), \
M_IF_METHOD_ALL(INIT, __VA_ARGS__)(INIT(M_C(name,_init)),), \
PROPERTIES(( LET_AS_INIT_WITH(1) )) \
)
/* Specialization of the definition a function object interface of name 'name'
* with a function like "retcode (void)" that doesn't have any input parameters.
* Define the following types to be used by instance:
* - M_C(name, _retcode_ct): internal type of the return code
* - M_C(name, _callback_ct): internal type of the callback.
* - M_C(name, _ct): synonym of main type used by oplist.
*/
#define M_FUNC0BJ_ITF_NO_PARAM_DEF(name, interface_t, retcode) \
\
/* Forward declaration */ \
struct M_C(name, _s); \
\
/* Internal type for instance */ \
typedef retcode M_C(name, _retcode_ct); \
/* No parameters to the callback */ \
typedef retcode(*M_C(name, _callback_ct))(struct M_C(name, _s) *); \
\
typedef struct M_C(name, _s) { \
M_C(name, _callback_ct) callback; \
} interface_t[1]; \
\
/* Internal type for oplist & instance */ \
typedef interface_t M_C(name, _ct); \
\
static inline retcode \
M_C(name, _call)(interface_t funcobj) \
{ \
M_IF(M_KEYWORD_P(void, retcode)) ( /* nothing */,return) \
funcobj->callback(funcobj); \
}
/* Specialization of the definition a function object interface of name 'name'
* with a function like retcode, type of param1, type of param 2, ...
* with mandatory input parameters.
* Define the following types to be used by instance:
* - M_C(name, _retcode_ct): internal type of the return code
* - M_C(name, _callback_ct): internal type of the callback.
* - M_C4(name, _param_, num, _ct) for each parameter defined
* - M_C(name, _ct): synonym of main type used by oplist.
*/
#define M_FUNC0BJ_ITF_PARAM_DEF(name, interface_t, retcode, ...) \
\
/* Forward declaration */ \
struct M_C(name, _s); \
\
/* Internal types for instance */ \
typedef retcode M_C(name, _retcode_ct); \
/* Define types for all parameters */ \
M_MAP3(M_FUNC0BJ_BASE_TYPE, name, __VA_ARGS__) \
/* Define callback type with all parameters */ \
typedef retcode(*M_C(name, _callback_ct))(struct M_C(name, _s) *, __VA_ARGS__); \
\
typedef struct M_C(name, _s) { \
M_C(name, _callback_ct) callback; \
} interface_t[1]; \
\
/* Internal type for oplist & instance */ \
typedef interface_t M_C(name, _ct); \
\
static inline retcode \
M_C(name, _call)(interface_t funcobj \
M_MAP3(M_FUNC0BJ_BASE_ARGLIST, name, __VA_ARGS__) ) \
{ \
/* If the retcode is 'void', don't return the value of the callback */ \
M_IF(M_KEYWORD_P(void, retcode)) ( /* nothing */,return) \
funcobj->callback(funcobj M_MAP3(M_FUNC0BJ_BASE_ARGCALL, name, __VA_ARGS__) ); \
}
/* Specialization of the definition a function object instance of name 'name'
* with no member attribute.
*/
#define M_FUNC0BJ_INS_NO_ATTR_DEF(name, instance_t, base_name, param_list, callback_core) \
typedef struct M_C(name, _s) { \
M_C(base_name, _callback_ct) callback; \
} instance_t[1]; \
\
/* Internal type for oplist */ \
typedef instance_t M_C(name, _ct); \
\
static inline M_C(base_name, _retcode_ct) \
M_C(name, _callback)(M_C(base_name, _ct) _self \
M_IF_EMPTY(M_OPFLAT param_list)( \
/* No param */, \
M_MAP3(M_FUNC0BJ_INS_ARGLIST, base_name, M_OPFLAT param_list) \
) \
) \
{ \
struct M_C(name, _s) *self = (struct M_C(name, _s) *)_self; \
(void) self; /* maybe unused */ \
callback_core; \
} \
\
static inline void \
M_C(name, _init_with)(instance_t obj) \
{ \
obj->callback = M_C(name, _callback); \
} \
\
static inline void \
M_C(name, _clear)(instance_t obj) \
{ \
(void) obj; /* nothing to do */ \
} \
\
static inline struct M_C(base_name, _s) * \
M_C(name, _as_interface)(instance_t obj) \
{ \
return (struct M_C(base_name, _s) *) obj; \
} \
\
static inline void \
M_C(name, _init)(instance_t obj) \
{ \
obj->callback = M_C(name, _callback); \
} \
/* Specialization of the definition a function object instance of name 'name'
* with mandatory member attribute.
* First inject oplist in member attributes.
*/
#define M_FUNC0BJ_INS_ATTR_DEF(name, instance_t, base_name, param_list, callback_core, ...) \
M_FUNC0BJ_INS_ATTR_DEF_P2(name, instance_t, base_name, param_list, callback_core, M_FUNC0BJ_INJECT_GLOBAL(__VA_ARGS__) )
/* Inject the oplist within the list of arguments */
#define M_FUNC0BJ_INJECT_GLOBAL(...) \
M_MAP_C(M_FUNC0BJ_INJECT_OPLIST_A, __VA_ARGS__)
/* Transform (x, type) into (x, type, oplist) if there is global registered oplist
or (x, type, M_DEFAULT_OPLIST) if there is no global one,
or keep (x, type, oplist) if oplist was already present */
#define M_FUNC0BJ_INJECT_OPLIST_A( duo_or_trio ) \
M_FUNC0BJ_INJECT_OPLIST_B duo_or_trio
#define M_FUNC0BJ_INJECT_OPLIST_B( f, ... ) \
M_IF_NARGS_EQ1(__VA_ARGS__)( (f, __VA_ARGS__, M_GLOBAL_OPLIST_OR_DEF(__VA_ARGS__)()), (f, __VA_ARGS__) )
// Test if all third argument of all arguments is an oplist
#define M_FUNC0BJ_IF_ALL_OPLIST(...) \
M_IF(M_REDUCE(M_FUNC0BJ_IS_OPLIST_P, M_AND, __VA_ARGS__))
// Test if the third argument is an oplist. a is a trio (name, type, oplist)
#define M_FUNC0BJ_IS_OPLIST_P(a) \
M_OPLIST_P(M_RET_ARG3 a)
/* Validate the oplist before going further */
#define M_FUNC0BJ_INS_ATTR_DEF_P2(name, instance_t, base_name, param_list, callback_core, ...) \
M_FUNC0BJ_IF_ALL_OPLIST(__VA_ARGS__)(M_FUNC0BJ_INS_ATTR_DEF_P3, M_FUNC0BJ_INS_ATTR_DEF_FAILURE)(name, instance_t, base_name, param_list, callback_core, __VA_ARGS__)
/* Stop processing with a compilation failure */
#define M_FUNC0BJ_INS_ATTR_DEF_FAILURE(name, instance_t, base_name, param_list, callback_core, ...) \
M_STATIC_FAILURE(M_LIB_NOT_AN_OPLIST, "(FUNC_OBJ_INS_DEF): at least one of the given argument is not a valid oplist: " #__VA_ARGS__)
/* Expand the Function Object with members */
#define M_FUNC0BJ_INS_ATTR_DEF_P3(name, instance_t, base_name, param_list, callback_core, ...) \
typedef struct M_C(name, _s) { \
/* Callback is the mandatory first argument */ \
M_C(base_name, _callback_ct) callback; \
/* All the member attribute of the Function Object */ \
M_MAP(M_FUNC0BJ_INS_ATTR_STRUCT, __VA_ARGS__) \
} instance_t[1]; \
\
/* Internal type for oplist */ \
typedef instance_t M_C(name, _ct); \
\
M_FUNC0BJ_CONTROL_ALL_OPLIST(name, __VA_ARGS__) \
\
static inline M_C(base_name, _retcode_ct) \
M_C(name, _callback)(M_C(base_name, _ct) _self \
M_IF_EMPTY(M_OPFLAT param_list)( \
/* No param */, \
M_MAP3(M_FUNC0BJ_INS_ARGLIST, base_name, M_OPFLAT param_list) \
) \
) \
{ \
struct M_C(name, _s) *self = (struct M_C(name, _s) *)(void*)_self; \
(void) self; /* maybe unused */ \
callback_core; \
} \
\
static inline void \
M_C(name, _init_with)(instance_t obj M_MAP(M_FUNC0BJ_INS_ATTR_LIST, __VA_ARGS__)) \
{ \
obj->callback = M_C(name, _callback); \
M_MAP(M_FUNC0BJ_INS_ATTR_INIT_SET, __VA_ARGS__); \
} \
\
static inline void \
M_C(name, _clear)(instance_t obj) \
{ \
M_MAP(M_FUNC0BJ_INS_ATTR_CLEAR, __VA_ARGS__); \
} \
\
static inline struct M_C(base_name, _s) * \
M_C(name, _as_interface)(instance_t obj) \
{ \
return (struct M_C(base_name, _s) *) obj; \
} \
\
M_IF(M_FUNC0BJ_TEST_METHOD_P(INIT, __VA_ARGS)) \
( \
static inline void \
M_C(name, _init)(instance_t obj) \
{ \
obj->callback = M_C(name, _callback); \
M_MAP(M_FUNC0BJ_INS_ATTR_INIT, __VA_ARGS__); \
} \
, /* END OF INIT METHOD */ ) \
/* Define a numbered type of a parameter of the callback*/
#define M_FUNC0BJ_BASE_TYPE(name, num, type) \
typedef type M_C4(name, _param_, num, _ct);
/* Define a list of the type of arguments for a function definition */
#define M_FUNC0BJ_BASE_ARGLIST(name, num, type) \
M_DEFERRED_COMMA type M_C(param_, num)
/* Define a list of arguments for a function call */
#define M_FUNC0BJ_BASE_ARGCALL(name, num, type) \
M_DEFERRED_COMMA M_C(param_, num)
/* Helper macros */
/* arg = (name, type [, oplist]) */
#define M_FUNC0BJ_INS_ATTR_STRUCT(arg) \
M_RET_ARG2 arg M_RET_ARG1 arg;
#define M_FUNC0BJ_INS_ATTR_LIST(arg) \
M_DEFERRED_COMMA M_RET_ARG2 arg const M_RET_ARG1 arg
#define M_FUNC0BJ_INS_ATTR_INIT(arg) \
M_CALL_INIT(M_RET_ARG3 arg, obj -> M_RET_ARG1 arg);
#define M_FUNC0BJ_INS_ATTR_INIT_SET(arg) \
M_CALL_INIT_SET(M_RET_ARG3 arg, obj -> M_RET_ARG1 arg, M_RET_ARG1 arg);
#define M_FUNC0BJ_INS_ATTR_CLEAR(arg) \
M_CALL_CLEAR(M_RET_ARG3 arg, obj -> M_RET_ARG1 arg);
/* Define the list of arguments of the instance of the callback */
#define M_FUNC0BJ_INS_ARGLIST(name, num, param) \
M_DEFERRED_COMMA M_C4(name, _param_, num, _ct) param
/* Macros for testing for a method presence in all the attributes */
#define M_FUNC0BJ_TEST_METHOD2_P(method, op) \
M_TEST_METHOD_P(method, op)
#define M_FUNC0BJ_TEST_METHOD1_P(method, arg) \
M_APPLY(M_FUNC0BJ_TEST_METHOD2_P, method, M_RET_ARG3 arg)
#define M_FUNC0BJ_TEST_METHOD_P(method, ...) \
M_IF(M_REDUCE2(M_FUNC0BJ_TEST_METHOD1_P, M_AND, method, __VA_ARGS__))
/* Macro for checking compatible type and oplist for all the attributes */
#define M_FUNC0BJ_CONTROL_ALL_OPLIST(name, ...) \
M_MAP2(M_FUNC0BJ_CONTROL_OPLIST, name, __VA_ARGS__)
#define M_FUNC0BJ_CONTROL_OPLIST(name, a) \
M_CHECK_COMPATIBLE_OPLIST(name, M_RET_ARG1 a, M_RET_ARG2 a, M_RET_ARG3 a)
#endif
+111 -84
View File
@@ -1,7 +1,7 @@
/*
* M*LIB - GENINT module
* M*LIB - Integer Generator (GENINT) module
*
* Copyright (c) 2017-2019, Patrick Pelissier
* Copyright (c) 2017-2021, Patrick Pelissier
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
@@ -28,72 +28,89 @@
#include "m-core.h"
#include "m-atomic.h"
/* GENINT is a container of integers with the following properties:
M_BEGIN_PROTECTED_CODE
/* GENINT is an internal container providing unique integers.
It has the following properties:
- it stores integer from [0..N) (N is fixed).
- an integer can have only one occurrence in the container.
- you can atomically push in / pop out integer from this container
provided that they were not already in the container.
provided that it is not already in the container.
- there are no order (like FIFO or stack)
This can be used to map integers to index of resources in a table.
At most we can support N = GENINT_LIMBSIZE * GENINT_LIMBSIZE >= 4096
due to the master trick. For the typical usage of this container
At most we can support N = 32*64 = 2048 with the master limb usage.
For the typical usage of this container
(mapping hardware or software limited resources), this should be
enough.
*/
// TO DO: We may want a specialization with constant N value.
// Define the limb size
typedef unsigned long long genint_limb_t;
// Define the limb size used by genint
typedef unsigned long long genint_limb_ct;
/* Define a generator of unique integer (Lock Free) */
typedef struct genint_s {
unsigned int n; // size of the container
unsigned int max; // number of allocated limb - 1
genint_limb_t mask0; // mask of the last limb
genint_limb_t mask_master; // mask of master
genint_limb_ct mask0; // mask of the last limb (constant)
genint_limb_ct mask_master; // mask of the master limb that controls others (constant)
atomic_ullong master; // master bitfield (which informs if a limb is full or not)
atomic_ullong *data; // the bitfield which informs if an integer
atomic_ullong *data; // the bitfield which informs if an integer is used or not
} genint_t[1];
// Define the max supported value
#define GENINT_MAX_ALLOC (GENINT_LIMBSIZE * (GENINT_LIMBSIZE - GENINT_ABA_CPT))
// Define the max absolute supported value. It should be 2048 on most implementations.
#define GENINT_MAX_ALLOC (M_GEN1NT_LIMBSIZE * (M_GEN1NT_LIMBSIZE - M_GEN1NT_ABA_CPT))
// Define the size of a limb in bits.
#define GENINT_LIMBSIZE (sizeof(genint_limb_t) * CHAR_BIT)
#define M_GEN1NT_LIMBSIZE ((unsigned)(sizeof(genint_limb_ct) * CHAR_BIT))
#define GENINT_CONTRACT(s) do { \
assert (s != NULL); \
assert (s->n > 0 && s->n <= GENINT_MAX_ALLOC); \
assert ((s->max+1) * GENINT_LIMBSIZE >= s->n); \
assert (s->data != NULL); \
// Define the contract of a genint
#define M_GEN1NT_CONTRACT(s) do { \
M_ASSERT (s != NULL); \
M_ASSERT (s->n > 0 && s->n <= GENINT_MAX_ALLOC); \
M_ASSERT ((s->max+1) * M_GEN1NT_LIMBSIZE >= s->n); \
M_ASSERT (s->data != NULL); \
} while (0)
#define GENINT_ONE ((genint_limb_t)1)
// Define the limb one
#define M_GEN1NT_ONE ((genint_limb_ct)1)
// Value returned in case of error.
#define GENINT_ERROR (-1U)
#define M_GEN1NT_FULL_MASK ULLONG_MAX
// 32 bits of master are kept for handling the ABA problems.
#define GENINT_ABA_CPT 32
#define GENINT_ABA_CPT_T uint32_t
// Value returned in case of error (not integer available).
#define GENINT_ERROR (UINT_MAX)
// Set the bit i of master
#define GENINT_MASTER_SET(master, i) \
((((master)& (~((GENINT_ONE<< GENINT_ABA_CPT)-1))) | (GENINT_ONE << (GENINT_LIMBSIZE - 1 - i))) \
|((GENINT_ABA_CPT_T)((master) + 1)))
/* 32 bits of the master mask are kept for handling the ABA problem.
* NOTE: May be too much. 16 bits should be more than enough. TBC
*/
#define M_GEN1NT_ABA_CPT 32
#define M_GEN1NT_ABA_CPT_T uint32_t
// Reset the bit i of master
#define GENINT_MASTER_RESET(master, i) \
(((master) & (~((GENINT_ONE<< GENINT_ABA_CPT)-1)) & ~(GENINT_ONE << (GENINT_LIMBSIZE - 1 - i))) \
|((GENINT_ABA_CPT_T)((master) + 1)))
// Set the bit 'i' of the master limb, and increase ABA counter.
#define M_GEN1NT_MASTER_SET(master, i) \
((((master)& (~((M_GEN1NT_ONE<< M_GEN1NT_ABA_CPT)-1))) | (M_GEN1NT_ONE << (M_GEN1NT_LIMBSIZE - 1 - i))) \
|((M_GEN1NT_ABA_CPT_T)((master) + 1)))
static inline void genint_init(genint_t s, unsigned int n)
// Reset the bit i of the master limb, and increase ABA counter.
#define M_GEN1NT_MASTER_RESET(master, i) \
(((master) & (~((M_GEN1NT_ONE<< M_GEN1NT_ABA_CPT)-1)) & ~(M_GEN1NT_ONE << (M_GEN1NT_LIMBSIZE - 1 - i))) \
|((M_GEN1NT_ABA_CPT_T)((master) + 1)))
/* Initialize an integer generator (CONSTRUCTOR).
* Initialy, the container is full of all the integers up to 'n-1'
* The typical sequence is to initialize the container, and pop
* the integer from it. Each pop integer is **unique** for all threads,
* meaning it can be used to index global unique resources shared
* for all threads.
*/
static inline void
genint_init(genint_t s, unsigned int n)
{
assert (s != NULL && n > 0 && n <= GENINT_MAX_ALLOC);
const size_t alloc = (n + GENINT_LIMBSIZE - 1) / GENINT_LIMBSIZE;
const unsigned int index = n % GENINT_LIMBSIZE;
M_ASSERT (s != NULL && n > 0 && n <= GENINT_MAX_ALLOC);
const size_t alloc = (n + M_GEN1NT_LIMBSIZE - 1) / M_GEN1NT_LIMBSIZE;
const unsigned int index = n % M_GEN1NT_LIMBSIZE;
atomic_ullong *ptr = M_MEMORY_REALLOC (atomic_ullong, NULL, alloc);
if (M_UNLIKELY (ptr == NULL)) {
M_MEMORY_FULL(alloc);
@@ -101,68 +118,74 @@ static inline void genint_init(genint_t s, unsigned int n)
}
s->n = n;
s->data = ptr;
s->max = alloc-1;
s->mask0 = (index == 0) ? -GENINT_ONE : ~((GENINT_ONE<<(GENINT_LIMBSIZE-index))-1);
s->mask_master = (((GENINT_ONE << alloc) - 1) << (GENINT_LIMBSIZE-alloc)) >> GENINT_ABA_CPT;
atomic_init (&s->master, (genint_limb_t)0);
s->max = (unsigned int) (alloc-1);
s->mask0 = (index == 0) ? M_GEN1NT_FULL_MASK : ~((M_GEN1NT_ONE<<(M_GEN1NT_LIMBSIZE-index))-1);
s->mask_master = (((M_GEN1NT_ONE << alloc) - 1) << (M_GEN1NT_LIMBSIZE-alloc)) >> M_GEN1NT_ABA_CPT;
atomic_init (&s->master, (genint_limb_ct)0);
for(unsigned int i = 0; i < alloc; i++)
atomic_init(&s->data[i], (genint_limb_t)0);
GENINT_CONTRACT(s);
atomic_init(&s->data[i], (genint_limb_ct)0);
M_GEN1NT_CONTRACT(s);
}
static inline void genint_clear(genint_t s)
/* Clear an integer generator (Destructor) */
static inline void
genint_clear(genint_t s)
{
GENINT_CONTRACT(s);
M_GEN1NT_CONTRACT(s);
M_MEMORY_FREE(s->data);
s->data = NULL;
}
static inline size_t genint_size(genint_t s)
/* Return the maximum integer that the generator will provide */
static inline size_t
genint_size(genint_t s)
{
GENINT_CONTRACT(s);
M_GEN1NT_CONTRACT(s);
return s->n;
}
// For a typical case, the amortized cost is one CAS per pop.
static inline unsigned int genint_pop(genint_t s)
/* Get an unique integer from the integer generator.
* NOTE: For a typical case, the amortized cost is one CAS per pop. */
static inline unsigned int
genint_pop(genint_t s)
{
GENINT_CONTRACT(s);
M_GEN1NT_CONTRACT(s);
// First read master to see which limb is not full.
genint_limb_t master = atomic_load(&s->master);
genint_limb_ct master = atomic_load(&s->master);
// While master is not full
while ((master >> GENINT_ABA_CPT) != s->mask_master) {
while ((master >> M_GEN1NT_ABA_CPT) != s->mask_master) {
// Let's get the index i of the first not full limb according to master.
unsigned int i = m_core_clz64(~master);
assert (i < GENINT_LIMBSIZE);
M_ASSERT (i < M_GEN1NT_LIMBSIZE);
// Let's compute the mask of this limb representing the limb as being full
genint_limb_t mask = s->mask0;
mask = (i == s->max) ? mask : -GENINT_ONE;
genint_limb_ct mask = s->mask0;
mask = (i == s->max) ? mask : M_GEN1NT_FULL_MASK;
unsigned int bit;
// Let's load this limb,
genint_limb_t next, org = atomic_load(&s->data[i]);
genint_limb_ct next, org = atomic_load(&s->data[i]);
do {
// If it is now full, we have been preempted by another.
if (M_UNLIKELY (org == mask))
goto next_element;
assert (org != -GENINT_ONE);
M_ASSERT (org != M_GEN1NT_FULL_MASK);
// At least one bit is free in the limb. Find one.
bit = GENINT_LIMBSIZE - 1 - m_core_clz64(~org);
assert (bit < GENINT_LIMBSIZE);
assert ((org & (GENINT_ONE<<bit)) == 0);
assert (i * GENINT_LIMBSIZE + GENINT_LIMBSIZE - 1 - bit < s->n);
bit = M_GEN1NT_LIMBSIZE - 1 - m_core_clz64(~org);
M_ASSERT (bit < M_GEN1NT_LIMBSIZE);
M_ASSERT ((org & (M_GEN1NT_ONE<<bit)) == 0);
M_ASSERT (i * M_GEN1NT_LIMBSIZE + M_GEN1NT_LIMBSIZE - 1 - bit < s->n);
// Set the integer as being used.
next = org | (GENINT_ONE << bit);
next = org | (M_GEN1NT_ONE << bit);
// Try to reserve the integer
} while (!atomic_compare_exchange_weak (&s->data[i], &org, next));
// We have reserved the integer.
// If the limb is now full, try to update master
if (M_UNLIKELY(next == mask)) {
while (true) {
genint_limb_t newMaster;
genint_limb_ct newMaster;
if (next == mask) {
newMaster = GENINT_MASTER_SET(master, i);
newMaster = M_GEN1NT_MASTER_SET(master, i);
} else {
newMaster = GENINT_MASTER_RESET(master, i);
newMaster = M_GEN1NT_MASTER_RESET(master, i);
}
if (atomic_compare_exchange_weak (&s->master, &master, newMaster))
break;
@@ -171,44 +194,46 @@ static inline unsigned int genint_pop(genint_t s)
}
}
// Return the new number
GENINT_CONTRACT(s);
return i * GENINT_LIMBSIZE + GENINT_LIMBSIZE - 1 - bit;
M_GEN1NT_CONTRACT(s);
return i * M_GEN1NT_LIMBSIZE + M_GEN1NT_LIMBSIZE - 1 - bit;
next_element:
// Reload master
master = atomic_load(&s->master);
}
GENINT_CONTRACT(s);
M_GEN1NT_CONTRACT(s);
return GENINT_ERROR; // No more resource available
}
// For a typical case, the amortized cost is one CAS per pop.
static inline void genint_push(genint_t s, unsigned int n)
/* Restore a used integer in the integer generator.
* NOTE: For a typical case, the amortized cost is one CAS per pop */
static inline void
genint_push(genint_t s, unsigned int n)
{
GENINT_CONTRACT(s);
assert (n < s->n);
const unsigned int i = n / GENINT_LIMBSIZE;
const unsigned int bit = GENINT_LIMBSIZE - 1 - (n % GENINT_LIMBSIZE);
genint_limb_t master = atomic_load(&s->master);
M_GEN1NT_CONTRACT(s);
M_ASSERT (n < s->n);
const unsigned int i = n / M_GEN1NT_LIMBSIZE;
const unsigned int bit = M_GEN1NT_LIMBSIZE - 1 - (n % M_GEN1NT_LIMBSIZE);
genint_limb_ct master = atomic_load(&s->master);
// Load the limb
genint_limb_t next, org = atomic_load(&s->data[i]);
genint_limb_ct next, org = atomic_load(&s->data[i]);
do {
assert ((org & (GENINT_ONE << bit)) != 0);
M_ASSERT ((org & (M_GEN1NT_ONE << bit)) != 0);
// Reset it
next = org & (~(GENINT_ONE << bit));
next = org & (~(M_GEN1NT_ONE << bit));
// Try to unreserve it.
} while (!atomic_compare_exchange_weak (&s->data[i], &org, next));
// if the limb was marked as full by master
genint_limb_t mask = s->mask0;
mask = (i == s->max) ? mask : -GENINT_ONE;
genint_limb_ct mask = s->mask0;
mask = (i == s->max) ? mask : M_GEN1NT_FULL_MASK;
if (M_UNLIKELY (next != mask)) {
// Let's compute the mask of this limb representing the limb as being full
// Let's try to update master to say that this limb is not full
while (true) {
genint_limb_t newMaster;
genint_limb_ct newMaster;
if (next == mask) {
newMaster = GENINT_MASTER_SET(master, i);
newMaster = M_GEN1NT_MASTER_SET(master, i);
} else {
newMaster = GENINT_MASTER_RESET(master, i);
newMaster = M_GEN1NT_MASTER_RESET(master, i);
}
if (atomic_compare_exchange_weak (&s->master, &master, newMaster))
break;
@@ -216,7 +241,9 @@ static inline void genint_push(genint_t s, unsigned int n)
next = atomic_load(&s->data[i]);
}
}
GENINT_CONTRACT(s);
M_GEN1NT_CONTRACT(s);
}
M_END_PROTECTED_CODE
#endif
+591 -520
View File
File diff suppressed because it is too large. Load diff
+188 -96
View File
@@ -1,7 +1,7 @@
/*
* M*LIB - INTRUSIVE SHARED PTR Module
*
* Copyright (c) 2017-2019, Patrick Pelissier
* Copyright (c) 2017-2021, Patrick Pelissier
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
@@ -28,122 +28,214 @@
#include "m-core.h"
#include "m-atomic.h"
M_BEGIN_PROTECTED_CODE
/* Define the oplist of a intrusive shared pointer.
USAGE: ISHARED_OPLIST(name [, oplist_of_the_type]) */
#define ISHARED_PTR_OPLIST(...) \
ISHAREDI_PTR_OPLIST_P1(M_IF_NARGS_EQ1(__VA_ARGS__) \
((__VA_ARGS__, M_DEFAULT_OPLIST), \
#define ISHARED_PTR_OPLIST(...) \
M_ISHAR3D_PTR_OPLIST_P1(M_IF_NARGS_EQ1(__VA_ARGS__) \
((__VA_ARGS__, M_DEFAULT_OPLIST), \
(__VA_ARGS__ )))
/* Interface to add to a structure to allow intrusive support.
name: name of the intrusive shared pointer.
type: name of the type of the structure (aka. struct test_s) - not used currently.
NOTE: There can be only one interface of this kind in a type! */
#define ISHARED_PTR_INTERFACE(name, type) \
#define ISHARED_PTR_INTERFACE(name, type) \
atomic_int M_C(name, _cpt)
/* Value of the interface field for static intialization (Uses C99 designated element). */
#define ISHARED_PTR_STATIC_DESIGNATED_INIT(name, type) \
.M_C(name, _cpt) = ATOMIC_VAR_INIT(0)
/* Value of the interface field for static intialization (Uses C89 designated element). */
#define ISHARED_PTR_STATIC_INIT(name, type) \
ATOMIC_VAR_INIT(0)
/* Define the intrusive shared pointer type and its static inline functions.
USAGE: ISHARED_PTR_DEF(name[, oplist]) */
#define ISHARED_PTR_DEF(name, ...) \
ISHAREDI_PTR_DEF_P1(M_IF_NARGS_EQ1(__VA_ARGS__) \
((name, __VA_ARGS__, M_GLOBAL_OPLIST_OR_DEF(__VA_ARGS__)() ), \
(name, __VA_ARGS__ )))
USAGE: ISHARED_PTR_DEF(name, type, [, oplist]) */
#define ISHARED_PTR_DEF(name, ...) \
ISHARED_PTR_DEF_AS(name, M_C(name,_t), __VA_ARGS__)
/* Define the intrusive shared pointer type and its static inline functions
as the name name_t
USAGE: ISHARED_PTR_DEF_AS(name, name_t, type, [, oplist]) */
#define ISHARED_PTR_DEF_AS(name, name_t, ...) \
M_BEGIN_PROTECTED_CODE \
M_ISHAR3D_PTR_DEF_P1(M_IF_NARGS_EQ1(__VA_ARGS__) \
((name, __VA_ARGS__, M_GLOBAL_OPLIST_OR_DEF(__VA_ARGS__)(), name_t ), \
(name, __VA_ARGS__ , name_t ))) \
M_END_PROTECTED_CODE
/********************************** INTERNAL ************************************/
// Deferred evaluation
#define ISHAREDI_PTR_OPLIST_P1(arg) ISHAREDI_PTR_OPLIST_P2 arg
#define M_ISHAR3D_PTR_OPLIST_P1(arg) M_ISHAR3D_PTR_OPLIST_P2 arg
/* Validation of the given oplist */
#define M_ISHAR3D_PTR_OPLIST_P2(name, oplist) \
M_IF_OPLIST(oplist)(M_ISHAR3D_PTR_OPLIST_P3, M_ISHAR3D_PTR_OPLIST_FAILURE)(name, oplist)
/* Prepare a clean compilation failure */
#define M_ISHAR3D_PTR_OPLIST_FAILURE(name, oplist) \
((M_LIB_ERROR(ARGUMENT_OF_ISHARED_PTR_OPLIST_IS_NOT_AN_OPLIST, name, oplist)))
// Define the oplist
#define ISHAREDI_PTR_OPLIST_P2(name, oplist) ( \
INIT(M_INIT_DEFAULT), \
INIT_SET(M_C(name, _init_set2) M_IPTR), \
SET(M_C(name, _set) M_IPTR), \
CLEAR(M_C(name, _clear)), \
CLEAN(M_C(name, _clean) M_IPTR), \
TYPE(M_C(name, _type_t)), \
OPLIST(oplist), \
SUBTYPE(M_C(name, _type_t)) \
,M_IF_METHOD(NEW, oplist)(NEW(M_GET_NEW oplist),) \
,M_IF_METHOD(REALLOC, oplist)(REALLOC(M_GET_REALLOC oplist),) \
,M_IF_METHOD(DEL, oplist)(DEL(M_GET_DEL oplist),) \
#define M_ISHAR3D_PTR_OPLIST_P3(name, oplist) ( \
INIT(M_INIT_DEFAULT), \
INIT_SET(API_4(M_C(name, _init_set))), \
SET(M_C(name, _set) M_IPTR), \
CLEAR(M_C(name, _clear)), \
RESET(M_C(name, _reset) M_IPTR), \
NAME(name), \
TYPE(M_C(name, _ct)), \
OPLIST(oplist), \
SUBTYPE(M_C(name, _subtype_ct)) \
,M_IF_METHOD(NEW, oplist)(NEW(M_GET_NEW oplist),) \
,M_IF_METHOD(REALLOC, oplist)(REALLOC(M_GET_REALLOC oplist),) \
,M_IF_METHOD(DEL, oplist)(DEL(M_GET_DEL oplist),) \
)
// Deferred evaluatioin
#define ISHAREDI_PTR_DEF_P1(arg) ISHAREDI_PTR_DEF_P2 arg
#define M_ISHAR3D_PTR_DEF_P1(arg) M_ISHAR3D_PTR_DEF_P2 arg
#define ISHAREDI_PTR_DEF_P2(name, type, oplist) \
\
typedef type *M_C(name,_t); \
typedef type M_C(name, _type_t); \
\
static inline M_C(name,_t) \
M_C(name, _init)(type *ptr) \
{ \
if (M_LIKELY (ptr != NULL)) \
atomic_init(&ptr->M_C(name, _cpt), 1); \
return ptr; \
} \
\
static inline M_C(name,_t) \
M_C(name, _init_set)(M_C(name,_t) shared) \
{ \
if (M_LIKELY (shared != NULL)) { \
int n = atomic_fetch_add(&(shared->M_C(name, _cpt)), 1); \
(void) n; \
} \
return shared; \
} \
\
static inline void \
M_C(name, _init_set2)(M_C(name,_t) *ptr, M_C(name,_t) shared) \
{ \
assert (ptr != NULL); \
*ptr = M_C(name, _init_set)(shared); \
} \
\
static inline M_C(name,_t) \
M_C(name, _init_new)(void) \
{ \
type *ptr = M_CALL_NEW(oplist, type); \
if (ptr == NULL) { \
M_MEMORY_FULL(sizeof(type)); \
return NULL; \
} \
M_CALL_INIT(oplist, *ptr); \
atomic_init (&ptr->M_C(name, _cpt), 1); \
return ptr; \
} \
\
static inline void \
M_C(name, _clear)(M_C(name,_t) shared) \
{ \
if (shared != NULL) { \
if (atomic_fetch_sub(&(shared->M_C(name, _cpt)), 1) == 1) { \
M_CALL_CLEAR(oplist, *shared); \
M_IF_DISABLED_METHOD(DEL, oplist)(, M_CALL_DEL(oplist, shared);) \
} \
} \
} \
\
static inline void \
M_C(name, _clean)(M_C(name,_t) *shared) \
{ \
M_C(name, _clear)(*shared); \
*shared = NULL; \
} \
\
static inline void \
M_C(name, _set)(M_C(name,_t) *ptr, M_C(name,_t)shared) \
{ \
assert (ptr != NULL); \
if (M_LIKELY (*ptr != shared)) { \
M_C(name, _clear)(*ptr); \
*ptr = M_C(name, _init_set)(shared); \
} \
} \
\
/* Validate the oplist before going further */
#define M_ISHAR3D_PTR_DEF_P2(name, type, oplist, shared_t) \
M_IF_OPLIST(oplist)(M_ISHAR3D_PTR_DEF_P3, M_ISHAR3D_PTR_DEF_FAILURE)(name, type, oplist, shared_t)
/* Stop processing with a compilation failure */
#define M_ISHAR3D_PTR_DEF_FAILURE(name, type, oplist, shared_t) \
M_STATIC_FAILURE(M_LIB_NOT_AN_OPLIST, "(ISHARED_PTR_DEF): the given argument is not a valid oplist: " #oplist)
#define M_ISHAR3D_PTR_DEF_P3(name, type, oplist, shared_t) \
\
/* The shared pointer is only a pointer to the type */ \
typedef type *shared_t; \
\
/* Define internal types for oplist */ \
typedef shared_t M_C(name, _ct); \
typedef type M_C(name, _subtype_ct); \
\
M_CHECK_COMPATIBLE_OPLIST(name, 1, type, oplist) \
\
static inline shared_t \
M_C(name, _init)(type *ptr) \
{ \
/* Initialize the type referenced by the pointer */ \
if (M_LIKELY (ptr != NULL)) { \
atomic_init(&ptr->M_C(name, _cpt), 2); \
} \
return ptr; \
} \
\
static inline shared_t \
M_C(name, _init_set)(shared_t shared) \
{ \
if (M_LIKELY (shared != NULL)) { \
int n = atomic_fetch_add(&(shared->M_C(name, _cpt)), 2); \
(void) n; \
} \
return shared; \
} \
\
M_IF_METHOD(INIT, oplist)( \
M_IF_DISABLED_METHOD(NEW, oplist) \
( \
/* This function is only for static object */ \
static inline shared_t \
M_C(name, _init_once)(type *shared) \
{ \
if (M_LIKELY (shared != NULL)) { \
/* Pretty much like atomic_add, except the first one increment by 1, others by 2 */ \
int o = atomic_load(&(shared->M_C(name, _cpt))); \
int n; \
do { \
n = o + 1 + (o != 0); \
} while (!atomic_compare_exchange_strong(&(shared->M_C(name, _cpt)), &o, n)); \
if (o == 0) { \
/* Partial initialization: _cpt is odd */ \
/* Call the INIT function once */ \
M_CALL_INIT(oplist, *shared); \
/* Finish initialization: _cpt is even */ \
atomic_fetch_add(&(shared->M_C(name, _cpt)), 1); \
} else if ( (o&1) != 0) { \
/* Not fully initialized yet: wait for initialization */ \
m_core_backoff_ct bkoff; \
m_core_backoff_init(bkoff); \
/* Wait for _cpt to be _even */ \
while ((atomic_load(&(shared->M_C(name, _cpt)))&1) != 0 ) { \
m_core_backoff_wait(bkoff); \
} \
} \
M_ASSERT( (atomic_load(&(shared->M_C(name, _cpt)))&1) == 0); \
} \
return shared; \
} \
, \
/* This function is only for dynamic object */ \
static inline shared_t \
M_C(name, _init_new)(void) \
{ \
type *ptr = M_CALL_NEW(oplist, type); \
if (ptr == NULL) { \
M_MEMORY_FULL(sizeof(type)); \
return NULL; \
} \
M_CALL_INIT(oplist, *ptr); \
atomic_init (&ptr->M_C(name, _cpt), 2); \
return ptr; \
} \
/* End of NEW */) \
, /* End of INIT */) \
\
static inline void \
M_C(name, _clear)(shared_t shared) \
{ \
if (shared != NULL) { \
if (atomic_fetch_sub(&(shared->M_C(name, _cpt)), 2) == 2) { \
M_CALL_CLEAR(oplist, *shared); \
M_IF_DISABLED_METHOD(DEL, oplist)(, M_CALL_DEL(oplist, shared);) \
} \
} \
} \
\
static inline void \
M_C(name, _clear_ptr)(shared_t *shared) \
{ \
M_ASSERT(shared != NULL); \
M_C(name, _clear)(*shared); \
*shared = NULL; \
} \
\
static inline void \
M_C(name, _reset)(shared_t *shared) \
{ \
M_C(name, _clear)(*shared); \
*shared = NULL; \
} \
\
static inline void M_ATTR_DEPRECATED \
M_C(name, _clean)(shared_t *shared) \
{ \
M_C(name, _reset)(shared); \
} \
\
static inline void \
M_C(name, _set)(shared_t *ptr, shared_t shared) \
{ \
M_ASSERT (ptr != NULL); \
if (M_LIKELY (*ptr != shared)) { \
M_C(name, _clear)(*ptr); \
*ptr = M_C(name, _init_set)(shared); \
} \
} \
\
M_END_PROTECTED_CODE
#endif
+1381 -1286
View File
File diff suppressed because it is too large. Load diff
+126 -96
View File
@@ -1,7 +1,7 @@
/*
* M*LIB - MEMPOOL module
*
* Copyright (c) 2017-2019, Patrick Pelissier
* Copyright (c) 2017-2021, Patrick Pelissier
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
@@ -37,113 +37,143 @@
*ptr = 17;
mempool_uint_free(m, ptr);
mempool_uint_clear(m); // Give back memory to system
NOTE: Can not use m-list since it may be expanded from LIST_DEF
*/
// NOTE: Can not use m-list since it may be expanded from LIST_DEF
#define MEMPOOL_DEF(name, type) \
MEMPOOL_DEF_AS(name, M_C(name,_t), type)
/* Fast Fixed Size thread unsafe allocator based on memory region.
USAGE:
MEMPOOL_DEF_AS(memppol_uint, name_t, unsigned int)
*/
#define MEMPOOL_DEF_AS(name, name_t, type) \
M_BEGIN_PROTECTED_CODE \
M_M3MPOOL_DEF_P2(name, type, name_t ) \
M_END_PROTECTED_CODE
#define MEMPOOL_DEF(name, type) \
\
typedef union M_C(name,_union_s) { \
type t; \
union M_C(name,_union_s) *next; \
} M_C(name,_union_t); \
\
typedef struct M_C(name,_segment_s) { \
unsigned int count; \
struct M_C(name,_segment_s) *next; \
M_C(name,_union_t) tab[MEMPOOL_MAX_PER_SEGMENT(type)]; \
} M_C(name,_segment_t); \
\
typedef struct M_C(name, _s) { \
M_C(name,_union_t) *free_list; \
M_C(name,_segment_t) *current_segment; \
} M_C(name,_t)[1]; \
\
static inline void \
M_C(name,_init)(M_C(name,_t) mem) \
{ \
mem->free_list = NULL; \
mem->current_segment = M_MEMORY_ALLOC(M_C(name,_segment_t)); \
if (mem->current_segment == NULL) { \
M_MEMORY_FULL(sizeof (M_C(name,_segment_t))); \
return; \
} \
mem->current_segment->next = NULL; \
mem->current_segment->count = 0; \
MEMPOOLI_CONTRACT(mem, type); \
} \
\
static inline void \
M_C(name,_clear)(M_C(name,_t) mem) \
{ \
MEMPOOLI_CONTRACT(mem, type); \
M_C(name,_segment_t) *segment = mem->current_segment; \
while (segment != NULL) { \
M_C(name,_segment_t) *next = segment->next; \
M_MEMORY_DEL (segment); \
segment = next; \
} \
/* Clean pointers to be safer */ \
mem->free_list = NULL; \
mem->current_segment = NULL; \
} \
\
static inline type * \
M_C(name,_alloc)(M_C(name,_t) mem) \
{ \
MEMPOOLI_CONTRACT(mem, type); \
M_C(name,_union_t) *ret = mem->free_list; \
if (ret != NULL) { \
mem->free_list = ret->next; \
return &ret->t; \
} \
M_C(name,_segment_t) *segment = mem->current_segment; \
assert(segment != NULL); \
unsigned int count = segment->count; \
if (M_UNLIKELY (count >= MEMPOOL_MAX_PER_SEGMENT(type))) { \
M_C(name,_segment_t) *new_segment = M_MEMORY_ALLOC (M_C(name,_segment_t)); \
if (M_UNLIKELY (new_segment == NULL)) { \
M_MEMORY_FULL(sizeof (M_C(name,_segment_t))); \
return NULL; \
} \
new_segment->next = segment; \
new_segment->count = 0; \
mem->current_segment = new_segment; \
segment = new_segment; \
count = 0; \
} \
ret = &segment->tab[count]; \
segment->count = count + 1; \
MEMPOOLI_CONTRACT(mem, type); \
return &ret->t; \
} \
\
static inline void \
M_C(name,_free)(M_C(name,_t) mem, type *ptr) \
{ \
MEMPOOLI_CONTRACT(mem, type); \
/* NOTE: Unsafe cast: suppose that the given pointer \
was allocated by the previous alloc function. */ \
M_C(name,_union_t) *ret = (M_C(name,_union_t) *)(uintptr_t)ptr; \
ret->next = mem->free_list; \
mem->free_list = ret; \
MEMPOOLI_CONTRACT(mem, type); \
} \
/* User shall be able to cutomize the size of the segment and/or
the minimun number of elements.
The default is the number of elements that fits in 16KB.
*/
#ifndef MEMPOOL_MAX_PER_SEGMENT
#define MEMPOOL_MAX_PER_SEGMENT(type) \
#ifndef M_USE_MEMPOOL_MAX_PER_SEGMENT
#define M_USE_MEMPOOL_MAX_PER_SEGMENT(type) \
M_MAX((16*1024-sizeof(unsigned int) - 2*sizeof(void*)) / sizeof (type), 256U)
#endif
/********************************** INTERNAL ************************************/
#define M_M3MPOOL_DEF_P2(name, type, name_t) \
\
/* Define the type of element in a segment of the mempool. \
Either it is the basic type or a pointer to another one. */ \
typedef union M_C(name,_union_s) { \
type t; \
union M_C(name,_union_s) *next; \
} M_C(name,_union_ct); \
\
/* Define a segment of a mempool. \
It is an array of basic type, each segment is in a linked list */ \
typedef struct M_C(name,_segment_s) { \
unsigned int count; \
struct M_C(name,_segment_s) *next; \
M_C(name,_union_ct) tab[M_USE_MEMPOOL_MAX_PER_SEGMENT(type)]; \
} M_C(name,_segment_ct); \
\
/* Define a mempool. \
It is a pointer to the first free object within the segments \
and the segments themselves */ \
typedef struct M_C(name, _s) { \
M_C(name,_union_ct) *free_list; \
M_C(name,_segment_ct) *current_segment; \
} name_t[1]; \
\
static inline void \
M_C(name,_init)(name_t mem) \
{ \
mem->free_list = NULL; \
mem->current_segment = M_MEMORY_ALLOC(M_C(name,_segment_ct)); \
if (mem->current_segment == NULL) { \
M_MEMORY_FULL(sizeof (M_C(name,_segment_ct))); \
return; \
} \
mem->current_segment->next = NULL; \
mem->current_segment->count = 0; \
M_M3MPOOL_CONTRACT(mem, type); \
} \
\
static inline void \
M_C(name,_clear)(name_t mem) \
{ \
M_M3MPOOL_CONTRACT(mem, type); \
M_C(name,_segment_ct) *segment = mem->current_segment; \
while (segment != NULL) { \
M_C(name,_segment_ct) *next = segment->next; \
M_MEMORY_DEL (segment); \
segment = next; \
} \
/* Clean pointers to be safer */ \
mem->free_list = NULL; \
mem->current_segment = NULL; \
} \
\
static inline type * \
M_C(name,_alloc)(name_t mem) \
{ \
M_M3MPOOL_CONTRACT(mem, type); \
/* Test if one object is in the free list */ \
M_C(name,_union_ct) *ret = mem->free_list; \
if (ret != NULL) { \
/* Yes, so return it, and pop it from the free list */ \
mem->free_list = ret->next; \
return &ret->t; \
} \
/* No cheap free object exist. Test within a segment */ \
M_C(name,_segment_ct) *segment = mem->current_segment; \
M_ASSERT(segment != NULL); \
unsigned int count = segment->count; \
/* If segment is full, allocate a new one from the system */ \
if (M_UNLIKELY (count >= M_USE_MEMPOOL_MAX_PER_SEGMENT(type))) { \
M_C(name,_segment_ct) *new_segment = M_MEMORY_ALLOC (M_C(name,_segment_ct)); \
if (M_UNLIKELY (new_segment == NULL)) { \
M_MEMORY_FULL(sizeof (M_C(name,_segment_ct))); \
return NULL; \
} \
new_segment->next = segment; \
new_segment->count = 0; \
mem->current_segment = new_segment; \
segment = new_segment; \
count = 0; \
} \
/* Return the object as the last element of the current segment */ \
ret = &segment->tab[count]; \
segment->count = count + 1; \
M_M3MPOOL_CONTRACT(mem, type); \
return &ret->t; \
} \
\
static inline void \
M_C(name,_free)(name_t mem, type *ptr) \
{ \
M_M3MPOOL_CONTRACT(mem, type); \
/* NOTE: Unsafe cast: suppose that the given pointer \
was allocated by the previous alloc function. */ \
M_C(name,_union_ct) *ret = (M_C(name,_union_ct) *)(uintptr_t)ptr; \
/* Add the object back in the free list */ \
ret->next = mem->free_list; \
mem->free_list = ret; \
/* NOTE: the objects are NOT given back to the system until the mempool \
is fully cleared */ \
M_M3MPOOL_CONTRACT(mem, type); \
} \
#define MEMPOOLI_CONTRACT(mempool, type) do { \
assert((mempool) != NULL); \
assert((mempool)->current_segment != NULL); \
assert((mempool)->current_segment->count <= MEMPOOL_MAX_PER_SEGMENT(type)); \
/* MEMPOOL contract */
#define M_M3MPOOL_CONTRACT(mempool, type) do { \
M_ASSERT((mempool) != NULL); \
M_ASSERT((mempool)->current_segment != NULL); \
M_ASSERT((mempool)->current_segment->count <= M_USE_MEMPOOL_MAX_PER_SEGMENT(type)); \
} while (0)
#endif
+159 -33
View File
@@ -1,7 +1,7 @@
/*
* M*LIB - Thin Mutex & Thread wrapper
*
* Copyright (c) 2017-2019, Patrick Pelissier
* Copyright (c) 2017-2021, Patrick Pelissier
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
@@ -25,110 +25,173 @@
#ifndef MSTARLIB_MUTEX_H
#define MSTARLIB_MUTEX_H
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L \
/* Auto-detect the thread backend to use if the user has not override it */
#ifndef M_USE_THREAD_BACKEND
# if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L \
&& !defined(__STDC_NO_THREADS__)
# define M_USE_THREAD_BACKEND 1
# elif defined(WIN32) || defined(_WIN32) || defined(__CYGWIN__)
# define M_USE_THREAD_BACKEND 2
# else
# define M_USE_THREAD_BACKEND 3
# endif
#endif
/****************************** C11 version ********************************/
#if M_USE_THREAD_BACKEND == 1
#include <threads.h>
#include <assert.h>
#include <stdbool.h>
#include "m-core.h"
M_BEGIN_PROTECTED_CODE
/* Define a mutex type based on C11 definition */
typedef mtx_t m_mutex_t[1];
/* Define a condition variable type based on C11 definition */
typedef cnd_t m_cond_t[1];
/* Define a thread type based on C11 definition */
typedef thrd_t m_thread_t[1];
/* Initialize the mutex (constructor) */
static inline void m_mutex_init(m_mutex_t m)
{
int rc = mtx_init(m, mtx_plain);
// Abort program in case of initialization failure
// There is really nothing else to do if a mutex cannot be constructed
M_ASSERT_INIT (rc == 0, "mutex");
}
/* Clear the mutex (destructor) */
static inline void m_mutex_clear(m_mutex_t m)
{
mtx_destroy(m);
}
/* Lock the mutex */
static inline void m_mutex_lock(m_mutex_t m)
{
mtx_lock(m);
}
/* Unlock the mutex */
static inline void m_mutex_unlock(m_mutex_t m)
{
mtx_unlock(m);
}
/* Initialize the condition variable (constructor) */
static inline void m_cond_init(m_cond_t c)
{
int rc = cnd_init(c);
// Abort program in case of initialization failure
// There is really nothing else to do if the object cannot be constructed
M_ASSERT_INIT (rc == 0, "conditional variable");
}
/* Clear the condition variable (destructor) */
static inline void m_cond_clear(m_cond_t c)
{
cnd_destroy(c);
}
/* Signal the condition variable to at least one waiting thread */
static inline void m_cond_signal(m_cond_t c)
{
cnd_signal(c);
}
/* Signal the condition variable to all waiting threads */
static inline void m_cond_broadcast(m_cond_t c)
{
cnd_broadcast(c);
}
/* Wait for signaling the condition variable by another thread */
static inline void m_cond_wait(m_cond_t c, m_mutex_t m)
{
cnd_wait(c, m);
}
/* Create the thread (constructor) and start it */
static inline void m_thread_create(m_thread_t t, void (*func)(void*), void* arg)
{
int rc = thrd_create(t, (int(*)(void*))(void(*)(void))func, arg);
// Abort program in case of initialization failure
M_ASSERT_INIT (rc == thrd_success, "thread");
}
/* Wait for the thread to terminate and destroy it (destructor) */
static inline void m_thread_join(m_thread_t t)
{
int rc = thrd_join(*t, NULL);
assert (rc == thrd_success);
M_ASSERT (rc == thrd_success);
// Avoid warning about variable unused.
(void) rc;
}
/* The thread has nothing meaningfull to do.
Inform the OS to let other threads be scheduled */
static inline void m_thread_yield(void)
{
thrd_yield();
}
/* Sleep the thread for at least usec microseconds.
Return true if the sleep was successful */
static inline bool m_thread_sleep(unsigned long long usec)
{
struct timespec tv;
tv.tv_sec = usec / 1000000ULL;
tv.tv_nsec = (usec % 1000000ULL) * 1000UL;
tv.tv_sec = (long) (usec / 1000000ULL);
tv.tv_nsec = (long) ((usec % 1000000ULL) * 1000UL);
int retval = thrd_sleep(&tv, NULL);
return retval == 0;
}
// Internal type, not exported.
typedef once_flag m_oncei_t[1];
typedef once_flag m_once_ct[1];
// Initial value for m_once_ct
#define M_ONCEI_INIT_VALUE { ONCE_FLAG_INIT }
static inline void m_oncei_call(m_oncei_t o, void (*func)(void))
// Call the function exactly once
static inline void m_oncei_call(m_once_ct o, void (*func)(void))
{
call_once(o,func);
}
// Attribute to use to allocate a global variable to a thread.
#define M_THREAD_ATTR _Thread_local
M_END_PROTECTED_CODE
// MSYS2 doesn't define _WIN32 by default.
#elif defined(WIN32) || defined(_WIN32) || defined(__CYGWIN__)
/****************************** WIN32 version ******************************/
#elif M_USE_THREAD_BACKEND == 2
/* CLANG provides some useless and wrong warnings:
* - _WIN32_WINNT starts with '_' which is reserved by the standard
* as per the MSVC compiler, it is needed to be defined by the user
* to define which version of windows it want to be compatible with.
* - windows.h may be different than the case used by the file sytem
* there is however no normalized case.
*
* So, theses warnings have to be ignored and are disabled.
*
* We cannot add theses warnings in M_BEGIN_PROTECTED_CODE
* as they need to be disabled **BEFORE** including any system header
* and m-core includes some system headers.
* So we need to disable them explictly here.
*/
#if defined(__clang__) && __clang_major__ >= 4
_Pragma("clang diagnostic push")
_Pragma("clang diagnostic ignored \"-Wreserved-id-macro\"")
_Pragma("clang diagnostic ignored \"-Wnonportable-system-include-path\"")
#endif
/* CriticalSection & ConditionVariable are available from Windows Vista */
#ifndef WINVER
@@ -137,83 +200,112 @@ static inline void m_oncei_call(m_oncei_t o, void (*func)(void))
#ifndef _WIN32_WINNT
#define _WIN32_WINNT _WIN32_WINNT_VISTA
#endif
/* Include system headers */
#include <windows.h>
#include <assert.h>
#include <stdbool.h>
#include "m-core.h"
#if defined(__clang__) && __clang_major__ >= 4
_Pragma("clang diagnostic pop")
#endif
M_BEGIN_PROTECTED_CODE
/* Define a thread type based on WINDOWS definition */
typedef HANDLE m_thread_t[1];
/* Define a mutex type based on WINDOWS definition */
typedef CRITICAL_SECTION m_mutex_t[1];
/* Define a condition variable type based on WINDOWS definition */
typedef CONDITION_VARIABLE m_cond_t[1];
/* Initialize a mutex (Constructor)*/
static inline void m_mutex_init(m_mutex_t m)
{
InitializeCriticalSection(m);
}
/* Clear a mutex (destructor) */
static inline void m_mutex_clear(m_mutex_t m)
{
DeleteCriticalSection(m);
}
/* Lock a mutex */
static inline void m_mutex_lock(m_mutex_t m)
{
EnterCriticalSection(m);
}
/* Unlock a mutex */
static inline void m_mutex_unlock(m_mutex_t m)
{
LeaveCriticalSection(m);
}
/* Initialize a condition variable (constructor) */
static inline void m_cond_init(m_cond_t c)
{
InitializeConditionVariable(c);
}
/* Clear a condition variable (destructor) */
static inline void m_cond_clear(m_cond_t c)
{
(void) c; // There is no destructor for this object.
}
/* Signal a condition variable to at least one waiting thread */
static inline void m_cond_signal(m_cond_t c)
{
WakeConditionVariable(c);
}
/* Signal a condition variable to all waiting threads */
static inline void m_cond_broadcast(m_cond_t c)
{
WakeAllConditionVariable(c);
}
/* Wait for a condition variable */
static inline void m_cond_wait(m_cond_t c, m_mutex_t m)
{
SleepConditionVariableCS(c, m, INFINITE);
}
/* Create a thread (constructor) and start it */
static inline void m_thread_create(m_thread_t t, void (*func)(void*), void *arg)
{
*t = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) (uintptr_t) func, arg, 0, NULL);
M_ASSERT_INIT (*t != NULL, "thread");
}
/* Wait for the thread to terminate and destroy it (destructor) */
static inline void m_thread_join(m_thread_t t)
{
DWORD dwWaitResult = WaitForSingleObject(*t, INFINITE);
(void) dwWaitResult;
assert (dwWaitResult == WAIT_OBJECT_0);
M_ASSERT (dwWaitResult == WAIT_OBJECT_0);
CloseHandle(*t);
}
/* The thread has nothing meaningfull to do.
Inform the OS to let other threads be scheduled */
static inline void m_thread_yield(void)
{
Sleep(0);
}
/* Sleep the thread for at least usec microseconds
Return true if the sleep was successful */
static inline bool m_thread_sleep(unsigned long long usec)
{
LARGE_INTEGER ft;
ft.QuadPart = -(10ULL*usec);
M_ASSERT (usec <= LLONG_MAX);
ft.QuadPart = -(10LL*(long long) usec);
HANDLE hd = CreateWaitableTimer(NULL, TRUE, NULL);
M_ASSERT_INIT (hd != NULL, "timer");
SetWaitableTimer(hd, &ft, 0, NULL, NULL, 0);
@@ -224,7 +316,7 @@ static inline bool m_thread_sleep(unsigned long long usec)
// Internal type, not exported.
typedef INIT_ONCE m_oncei_t[1];
typedef INIT_ONCE m_once_ct[1];
#define M_ONCEI_INIT_VALUE { INIT_ONCE_STATIC_INIT }
static inline BOOL CALLBACK m_oncei_callback( PINIT_ONCE InitOnce, PVOID Parameter, PVOID *lpContext)
{
@@ -235,20 +327,24 @@ static inline BOOL CALLBACK m_oncei_callback( PINIT_ONCE InitOnce, PVOID Paramet
(*func)();
return TRUE;
}
static inline void m_oncei_call(m_oncei_t o, void (*func)(void))
static inline void m_oncei_call(m_once_ct o, void (*func)(void))
{
InitOnceExecuteOnce(o, m_oncei_callback, (void*)(intptr_t)func, NULL);
}
#if defined(_MSC_VER)
// Attribute to use to allocate a global variable to a thread (MSVC def).
# define M_THREAD_ATTR __declspec( thread )
#else
// Attribute to use to allocate a global variable to a thread (GCC def).
# define M_THREAD_ATTR __thread
#endif
#else
M_END_PROTECTED_CODE
/**************************** PTHREAD version ******************************/
#else
#include <pthread.h>
#ifdef _POSIX_PRIORITY_SCHEDULING
@@ -261,76 +357,103 @@ static inline void m_oncei_call(m_oncei_t o, void (*func)(void))
#include <stdbool.h>
#include "m-core.h"
M_BEGIN_PROTECTED_CODE
/* Define a mutex type based on PTHREAD definition */
typedef pthread_mutex_t m_mutex_t[1];
/* Define a condition variable type based on PTHREAD definition */
typedef pthread_cond_t m_cond_t[1];
/* Define a thread type based on PTHREAD definition */
typedef pthread_t m_thread_t[1];
/* Initialize the mutex (constructor) */
static inline void m_mutex_init(m_mutex_t m)
{
int _rc = pthread_mutex_init(m, NULL);
// Abort program in case of initialization failure
// There is really nothing else to do if a mutex cannot be constructed
M_ASSERT_INIT (_rc == 0, "mutex");
}
/* Clear the mutex (destructor) */
static inline void m_mutex_clear(m_mutex_t m)
{
pthread_mutex_destroy(m);
}
/* Lock the mutex */
static inline void m_mutex_lock(m_mutex_t m)
{
pthread_mutex_lock(m);
}
/* Unlock the mutex */
static inline void m_mutex_unlock(m_mutex_t m)
{
pthread_mutex_unlock(m);
}
/* Lazy lock initialization */
#define M_MUTEXI_INIT_VALUE { PTHREAD_MUTEX_INITIALIZER }
/* Internal function compatible with lazy lock */
static inline void m_mutexi_lazy_lock(m_mutex_t m)
{
pthread_mutex_lock(m);
}
/* Initialize the condition variable (constructor) */
static inline void m_cond_init(m_cond_t c)
{
int _rc = pthread_cond_init(c, NULL);
// Abort program in case of initialization failure
// There is really nothing else to do if a mutex cannot be constructed
M_ASSERT_INIT (_rc == 0, "conditional variable");
}
/* Clear the condition variable (destructor) */
static inline void m_cond_clear(m_cond_t c)
{
pthread_cond_destroy(c);
}
/* Signal a condition variable to at least a waiting thread */
static inline void m_cond_signal(m_cond_t c)
{
pthread_cond_signal(c);
}
/* Signal a condition variable to all waiting threads */
static inline void m_cond_broadcast(m_cond_t c)
{
pthread_cond_broadcast(c);
}
/* Waiting for a condition variable */
static inline void m_cond_wait(m_cond_t c, m_mutex_t m)
{
pthread_cond_wait(c, m);
}
/* Create a thread (constructor) and start it */
static inline void m_thread_create(m_thread_t t, void (*func)(void*), void *arg)
{
int _rc = pthread_create(t, NULL, (void*(*)(void*))(void(*)(void))func, arg);
M_ASSERT_INIT (_rc == 0, "thread");
}
/* Wait for the thread to terminate and destroy it (destructor) */
static inline void m_thread_join(m_thread_t t)
{
int _rc = pthread_join(*t, NULL);
(void)_rc; // Avoid warning about variable unused.
assert (_rc == 0);
M_ASSERT (_rc == 0);
}
/* The thread has nothing meaningfull to do.
Inform the OS to let other threads be scheduled */
static inline void m_thread_yield(void)
{
#ifdef _POSIX_PRIORITY_SCHEDULING
@@ -338,30 +461,33 @@ static inline void m_thread_yield(void)
#endif
}
/* Sleep for at least usec microseconds
Return true if the sleep was successful */
static inline bool m_thread_sleep(unsigned long long usec)
{
struct timeval tv;
/* We don't want to use usleep or nanosleep so that
we remain compatible with strict C99 build */
tv.tv_sec = usec / 1000000ULL;
tv.tv_usec = usec % 1000000ULL;
tv.tv_sec = (time_t) (usec / 1000000ULL);
tv.tv_usec = (suseconds_t) (usec % 1000000ULL);
int retval = select(1, NULL, NULL, NULL, &tv);
return retval == 0;
}
// Internal type, not exported.
typedef pthread_once_t m_oncei_t[1];
typedef pthread_once_t m_once_ct[1];
#define M_ONCEI_INIT_VALUE { PTHREAD_ONCE_INIT }
static inline void m_oncei_call(m_oncei_t o, void (*func)(void))
static inline void m_oncei_call(m_once_ct o, void (*func)(void))
{
pthread_once(o,func);
}
#define M_THREAD_ATTR __thread
M_END_PROTECTED_CODE
#endif
// TODO: m_thread_sleep doesn't yield thread during waiting, making it a poor choice for active waiting.
// TODO: Obsolete M_LOCK macro.
/* M_LOCK macro. Allow simple locking encapsulation.
@@ -377,25 +503,25 @@ static inline void m_oncei_call(m_oncei_t o, void (*func)(void))
or using C11's ONCE mechanism */
#ifdef M_MUTEXI_INIT_VALUE
# define M_LOCK_DECL(name) m_mutex_t name = M_MUTEXI_INIT_VALUE
# define M_LOCK(name) \
# define M_LOCK(name) \
M_LOCKI_DO(name, M_C(local_cont_, __LINE__), m_mutexi_lazy_lock, m_mutex_unlock)
#else
# define M_LOCK_DECL(name) \
m_mutex_t name; \
static void M_C(m_mutex_init_, name)(void) { \
m_mutex_init(name); \
} \
m_oncei_t M_C(m_once_, name) = M_ONCEI_INIT_VALUE
# define M_LOCKI_BY_ONCE(name) \
(m_oncei_call(M_C(m_once_, name), M_C(m_mutex_init_, name)), \
# define M_LOCK_DECL(name) \
m_mutex_t name; \
static void M_C(m_mutex_init_, name)(void) { \
m_mutex_init(name); \
} \
m_once_ct M_C(m_once_, name) = M_ONCEI_INIT_VALUE
# define M_LOCKI_BY_ONCE(name) \
(m_oncei_call(M_C(m_once_, name), M_C(m_mutex_init_, name)), \
m_mutex_lock(name), (void) 0 )
# define M_LOCK(name) \
# define M_LOCK(name) \
M_LOCKI_DO(name, M_C(local_cont_, __LINE__), M_LOCKI_BY_ONCE, m_mutex_unlock)
#endif
#define M_LOCKI_DO(name, cont, lock_func, unlock_func) \
for(bool cont = true \
; cont && (lock_func (name), true); \
#define M_LOCKI_DO(name, cont, lock_func, unlock_func) \
for(bool cont = true \
; cont && (lock_func (name), true); \
(unlock_func (name), cont = false))
#endif
+382 -302
View File
@@ -1,7 +1,7 @@
/*
* M*LIB - dynamic priority queue module
*
* Copyright (c) 2017-2019, Patrick Pelissier
* Copyright (c) 2017-2021, Patrick Pelissier
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
@@ -26,23 +26,32 @@
#define MSTARLIB_PRIOQUEUE_H
#include "m-core.h"
#include "m-array.h"
#include "m-array.h" /* Priority queue are built upon array */
/* Priority queue based on binary heap implementation */
/* Define a prioqueue of a given type and its associated functions.
USAGE: PRIOQUEUE_DEF(name, type [, oplist_of_the_type]) */
#define PRIOQUEUE_DEF(name, ...) \
PRIOQUEUEI_DEF_P1(M_IF_NARGS_EQ1(__VA_ARGS__) \
((name, __VA_ARGS__, M_GLOBAL_OPLIST_OR_DEF(__VA_ARGS__)(), M_C(name,_t), M_C(name,_it_t) ), \
(name, __VA_ARGS__, M_C(name,_t), M_C(name,_it_t))))
#define PRIOQUEUE_DEF(name, ...) \
PRIOQUEUE_DEF_AS(name, M_C(name,_t), M_C(name,_it_t), __VA_ARGS__)
/* Define a prioqueue of a given type and its associated functions.
as the name name_t with an iterator named it_t
USAGE: PRIOQUEUE_DEF_AS(name, name_t, it_t, type [, oplist_of_the_type]) */
#define PRIOQUEUE_DEF_AS(name, name_t, it_t, ...) \
M_BEGIN_PROTECTED_CODE \
M_PR1OQUEUE_DEF_P1(M_IF_NARGS_EQ1(__VA_ARGS__) \
((name, __VA_ARGS__, M_GLOBAL_OPLIST_OR_DEF(__VA_ARGS__)(), name_t, it_t ), \
(name, __VA_ARGS__, name_t, it_t ))) \
M_END_PROTECTED_CODE
/* Define the oplist of a prioqueue of type.
USAGE: PRIOQUEUE_OPLIST(name[, oplist of the type]) */
#define PRIOQUEUE_OPLIST(...) \
PRIOQUEUEI_OPLIST_P1(M_IF_NARGS_EQ1(__VA_ARGS__) \
((__VA_ARGS__, M_DEFAULT_OPLIST), \
#define PRIOQUEUE_OPLIST(...) \
M_PR1OQUEUE_OPLIST_P1(M_IF_NARGS_EQ1(__VA_ARGS__) \
((__VA_ARGS__, M_DEFAULT_OPLIST), \
(__VA_ARGS__ )))
@@ -51,29 +60,59 @@
/* Deferred evaluation for the definition,
so that all arguments are evaluated before further expansion */
#define PRIOQUEUEI_OPLIST_P1(arg) PRIOQUEUEI_OPLIST_P2 arg
#define PRIOQUEUEI_DEF_P1(arg) PRIOQUEUEI_DEF_P2 arg
#define M_PR1OQUEUE_OPLIST_P1(arg) M_PR1OQUEUE_OPLIST_P2 arg
/* Validation of the given oplist */
#define M_PR1OQUEUE_OPLIST_P2(name, oplist) \
M_IF_OPLIST(oplist)(M_PR1OQUEUE_OPLIST_P3, M_PR1OQUEUE_OPLIST_FAILURE)(name, oplist)
/* Prepare a clean compilation failure */
#define M_PR1OQUEUE_OPLIST_FAILURE(name, oplist) \
((M_LIB_ERROR(ARGUMENT_OF_PRIOQUEUE_OPLIST_IS_NOT_AN_OPLIST, name, oplist)))
/* Define oplist of a priority queue */
#define PRIOQUEUEI_OPLIST_P2(name, oplist) \
(INIT(M_C(name, _init)) \
,INIT_SET(M_C(name, _init_set)) \
,INIT_WITH(API_1(M_INIT_VAI)) \
,SET(M_C(name, _set)) \
,CLEAR(M_C(name, _clear)) \
,INIT_MOVE(M_C(name, _init_move)) \
,MOVE(M_C(name, _move)) \
,SWAP(M_C(name, _swap)) \
,TYPE(M_C(name,_t)) \
,SUBTYPE(M_C(name, _type_t)) \
,CLEAN(M_C(name,_clean)) \
,PUSH(M_C(name,_push)) \
,POP(M_C(name,_pop)) \
,OPLIST(oplist) \
,TEST_EMPTY(M_C(name, _empty_p)), \
,GET_SIZE(M_C(name, _size)) \
#define M_PR1OQUEUE_OPLIST_P3(name, oplist) \
(INIT(M_C(name, _init)) \
,INIT_SET(M_C(name, _init_set)) \
,INIT_WITH(API_1(M_INIT_VAI)) \
,SET(M_C(name, _set)) \
,CLEAR(M_C(name, _clear)) \
,INIT_MOVE(M_C(name, _init_move)) \
,MOVE(M_C(name, _move)) \
,SWAP(M_C(name, _swap)) \
,NAME(name) \
,TYPE(M_C(name,_ct)) \
,SUBTYPE(M_C(name, _subtype_ct)) \
,RESET(M_C(name,_reset)) \
,PUSH(M_C(name,_push)) \
,POP(M_C(name,_pop)) \
,OPLIST(oplist) \
,EMPTY_P(M_C(name, _empty_p)), \
,GET_SIZE(M_C(name, _size)) \
,IT_TYPE(M_C(name, _it_ct)), \
IT_FIRST(M_C(name,_it)), \
IT_END(M_C(name,_it_end)), \
IT_SET(M_C(name,_it_set)), \
IT_END_P(M_C(name,_end_p)), \
IT_EQUAL_P(M_C(name,_it_equal_p)), \
IT_LAST_P(M_C(name,_last_p)), \
IT_NEXT(M_C(name,_next)), \
IT_CREF(M_C(name,_cref)), \
)
/* Deferred evaluation for the definition,
so that all arguments are evaluated before further expansion */
#define M_PR1OQUEUE_DEF_P1(arg) M_PR1OQUEUE_DEF_P2 arg
/* Validate the oplist before going further */
#define M_PR1OQUEUE_DEF_P2(name, type, oplist, prioqueue_t, it_t) \
M_IF_OPLIST(oplist)(M_PR1OQUEUE_DEF_P3, M_PR1OQUEUE_DEF_FAILURE)(name, type, oplist, prioqueue_t, it_t)
/* Stop processing with a compilation failure */
#define M_PR1OQUEUE_DEF_FAILURE(name, type, oplist, prioqueue_t, it_t) \
M_STATIC_FAILURE(M_LIB_NOT_AN_OPLIST, "(PRIOQUEUE_DEF): the given argument is not a valid oplist: " #oplist)
/* Define the priority queue:
- name: prefix to use,
- type: type of the contained objects,
@@ -81,281 +120,322 @@
- prioqueue_t: type of the container,
- it_t: iterator of the container
*/
#define PRIOQUEUEI_DEF_P2(name, type, oplist, prioqueue_t, it_t) \
ARRAY_DEF(M_C(name, _array), type, oplist) \
\
typedef type M_C(name, _type_t); \
\
typedef struct M_C(name, _s) { \
M_C(name, _array_t) array; \
} prioqueue_t[1]; \
typedef struct M_C(name, _s) *M_C(name, _ptr); \
typedef const struct M_C(name, _s) *M_C(name, _srcptr); \
\
typedef M_C(name, _array_it_t) it_t; \
\
static inline void \
M_C(name, _init)(prioqueue_t p) \
{ \
M_C(name, _array_init)(p->array); \
} \
\
static inline void \
M_C(name, _init_set)(prioqueue_t p, prioqueue_t const o) \
{ \
M_C(name, _array_init_set)(p->array, o->array); \
} \
\
static inline void \
M_C(name, _set)(prioqueue_t p, prioqueue_t const o) \
{ \
M_C(name, _array_set)(p->array, o->array); \
} \
\
static inline void \
M_C(name, _clear)(prioqueue_t p) \
{ \
M_C(name, _array_clear)(p->array); \
} \
\
static inline void \
M_C(name, _init_move)(prioqueue_t p, prioqueue_t o) \
{ \
M_C(name, _array_init_move)(p->array, o->array); \
} \
\
static inline void \
M_C(name, _move)(prioqueue_t p, prioqueue_t o) \
{ \
M_C(name, _array_move)(p->array, o->array); \
} \
\
static inline void \
M_C(name, _swap)(prioqueue_t p, prioqueue_t o) \
{ \
M_C(name, _array_swap)(p->array, o->array); \
} \
\
static inline void \
M_C(name, _clean)(prioqueue_t p) \
{ \
M_C(name, _array_clean)(p->array); \
} \
\
static inline size_t \
M_C(name, _i_parent)(size_t i) \
{ \
assert (i > 0); \
return (i - 1) / 2; \
} \
\
static inline size_t \
M_C(name, _i_lchild)(size_t i) \
{ \
assert(i <= ((-(size_t)1)-2)/2); \
return 2*i + 1; \
} \
\
static inline size_t \
M_C(name, _i_rchild)(size_t i) \
{ \
assert(i <= ((-(size_t)1)-2)/2); \
return 2*i + 2; \
} \
\
static inline int \
M_C(name, _i_cmp)(const prioqueue_t p, size_t i, size_t j) \
{ \
return M_CALL_CMP(oplist, *M_C(name, _array_cget)(p->array, i), \
*M_C(name, _array_cget)(p->array, j)); \
} \
\
static inline bool \
M_C(name, _empty_p)(prioqueue_t const p) \
{ \
return M_C(name, _array_empty_p)(p->array); \
} \
\
static inline size_t \
M_C(name, _size)(prioqueue_t const p) \
{ \
return M_C(name, _array_size)(p->array); \
} \
\
static inline void \
M_C(name, _push)(prioqueue_t p, type const x) \
{ \
M_C(name, _array_push_back)(p->array, x); \
\
size_t i = M_C(name, _array_size)(p->array)-1; \
while (i > 0) { \
size_t j = M_C(name, _i_parent)(i); \
if (M_C(name, _i_cmp)(p, j, i) <= 0) \
break; \
M_C(name, _array_swap_at) (p->array, i, j); \
i = j; \
} \
} \
\
static inline type const * \
M_C(name, _front)(prioqueue_t const p) \
{ \
return M_C(name, _array_cget)(p->array, 0); \
} \
\
static inline void \
M_C(name, _pop)(type *x, prioqueue_t p) \
{ \
size_t size = M_C(name, _array_size)(p->array)-1; \
M_C(name, _array_swap_at) (p->array, 0, size); \
M_C(name, _array_pop_back)(x, p->array); \
\
size_t i = 0; \
while (true) { \
size_t child = M_C(name, _i_lchild)(i); \
if (child >= size) break; \
size_t otherChild = M_C(name, _i_rchild)(i); \
if (otherChild < size \
&& M_C(name, _i_cmp)(p, otherChild, child) < 0 ) { \
child = otherChild; \
} \
if (M_C(name, _i_cmp)(p, i, child) <= 0) break; \
M_C(name, _array_swap_at) (p->array, i, child); \
i = child; \
} \
} \
\
static inline void \
M_C(name, _it)(it_t it, prioqueue_t const v) \
{ \
M_C(name, _array_it)(it, v->array); \
} \
\
static inline void \
M_C(name, _it_last)(it_t it, prioqueue_t const v) \
{ \
M_C(name, _array_it_last)(it, v->array); \
} \
\
static inline void \
M_C(name, _it_end)(it_t it, prioqueue_t const v) \
{ \
M_C(name, _array_it_end)(it, v->array); \
} \
\
static inline void \
M_C(name, _it_set)(it_t it, const it_t org) \
{ \
M_C(name, _array_it_set)(it, org); \
} \
\
static inline bool \
M_C(name, _end_p)(const it_t it) \
{ \
return M_C(name, _array_end_p)(it); \
} \
\
static inline bool \
M_C(name, _last_p)(const it_t it) \
{ \
return M_C(name, _array_last_p)(it); \
} \
\
static inline bool \
M_C(name, _it_equal_p)(const it_t it1, \
const it_t it2) \
{ \
return M_C(name, _array_it_equal_p)(it1, it2); \
} \
\
static inline void \
M_C(name, _next)(it_t it) \
{ \
M_C(name, _array_next)(it); \
} \
\
static inline void \
M_C(name, _previous)(it_t it) \
{ \
M_C(name, _array_previous)(it); \
} \
\
static inline type const * \
M_C(name, _cref)(const it_t it) \
{ \
return M_C(name, _array_cref)(it); \
} \
\
M_IF_METHOD(EQUAL, oplist) \
( \
/* EQUAL & CMP may be uncorrelated */ \
static inline bool \
M_C(name, _erase)(prioqueue_t p, type x) \
{ \
/* First pass: search for an item EQUAL to x */ \
/* NOTE: An HASHMAP may be a good idea to optimize this pass. */ \
size_t size = M_C(name, _array_size)(p->array); \
size_t i = 0; \
for(i = 0; i < size; i++) { \
if (M_CALL_EQUAL(oplist, *M_C(name, _array_cget)(p->array, i), x)) \
break; \
} \
/* If x is not found, then stop */ \
if (i >= size) \
return false; \
/* Swap the found item and the last element */ \
size--; \
M_C(name, _array_swap_at) (p->array, i, size); \
M_C(name, _array_pop_back)(NULL, p->array); \
#define M_PR1OQUEUE_DEF_P3(name, type, oplist, prioqueue_t, it_t) \
\
/* Definition of the internal array used to construct the priority queue */ \
ARRAY_DEF(M_C(name, _array), type, oplist) \
\
/* Define the priority queue over the defined array */ \
typedef struct M_C(name, _s) { \
M_C(name, _array_t) array; \
} prioqueue_t[1]; \
/* Define the pointer references to the priority queue */ \
typedef struct M_C(name, _s) *M_C(name, _ptr); \
typedef const struct M_C(name, _s) *M_C(name, _srcptr); \
\
/* The iterator is the same one as the one of the internal array */ \
typedef M_C(name, _array_it_t) it_t; \
\
/* Definition of the internal types used by the oplist */ \
typedef prioqueue_t M_C(name, _ct); \
typedef type M_C(name, _subtype_ct); \
typedef it_t M_C(name, _it_ct); \
\
M_CHECK_COMPATIBLE_OPLIST(name, 1, type, oplist) \
\
static inline void \
M_C(name, _init)(prioqueue_t p) \
{ \
M_C(name, _array_init)(p->array); \
} \
\
static inline void \
M_C(name, _init_set)(prioqueue_t p, prioqueue_t const o) \
{ \
M_C(name, _array_init_set)(p->array, o->array); \
} \
\
static inline void \
M_C(name, _set)(prioqueue_t p, prioqueue_t const o) \
{ \
M_C(name, _array_set)(p->array, o->array); \
} \
\
static inline void \
M_C(name, _clear)(prioqueue_t p) \
{ \
M_C(name, _array_clear)(p->array); \
} \
\
static inline void \
M_C(name, _init_move)(prioqueue_t p, prioqueue_t o) \
{ \
M_C(name, _array_init_move)(p->array, o->array); \
} \
\
static inline void \
M_C(name, _move)(prioqueue_t p, prioqueue_t o) \
{ \
M_C(name, _array_move)(p->array, o->array); \
} \
\
static inline void \
M_C(name, _swap)(prioqueue_t p, prioqueue_t o) \
{ \
M_C(name, _array_swap)(p->array, o->array); \
} \
\
static inline void \
M_C(name, _reset)(prioqueue_t p) \
{ \
M_C(name, _array_reset)(p->array); \
} \
\
static inline void M_ATTR_DEPRECATED \
M_C(name, _clean)(prioqueue_t p) \
{ \
M_C(name,_reset)(p); \
} \
\
static inline size_t \
M_C(name, _i_parent)(size_t i) \
{ \
M_ASSERT (i > 0); \
return (i - 1) / 2; \
} \
\
static inline size_t \
M_C(name, _i_lchild)(size_t i) \
{ \
M_ASSERT(i <= ((SIZE_MAX)-2)/2); \
return 2*i + 1; \
} \
\
static inline size_t \
M_C(name, _i_rchild)(size_t i) \
{ \
M_ASSERT(i <= ((SIZE_MAX)-2)/2); \
return 2*i + 2; \
} \
\
static inline int \
M_C(name, _i_cmp)(const prioqueue_t p, size_t i, size_t j) \
{ \
return M_CALL_CMP(oplist, *M_C(name, _array_cget)(p->array, i), \
*M_C(name, _array_cget)(p->array, j)); \
} \
\
static inline bool \
M_C(name, _empty_p)(prioqueue_t const p) \
{ \
return M_C(name, _array_empty_p)(p->array); \
} \
\
static inline size_t \
M_C(name, _size)(prioqueue_t const p) \
{ \
return M_C(name, _array_size)(p->array); \
} \
\
static inline void \
M_C(name, _push)(prioqueue_t p, type const x) \
{ \
/* Push back the new element at the end of the array */ \
M_C(name, _array_push_back)(p->array, x); \
\
/* Reorder the array by swapping with its parent \
* until it reaches the right position */ \
size_t i = M_C(name, _array_size)(p->array)-1; \
while (i > 0) { \
size_t j = M_C(name, _i_parent)(i); \
if (M_C(name, _i_cmp)(p, j, i) <= 0) \
break; \
M_C(name, _array_swap_at) (p->array, i, j); \
i = j; \
} \
} \
\
static inline type const * \
M_C(name, _front)(prioqueue_t const p) \
{ \
return M_C(name, _array_cget)(p->array, 0); \
} \
\
static inline void \
M_C(name, _pop)(type *x, prioqueue_t p) \
{ \
/* Swap the front element with the last element */ \
size_t size = M_C(name, _array_size)(p->array)-1; \
M_C(name, _array_swap_at) (p->array, 0, size); \
/* Swap the new last element */ \
M_C(name, _array_pop_back)(x, p->array); \
\
/* Reorder the heap */ \
size_t i = 0; \
while (true) { \
size_t child = M_C(name, _i_lchild)(i); \
if (child >= size) \
break; \
size_t otherChild = M_C(name, _i_rchild)(i); \
if (otherChild < size \
&& M_C(name, _i_cmp)(p, otherChild, child) < 0 ) { \
child = otherChild; \
} \
if (M_C(name, _i_cmp)(p, i, child) <= 0) \
break; \
M_C(name, _array_swap_at) (p->array, i, child); \
i = child; \
} \
} \
\
/* Define iterators over the array iterator */ \
static inline void \
M_C(name, _it)(it_t it, prioqueue_t const v) \
{ \
M_C(name, _array_it)(it, v->array); \
} \
\
static inline void \
M_C(name, _it_last)(it_t it, prioqueue_t const v) \
{ \
M_C(name, _array_it_last)(it, v->array); \
} \
\
static inline void \
M_C(name, _it_end)(it_t it, prioqueue_t const v) \
{ \
M_C(name, _array_it_end)(it, v->array); \
} \
\
static inline void \
M_C(name, _it_set)(it_t it, const it_t org) \
{ \
M_C(name, _array_it_set)(it, org); \
} \
\
static inline bool \
M_C(name, _end_p)(const it_t it) \
{ \
return M_C(name, _array_end_p)(it); \
} \
\
static inline bool \
M_C(name, _last_p)(const it_t it) \
{ \
return M_C(name, _array_last_p)(it); \
} \
\
static inline bool \
M_C(name, _it_equal_p)(const it_t it1, \
const it_t it2) \
{ \
return M_C(name, _array_it_equal_p)(it1, it2); \
} \
\
static inline void \
M_C(name, _next)(it_t it) \
{ \
M_C(name, _array_next)(it); \
} \
\
static inline void \
M_C(name, _previous)(it_t it) \
{ \
M_C(name, _array_previous)(it); \
} \
\
static inline type const * \
M_C(name, _cref)(const it_t it) \
{ \
return M_C(name, _array_cref)(it); \
} \
\
M_IF_METHOD(EQUAL, oplist) \
( \
/* EQUAL & CMP may be uncorrelated */ \
static inline bool \
M_C(name, _equal_p)(prioqueue_t const p, prioqueue_t const q) \
{ \
return M_C(name, _array_equal_p)(p->array, q->array); \
} \
\
static inline bool \
M_C(name, _erase)(prioqueue_t p, type x) \
{ \
/* First pass: search for an item EQUAL to x */ \
/* NOTE: An HASHMAP may be a good idea to optimize this pass. */ \
size_t size = M_C(name, _array_size)(p->array); \
size_t i = 0; \
for(i = 0; i < size; i++) { \
if (M_CALL_EQUAL(oplist, *M_C(name, _array_cget)(p->array, i), x)) \
break; \
} \
/* If x is not found, then stop */ \
if (i >= size) \
return false; \
/* Swap the found item and the last element */ \
size--; \
M_C(name, _array_swap_at) (p->array, i, size); \
M_C(name, _array_pop_back)(NULL, p->array); \
/* Move back the last swapped element to its right position in the heap */ \
while (true) { \
size_t child = M_C(name, _i_lchild)(i); \
if (child >= size) break; \
size_t otherChild = M_C(name, _i_rchild)(i); \
if (otherChild < size \
&& M_C(name, _i_cmp)(p, otherChild, child) < 0 ) { \
child = otherChild; \
} \
if (M_C(name, _i_cmp)(p, i, child) <= 0) break; \
M_C(name, _array_swap_at) (p->array, i, child); \
i = child; \
} \
return true; \
} \
\
static inline void \
M_C(name, _update_further)(prioqueue_t p, type xold, type xnew) \
{ \
/* This update assumes that the new position is further in the heap */ \
assert (M_CALL_CMP(oplist, xold, xnew) > 0); \
/* First pass: search for an item EQUAL to x */ \
size_t size = M_C(name, _array_size)(p->array); \
size_t i = 0; \
for(i = 0; i < size; i++) { \
if (M_CALL_EQUAL(oplist, *M_C(name, _array_cget)(p->array, i), xold)) \
break; \
} \
/* We shall have found the item */ \
assert (i < size); \
/* Set the found item to the new element */ \
M_C(name, _array_set_at) (p->array, i, xnew); \
/* Move back the updated element to its right position in the heap */ \
while (true) { \
size_t child = M_C(name, _i_lchild)(i); \
if (child >= size) break; \
size_t otherChild = M_C(name, _i_rchild)(i); \
if (otherChild < size \
&& M_C(name, _i_cmp)(p, otherChild, child) < 0 ) { \
child = otherChild; \
} \
if (M_C(name, _i_cmp)(p, i, child) <= 0) break; \
M_C(name, _array_swap_at) (p->array, i, child); \
i = child; \
} \
} \
\
, /* No EQUAL */ \) \
while (true) { \
size_t child = M_C(name, _i_lchild)(i); \
if (child >= size) break; \
size_t otherChild = M_C(name, _i_rchild)(i); \
if (otherChild < size \
&& M_C(name, _i_cmp)(p, otherChild, child) < 0 ) { \
child = otherChild; \
} \
if (M_C(name, _i_cmp)(p, i, child) <= 0) break; \
M_C(name, _array_swap_at) (p->array, i, child); \
i = child; \
} \
return true; \
} \
\
static inline void \
M_C(name, _update)(prioqueue_t p, type const xold, type const xnew) \
{ \
/* NOTE: xold can be the same pointer than xnew */ \
/* First pass: search for an item EQUAL to x */ \
size_t size = M_C(name, _array_size)(p->array); \
size_t i = 0; \
for(i = 0; i < size; i++) { \
if (M_CALL_EQUAL(oplist, *M_C(name, _array_cget)(p->array, i), xold)) \
break; \
} \
/* We shall have found the item */ \
M_ASSERT (i < size); \
/* Test if the position of the old data is further or nearer than the new */ \
int cmp = M_CALL_CMP(oplist, *M_C(name, _array_cget)(p->array, i), xnew); \
/* Set the found item to the new element */ \
M_C(name, _array_set_at) (p->array, i, xnew); \
if (cmp < 0) { \
/* Move back the updated element to its new position, further in the heap */ \
while (true) { \
size_t child = M_C(name, _i_lchild)(i); \
if (child >= size) break; \
size_t otherChild = M_C(name, _i_rchild)(i); \
if (otherChild < size \
&& M_C(name, _i_cmp)(p, otherChild, child) < 0 ) { \
child = otherChild; \
} \
if (M_C(name, _i_cmp)(p, i, child) <= 0) break; \
M_C(name, _array_swap_at) (p->array, i, child); \
i = child; \
} \
} else { \
/* Move back the updated element to its new position, nearest in the heap */ \
while (i > 0) { \
size_t parent = M_C(name, _i_parent)(i); \
if (M_C(name, _i_cmp)(p, parent, i) <= 0) break; \
M_C(name, _array_swap_at) (p->array, i, parent); \
i = parent; \
} \
} \
} \
, /* No EQUAL */ ) \
// TODO: set all & remove all function
+1104 -1004
View File
File diff suppressed because it is too large. Load diff
+148 -59
View File
@@ -1,7 +1,7 @@
/*
* M*LIB - Serial BIN
*
* Copyright (c) 2017-2019, Patrick Pelissier
* Copyright (c) 2017-2021, Patrick Pelissier
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
@@ -30,6 +30,80 @@
#include "m-core.h"
#include "m-string.h"
M_BEGIN_PROTECTED_CODE
/* Internal service:
* Write size_t in the stream in a compact form to reduce consumption
* (and I/O bandwidth)
*/
static inline bool
m_serial_bin_write_size(FILE *f, const size_t size)
{
bool b;
if (M_LIKELY(size < 253))
{
b = EOF != fputc((unsigned char) size, f);
} else if (size < 1ULL << 16) {
b = EOF != fputc(253, f); // Save 16 bits encoding
b &= EOF != fputc((unsigned char) (size >> 8), f);
b &= EOF != fputc((unsigned char) size, f);
}
// For 32 bits systems, don't encode a 64 bits size_t
#if SIZE_MAX < 1ULL<< 32
else {
b = EOF != fputc(254, f); // Save 32 bits encoding
b &= EOF != fputc((unsigned char) (size >> 24), f);
b &= EOF != fputc((unsigned char) (size >> 16), f);
b &= EOF != fputc((unsigned char) (size >> 8), f);
b &= EOF != fputc((unsigned char) size, f);
}
#else
else if (size < 1ULL<< 32) {
b = EOF != fputc(254, f); // Save 32 bits encoding
b &= EOF != fputc((unsigned char) (size >> 24), f);
b &= EOF != fputc((unsigned char) (size >> 16), f);
b &= EOF != fputc((unsigned char) (size >> 8), f);
b &= EOF != fputc((unsigned char) size, f);
} else {
b = EOF != fputc(255, f); // Save 64 bits encoding
b &= EOF != fputc((unsigned char) (size >> 56), f);
b &= EOF != fputc((unsigned char) (size >> 48), f);
b &= EOF != fputc((unsigned char) (size >> 40), f);
b &= EOF != fputc((unsigned char) (size >> 32), f);
b &= EOF != fputc((unsigned char) (size >> 24), f);
b &= EOF != fputc((unsigned char) (size >> 16), f);
b &= EOF != fputc((unsigned char) (size >> 8), f);
b &= EOF != fputc((unsigned char) size, f);
}
#endif
return b;
}
/* Internal service:
* Read size_t in the stream from a compact form to reduce consumption
* (and I/O bandwidth)
*/
static inline bool
m_serial_bin_read_size(FILE *f, size_t *size)
{
int c;
c = fgetc(f);
if (M_UNLIKELY(c == EOF)) return false;
if (M_LIKELY(c < 253)) {
*size = (size_t) c;
return true;
}
size_t s = 0;
int l = (c = 255) ? 8 : (c == 254) ? 4 : 2;
for(int i = 0; i < l; i++) {
c = fgetc(f);
if (M_UNLIKELY(c == EOF)) return false;
s = (s << 8) | (size_t) c;
}
*size = s;
return true;
}
/* Write the boolean 'data' into the serial stream 'serial'.
Return M_SERIAL_OK_DONE if it succeeds, M_SERIAL_FAIL otherwise */
static inline m_serial_return_code_t
@@ -37,7 +111,7 @@ m_serial_bin_write_boolean(m_serial_write_t serial, const bool data)
{
FILE *f = (FILE *)serial->data[0].p;
size_t n = fwrite (M_ASSIGN_CAST(const void*, &data), sizeof (bool), 1, f);
return n == 1 ? M_SERIAL_OK_DONE : M_SERIAL_FAIL;
return n == 1 ? M_SERIAL_OK_DONE : m_core_serial_fail();
}
/* Write the integer 'data' of 'size_of_type' bytes into the serial stream 'serial'.
@@ -54,26 +128,26 @@ m_serial_bin_write_integer(m_serial_write_t serial,const long long data, const s
FILE *f = (FILE *)serial->data[0].p;
switch (size_of_type) {
case 1:
i8 = data;
i8 = (int8_t) data;
n = fwrite (M_ASSIGN_CAST(const void*, &i8), sizeof i8, 1, f);
break;
case 2:
i16 = data;
i16 = (int16_t) data;
n = fwrite (M_ASSIGN_CAST(const void*, &i16), sizeof i16, 1, f);
break;
case 4:
i32 = data;
i32 = (int32_t) data;
n = fwrite (M_ASSIGN_CAST(const void*, &i32), sizeof i32, 1, f);
break;
case 8:
i64 = data;
i64 = (int64_t) data;
n = fwrite (M_ASSIGN_CAST(const void*, &i64), sizeof i64, 1, f);
break;
default:
M_ASSERT_INIT(false, "an integer of suitable size");
M_ASSERT_INIT(false, "an integer of suitable size (8/16/32/64)");
break;
}
return n == 1 ? M_SERIAL_OK_DONE : M_SERIAL_FAIL;
return n == 1 ? M_SERIAL_OK_DONE : m_core_serial_fail();
}
/* Write the float 'data' of 'size_of_type' bytes into the serial stream 'serial'.
@@ -87,35 +161,35 @@ m_serial_bin_write_float(m_serial_write_t serial, const long double data, const
size_t n;
FILE *f = (FILE *)serial->data[0].p;
switch (size_of_type) {
case sizeof f1:
f1 = data;
if (size_of_type == sizeof f1) {
f1 = (float) data;
n = fwrite (M_ASSIGN_CAST(const void*, &f1), sizeof f1, 1, f);
break;
case sizeof f2:
f2 = data;
} else if (size_of_type == sizeof f2) {
f2 = (double) data;
n = fwrite (M_ASSIGN_CAST(const void*, &f2), sizeof f2, 1, f);
break;
case sizeof f3:
f3 = data;
} else if (size_of_type == sizeof f3) {
f3 = (long double) data;
n = fwrite (M_ASSIGN_CAST(const void*, &f3), sizeof f3, 1, f);
break;
default:
} else {
M_ASSERT_INIT(false, "a float of suitable size");
break;
}
return n == 1 ? M_SERIAL_OK_DONE : M_SERIAL_FAIL;
return n == 1 ? M_SERIAL_OK_DONE : m_core_serial_fail();
}
/* Write the null-terminated string 'data'into the serial stream 'serial'.
Return M_SERIAL_OK_DONE if it succeeds, M_SERIAL_FAIL otherwise */
static inline m_serial_return_code_t
m_serial_bin_write_string(m_serial_write_t serial, const char data[])
m_serial_bin_write_string(m_serial_write_t serial, const char data[], size_t length)
{
M_ASSERT_SLOW(length == strlen(data) );
FILE *f = (FILE *)serial->data[0].p;
size_t l = strlen(data);
size_t n = fwrite (M_ASSIGN_CAST(const void*, data), 1, l+1, f);
return n == l+1 ? M_SERIAL_OK_DONE : M_SERIAL_FAIL;
M_ASSERT(f != NULL && data != NULL);
// Write first the number of (non null) characters
if (m_serial_bin_write_size(f, length) != true) return m_core_serial_fail();
// Write the characters (excluding the final null char)
// NOTE: fwrite supports length == 0.
size_t n = fwrite (M_ASSIGN_CAST(const void*, data), 1, length, f);
return (n == length) ? M_SERIAL_OK_DONE : m_core_serial_fail();
}
/* Start writing an array of 'number_of_elements' objects into the serial stream 'serial'.
@@ -130,7 +204,7 @@ m_serial_bin_write_array_start(m_serial_local_t local, m_serial_write_t serial,
FILE *f = (FILE *)serial->data[0].p;
size_t n = fwrite (M_ASSIGN_CAST(const void*, &number_of_elements), sizeof number_of_elements, 1, f);
local->data[0].b = (number_of_elements == 0);
return n == 1 ? M_SERIAL_OK_CONTINUE : M_SERIAL_FAIL;
return n == 1 ? M_SERIAL_OK_CONTINUE : m_core_serial_fail();
}
/* Write an array separator between elements of an array into the serial stream 'serial' if needed.
@@ -143,7 +217,7 @@ m_serial_bin_write_array_next(m_serial_local_t local, m_serial_write_t serial)
if (local->data[0].b) {
size_t n = 0xABCDEF;
n = fwrite (M_ASSIGN_CAST(const void*, &n), sizeof n, 1, f);
return n == 1 ? M_SERIAL_OK_CONTINUE : M_SERIAL_FAIL;
return n == 1 ? M_SERIAL_OK_CONTINUE : m_core_serial_fail();
} else {
return M_SERIAL_OK_CONTINUE;
}
@@ -159,7 +233,7 @@ m_serial_bin_write_array_end(m_serial_local_t local, m_serial_write_t serial)
if (local->data[0].b) {
size_t n = 0x12345678;
n = fwrite (M_ASSIGN_CAST(const void*, &n), sizeof n, 1, f);
return n == 1 ? M_SERIAL_OK_CONTINUE : M_SERIAL_FAIL;
return n == 1 ? M_SERIAL_OK_CONTINUE : m_core_serial_fail();
} else {
return M_SERIAL_OK_CONTINUE;
}
@@ -223,7 +297,7 @@ m_serial_bin_write_variant_start(m_serial_local_t local, m_serial_write_t serial
(void) local;
FILE *f = (FILE *)serial->data[0].p;
size_t n = fwrite (M_ASSIGN_CAST(const void*, &index), sizeof index, 1, f);
return n == 1 ? ((index < 0) ? M_SERIAL_OK_DONE : M_SERIAL_OK_CONTINUE) : M_SERIAL_FAIL;
return n == 1 ? ((index < 0) ? M_SERIAL_OK_DONE : M_SERIAL_OK_CONTINUE) : m_core_serial_fail();
}
/* End Writing a variant into the serial stream 'serial'.
@@ -268,6 +342,13 @@ static inline void m_serial_bin_write_clear(m_serial_write_t serial)
}
/* Define a synonym of m_serial_read_t to the BIN serializer with its proper OPLIST */
typedef m_serial_write_t m_serial_bin_write_t;
#define M_OPL_m_serial_bin_write_t() \
(INIT_WITH(m_serial_bin_write_init), CLEAR(m_serial_bin_write_clear), \
TYPE(m_serial_bin_write_t), PROPERTIES(( LET_AS_INIT_WITH(1) )) )
/* Read from the stream 'serial' a boolean.
Set '*b' with the boolean value if succeeds
Return M_SERIAL_OK_DONE if it succeeds, M_SERIAL_FAIL otherwise */
@@ -275,7 +356,7 @@ static inline m_serial_return_code_t
m_serial_bin_read_boolean(m_serial_read_t serial, bool *b){
FILE *f = (FILE*) serial->data[0].p;
size_t n = fread (M_ASSIGN_CAST(void*, b), sizeof (bool), 1, f);
return n == 1 ? M_SERIAL_OK_DONE : M_SERIAL_FAIL;
return n == 1 ? M_SERIAL_OK_DONE : m_core_serial_fail();
}
/* Read from the stream 'serial' an integer that can be represented with 'size_of_type' bytes.
@@ -310,7 +391,7 @@ m_serial_bin_read_integer(m_serial_read_t serial, long long *i, const size_t siz
M_ASSERT_INIT(false, "an integer of suitable size");
break;
}
return n == 1 ? M_SERIAL_OK_DONE : M_SERIAL_FAIL;
return n == 1 ? M_SERIAL_OK_DONE : m_core_serial_fail();
}
/* Read from the stream 'serial' a float that can be represented with 'size_of_type' bytes.
@@ -323,24 +404,19 @@ m_serial_bin_read_float(m_serial_read_t serial, long double *r, const size_t siz
long double f3;
size_t n;
FILE *f = (FILE *)serial->data[0].p;
switch (size_of_type) {
case sizeof f1:
if (size_of_type == sizeof f1) {
n = fread (M_ASSIGN_CAST(void*, &f1), sizeof f1, 1, f);
*r = f1;
break;
case sizeof f2:
} else if (size_of_type == sizeof f2) {
n = fread (M_ASSIGN_CAST(void*, &f2), sizeof f2, 1, f);
*r = f2;
break;
case sizeof f3:
} else if (size_of_type == sizeof f3) {
n = fread (M_ASSIGN_CAST(void*, &f3), sizeof f3, 1, f);
*r = f3;
break;
default:
} else {
M_ASSERT_INIT(false, "a float of suitable size");
break;
}
return n == 1 ? M_SERIAL_OK_DONE : M_SERIAL_FAIL;
return n == 1 ? M_SERIAL_OK_DONE : m_core_serial_fail();
}
/* Read from the stream 'serial' a string.
@@ -349,14 +425,19 @@ m_serial_bin_read_float(m_serial_read_t serial, long double *r, const size_t siz
static inline m_serial_return_code_t
m_serial_bin_read_string(m_serial_read_t serial, struct string_s *s){
FILE *f = (FILE*) serial->data[0].p;
string_clean(s);
int c;
c = fgetc(f);
while (c != 0 && c != EOF) {
string_push_back(s, c);
c = fgetc(f);
}
return c != EOF ? M_SERIAL_OK_DONE : M_SERIAL_FAIL;
M_ASSERT(f != NULL && s != NULL);
// First read the number of non null characters
size_t length;
if (m_serial_bin_read_size(f, &length) != true) return m_core_serial_fail();
// Use of internal string interface to dimension the string
char *p = m_str1ng_fit2size(s, length + 1);
m_str1ng_set_size(s, length);
// Read the characters excluding the final null one.
// NOTE: fread supports length == 0.
size_t n = fread(M_ASSIGN_CAST(void*, p), 1, length, f);
// Force the final null character
p[length] = 0;
return (n == length) ? M_SERIAL_OK_DONE : m_core_serial_fail();
}
/* Start reading from the stream 'serial' an array.
@@ -372,7 +453,7 @@ m_serial_bin_read_array_start(m_serial_local_t local, m_serial_read_t serial, si
FILE *f = (FILE*) serial->data[0].p;
size_t n = fread (M_ASSIGN_CAST(void*, num), sizeof *num, 1, f);
if (n != 1)
return M_SERIAL_FAIL;
return m_core_serial_fail();
local->data[0].b = (*num == 0);
local->data[1].s = *num;
if (local->data[0].b) {
@@ -380,8 +461,8 @@ m_serial_bin_read_array_start(m_serial_local_t local, m_serial_read_t serial, si
size_t p;
n = fread (M_ASSIGN_CAST(void*, &p), sizeof p, 1, f);
if (n != 1)
return M_SERIAL_FAIL;
return p == 0xABCDEF ? M_SERIAL_OK_CONTINUE : p == 0x12345678 ? M_SERIAL_OK_DONE : M_SERIAL_FAIL;
return m_core_serial_fail();
return p == 0xABCDEF ? M_SERIAL_OK_CONTINUE : p == 0x12345678 ? M_SERIAL_OK_DONE : m_core_serial_fail();
}
return M_SERIAL_OK_CONTINUE;
}
@@ -399,10 +480,10 @@ m_serial_bin_read_array_next(m_serial_local_t local, m_serial_read_t serial)
size_t p, n;
n = fread (M_ASSIGN_CAST(void*, &p), sizeof p, 1, f);
if (n != 1)
return M_SERIAL_FAIL;
return p == 0xABCDEF ? M_SERIAL_OK_CONTINUE : p == 0x12345678 ? M_SERIAL_OK_DONE : M_SERIAL_FAIL;
return m_core_serial_fail();
return p == 0xABCDEF ? M_SERIAL_OK_CONTINUE : p == 0x12345678 ? M_SERIAL_OK_DONE : m_core_serial_fail();
} else {
assert(local->data[1].s > 0);
M_ASSERT(local->data[1].s > 0);
local->data[1].s --;
return local->data[1].s == 0 ? M_SERIAL_OK_DONE : M_SERIAL_OK_CONTINUE;
}
@@ -427,7 +508,7 @@ static inline m_serial_return_code_t
m_serial_bin_read_tuple_start(m_serial_local_t local, m_serial_read_t serial)
{
(void) serial;
local->data[1].s = 0;
local->data[1].i = 0;
return M_SERIAL_OK_CONTINUE;
}
@@ -443,8 +524,8 @@ m_serial_bin_read_tuple_id(m_serial_local_t local, m_serial_read_t serial, const
(void) serial;
(void) field_name;
(void) max;
*id = local->data[1].s;
local->data[1].s ++;
*id = local->data[1].i;
local->data[1].i ++;
return (*id == max) ? M_SERIAL_OK_DONE : M_SERIAL_OK_CONTINUE;
}
@@ -462,7 +543,7 @@ m_serial_bin_read_variant_start(m_serial_local_t local, m_serial_read_t serial,
(void) local; // argument not used
FILE *f = (FILE*) serial->data[0].p;
size_t n = fread (M_ASSIGN_CAST(void*, id), sizeof *id, 1, f);
return n == 1 ? ((*id < 0) ? M_SERIAL_OK_DONE : M_SERIAL_OK_CONTINUE) : M_SERIAL_FAIL;
return n == 1 ? ((*id < 0) ? M_SERIAL_OK_DONE : M_SERIAL_OK_CONTINUE) : m_core_serial_fail();
}
/* End reading a variant from the stream 'serial'.
@@ -503,4 +584,12 @@ static inline void m_serial_bin_read_clear(m_serial_read_t serial)
(void) serial; // Nothing to do
}
/* Define a synonym of m_serial_read_t to the BIN serializer with its proper OPLIST */
typedef m_serial_read_t m_serial_bin_read_t;
#define M_OPL_m_serial_bin_read_t() \
(INIT_WITH(m_serial_bin_read_init), CLEAR(m_serial_bin_read_clear), \
TYPE(m_serial_bin_read_t), PROPERTIES(( LET_AS_INIT_WITH(1) )) )
M_END_PROTECTED_CODE
#endif
+718 -64
View File
File diff suppressed because it is too large. Load diff
+435 -354
View File
@@ -1,7 +1,7 @@
/*
* M*LIB - SHARED Module
*
* Copyright (c) 2017-2019, Patrick Pelissier
* Copyright (c) 2017-2021, Patrick Pelissier
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
@@ -29,392 +29,473 @@
#include "m-atomic.h"
#include "m-genint.h"
M_BEGIN_PROTECTED_CODE
/* Define the oplist of a shared pointer.
USAGE: SHARED_OPLIST(name [, oplist_of_the_type]) */
#define SHARED_PTR_OPLIST(...) \
SHAREDI_PTR_OPLIST_P1(M_IF_NARGS_EQ1(__VA_ARGS__) \
((__VA_ARGS__, M_DEFAULT_OPLIST ), \
_OPLIST(__VA_ARGS__ )))
#define SHARED_PTR_OPLIST(...) \
M_SHAR3D_PTR_OPLIST_P1(M_IF_NARGS_EQ1(__VA_ARGS__) \
((__VA_ARGS__, M_DEFAULT_OPLIST ), \
(__VA_ARGS__ )))
/* Define shared pointer and its function.
USAGE: SHARED_PTR_DEF(name, type, [, oplist]) */
#define SHARED_PTR_DEF(name, ...) \
SHAREDI_PTR_DEF_P1(M_IF_NARGS_EQ1(__VA_ARGS__) \
((name, __VA_ARGS__, M_GLOBAL_OPLIST_OR_DEF(__VA_ARGS__)(), SHAREDI_ATOMIC_OPLIST ), \
(name, __VA_ARGS__ , SHAREDI_ATOMIC_OPLIST)))
#define SHARED_PTR_DEF(name, ...) \
SHARED_PTR_DEF_AS(name, M_C(name,_t), __VA_ARGS__)
/* Define shared pointer and its function
as the given name name_t
USAGE: SHARED_PTR_DEF_AS(name, name_t, type, [, oplist]) */
#define SHARED_PTR_DEF_AS(name, name_t, ...) \
M_BEGIN_PROTECTED_CODE \
M_SHAR3D_PTR_DEF_P1(M_IF_NARGS_EQ1(__VA_ARGS__) \
((name, __VA_ARGS__, M_GLOBAL_OPLIST_OR_DEF(__VA_ARGS__)(), M_SHAR3D_ATOMIC_OPLIST, name_t ), \
(name, __VA_ARGS__ , M_SHAR3D_ATOMIC_OPLIST, name_t ))) \
M_END_PROTECTED_CODE
/* Define relaxed shared pointer and its function (thread unsafe).
USAGE: SHARED_PTR_RELAXED_DEF(name, type, [, oplist]) */
#define SHARED_PTR_RELAXED_DEF(name, ...) \
SHAREDI_PTR_DEF_P1(M_IF_NARGS_EQ1(__VA_ARGS__) \
((name, __VA_ARGS__, M_GLOBAL_OPLIST_OR_DEF(__VA_ARGS__)(), SHAREDI_INTEGER_OPLIST ), \
(name, __VA_ARGS__ , SHAREDI_INTEGER_OPLIST)))
#define SHARED_PTR_RELAXED_DEF(name, ...) \
SHARED_PTR_RELAXED_DEF_AS(name, M_C(name,_t), __VA_ARGS__)
/* Define relaxed shared pointer and its function (thread unsafe)
as the given name name_t
USAGE: SHARED_PTR_RELAXED_DEF(name, type, [, oplist]) */
#define SHARED_PTR_RELAXED_DEF_AS(name, name_t, ...) \
M_BEGIN_PROTECTED_CODE \
M_SHAR3D_PTR_DEF_P1(M_IF_NARGS_EQ1(__VA_ARGS__) \
((name, __VA_ARGS__, M_GLOBAL_OPLIST_OR_DEF(__VA_ARGS__)(), M_SHAR3D_INTEGER_OPLIST, name_t ), \
(name, __VA_ARGS__, M_SHAR3D_INTEGER_OPLIST, name_t ))) \
M_END_PROTECTED_CODE
/* Define shared resource and its function.
This is a bounded pool of resource shared by multiple owners.
USAGE: SHARED_RESOURCE_DEF(name, type, [, oplist]) */
#define SHARED_RESOURCE_DEF(name, ...) \
SHAREDI_RESOURCE_DEF_P1(M_IF_NARGS_EQ1(__VA_ARGS__) \
((name, __VA_ARGS__, M_GLOBAL_OPLIST_OR_DEF(__VA_ARGS__) ), \
(name, __VA_ARGS__)))
#define SHARED_RESOURCE_DEF(name, ...) \
SHARED_RESOURCE_DEF_AS(name, M_C(name,_t), M_C(name,_it_t), __VA_ARGS__)
/* Define shared resource and its function
as the given name named_t and the iterator it_t
This is a bounded pool of resource shared by multiple owners.
USAGE: SHARED_RESOURCE_DEF_AS(name, name_t, it_t, type, [, oplist]) */
#define SHARED_RESOURCE_DEF_AS(name, name_t, it_t, ...) \
M_BEGIN_PROTECTED_CODE \
M_SHAR3D_RESOURCE_DEF_P1(M_IF_NARGS_EQ1(__VA_ARGS__) \
((name, __VA_ARGS__, M_GLOBAL_OPLIST_OR_DEF(__VA_ARGS__)(), name_t, it_t ), \
(name, __VA_ARGS__, name_t, it_t ))) \
M_END_PROTECTED_CODE
/********************************** INTERNAL ************************************/
// deferred
#define SHAREDI_PTR_OPLIST_P1(arg) SHAREDI_PTR_OPLIST_P2 arg
// deferred evaluation
#define M_SHAR3D_PTR_OPLIST_P1(arg) M_SHAR3D_PTR_OPLIST_P2 arg
#define SHAREDI_PTR_OPLIST_P2(name, oplist) ( \
INIT(M_C(name, _init)), \
CLEAR(M_C(name, _clear)), \
INIT_SET(M_C(name, _init_set)), \
SET(M_C(name, _set)) \
INIT_MOVE(M_C(name, _init_move)), \
CLEAN(M_C(name, _clean)), \
MOVE(M_C(name, _move)), \
SWAP(M_C(name, _swap)) \
,M_IF_METHOD(NEW, oplist)(NEW(M_GET_NEW oplist),) \
,M_IF_METHOD(REALLOC, oplist)(REALLOC(M_GET_REALLOC oplist),) \
,M_IF_METHOD(DEL, oplist)(DEL(M_GET_DEL oplist),) \
/* Validation of the given, shared_t oplist */
#define M_SHAR3D_PTR_OPLIST_P2(name, oplist) \
M_IF_OPLIST(oplist)(M_SHAR3D_PTR_OPLIST_P3, M_SHAR3D_PTR_OPLIST_FAILURE)(name, oplist)
/* Prepare a clean compilation failure */
#define M_SHAR3D_PTR_OPLIST_FAILURE(name, oplist) \
((M_LIB_ERROR(ARGUMENT_OF_SHARED_PTR_OPLIST_IS_NOT_AN_OPLIST, name, oplist)))
#define M_SHAR3D_PTR_OPLIST_P3(name, oplist) ( \
INIT(M_C(name, _init)), \
CLEAR(M_C(name, _clear)), \
INIT_SET(M_C(name, _init_set)), \
SET(M_C(name, _set)) \
INIT_MOVE(M_C(name, _init_move)), \
RESET(M_C(name, _reset)), \
MOVE(M_C(name, _move)), \
SWAP(M_C(name, _swap)) \
,NAME(name) \
,TYPE(M_C(name, _ct)) \
,M_IF_METHOD(NEW, oplist)(NEW(M_GET_NEW oplist),) \
,M_IF_METHOD(REALLOC, oplist)(REALLOC(M_GET_REALLOC oplist),) \
,M_IF_METHOD(DEL, oplist)(DEL(M_GET_DEL oplist),) \
)
// deferred
#define SHAREDI_PTR_DEF_P1(arg) SHAREDI_PTR_DEF_P2 arg
// OPLIST to handle a counter of atomic type
#define SHAREDI_ATOMIC_OPLIST (TYPE(atomic_int), \
INIT_SET(atomic_init), \
ADD(atomic_fetch_add), \
SUB(atomic_fetch_sub), \
#define M_SHAR3D_ATOMIC_OPLIST (TYPE(atomic_int), \
INIT_SET(atomic_init), \
ADD(atomic_fetch_add), \
SUB(atomic_fetch_sub), \
IT_CREF(atomic_load))
// OPLIST to handle a counter of non-atomic type with its helper functions.
#define SHAREDI_INTEGER_OPLIST (TYPE(int), \
INIT_SET(sharedi_integer_init_set), \
ADD(sharedi_integer_add), \
SUB(sharedi_integer_sub), \
IT_CREF(sharedi_integer_cref))
static inline void sharedi_integer_init_set(int *p, int val) { *p = val; }
static inline int sharedi_integer_add(int *p, int val) { int r = *p; *p += val; return r; }
static inline int sharedi_integer_sub(int *p, int val) { int r = *p; *p -= val; return r; }
static inline int sharedi_integer_cref(int *p) { return *p; }
// OPLIST to handle a counter of non-atomic type
#define M_SHAR3D_INTEGER_OPLIST (TYPE(int), \
INIT_SET(m_shar3d_integer_init_set), \
ADD(m_shar3d_integer_add), \
SUB(m_shar3d_integer_sub), \
IT_CREF(m_shar3d_integer_cref))
#define SHAREDI_CONTRACT(shared, cpt_oplist) do { \
assert(shared != NULL); \
assert(*shared == NULL || M_CALL_IT_CREF(cpt_oplist, &(*shared)->cpt) >= 1); \
/* Atomic like interface for basic integers */
static inline void m_shar3d_integer_init_set(int *p, int val) { *p = val; }
static inline int m_shar3d_integer_add(int *p, int val) { int r = *p; *p += val; return r; }
static inline int m_shar3d_integer_sub(int *p, int val) { int r = *p; *p -= val; return r; }
static inline int m_shar3d_integer_cref(int *p) { return *p; }
/* Contract of a shared pointer */
#define M_SHAR3D_CONTRACT(shared, cpt_oplist) do { \
M_ASSERT(shared != NULL); \
M_ASSERT(*shared == NULL || M_CALL_IT_CREF(cpt_oplist, &(*shared)->cpt) >= 1); \
} while (0)
#define SHAREDI_PTR_DEF_P2(name, type, oplist, cpt_oplist) \
\
typedef struct M_C(name, _s){ \
type *data; /* Pointer to the data */ \
M_GET_TYPE cpt_oplist cpt; /* Counter of how many points to the data */ \
bool combineAlloc; /* Does the data and the ptr share the slot? */ \
} *M_C(name, _t)[1]; \
typedef struct M_C(name, _s) *M_C(name, _ptr); \
typedef const struct M_C(name, _s) *M_C(name, _srcptr); \
\
typedef struct M_C(name, combine_s) { \
type data; \
struct M_C(name, _s) ptr; \
} M_C(name, combine_t)[1]; \
\
static inline void \
M_C(name, _init)(M_C(name, _t) shared) \
{ \
*shared = NULL; \
} \
\
static inline void \
M_C(name, _init2)(M_C(name, _t) shared, type *data) \
{ \
assert (shared != NULL); \
/* The shared ptr get exclusive access to data */ \
struct M_C(name, _s) *ptr; \
if (M_UNLIKELY (data == NULL)) { \
*shared = NULL; \
return; \
} \
ptr = M_CALL_NEW(oplist, struct M_C(name, _s)); \
if (M_UNLIKELY (ptr == NULL)) { \
M_MEMORY_FULL(sizeof(struct M_C(name, _s))); \
return; \
} \
ptr->data = data; \
M_CALL_INIT_SET(cpt_oplist, &ptr->cpt, 1); \
ptr->combineAlloc = false; \
*shared = ptr; \
SHAREDI_CONTRACT(shared, cpt_oplist); \
} \
\
static inline void \
M_C(name, _init_new)(M_C(name, _t) shared) \
{ \
/* NOTE: Alloc 1 struct with both structures. */ \
struct M_C(name, combine_s) *p = \
M_CALL_NEW(oplist, struct M_C(name, combine_s)); \
if (M_UNLIKELY (p == NULL)) { \
M_MEMORY_FULL(sizeof(struct M_C(name, combine_s))); \
return; \
} \
struct M_C(name, _s) *ptr = &p->ptr; \
type *data = &p->data; \
M_CALL_INIT( oplist, *data); \
ptr->data = data; \
M_CALL_INIT_SET(cpt_oplist, &ptr->cpt, 1); \
ptr->combineAlloc = true; \
*shared = ptr; \
SHAREDI_CONTRACT(shared, cpt_oplist); \
} \
\
static inline bool \
M_C(name, _NULL_p)(const M_C(name, _t) shared) \
{ \
SHAREDI_CONTRACT(shared, cpt_oplist); \
return *shared == NULL; \
} \
\
static inline void \
M_C(name, _init_set)(M_C(name, _t) dest, \
const M_C(name, _t) shared) \
{ \
SHAREDI_CONTRACT(shared, cpt_oplist); \
assert (dest != shared); \
*dest = *shared; \
if (*dest != NULL) { \
int n = M_CALL_ADD(cpt_oplist, &((*dest)->cpt), 1); \
(void) n; /* unused return value */ \
} \
SHAREDI_CONTRACT(dest, cpt_oplist); \
} \
\
static inline void \
M_C(name, _clear)(M_C(name, _t) dest) \
{ \
SHAREDI_CONTRACT(dest, cpt_oplist); \
if (*dest != NULL) { \
if (M_CALL_SUB(cpt_oplist, &((*dest)->cpt), 1) == 1) { \
bool combineAlloc = (*dest)->combineAlloc; \
/* Note: if combineAlloc is true, the address of the slot \
combining both data & ptr is the same as the address of the \
first element, aka data itself. Static analyzer tools don't \
seem to detect this and report error. */ \
M_CALL_CLEAR(oplist, *(*dest)->data); \
M_CALL_DEL(oplist, (*dest)->data); \
if (combineAlloc == false) \
M_CALL_DEL(oplist, *dest); \
} \
*dest = NULL; \
} \
SHAREDI_CONTRACT(dest, cpt_oplist); \
} \
\
static inline void \
M_C(name, _clean)(M_C(name, _t) dest) \
{ \
/* NOTE: Clear will also set dest to NULL */ \
M_C(name, _clear)(dest); \
} \
\
static inline void \
M_C(name, _set)(M_C(name, _t) dest, \
const M_C(name, _t) shared) \
{ \
SHAREDI_CONTRACT(dest, cpt_oplist); \
SHAREDI_CONTRACT(shared, cpt_oplist); \
M_C(name, _clear)(dest); \
M_C(name, _init_set)(dest, shared); \
} \
\
static inline void \
M_C(name, _init_move)(M_C(name, _t) dest, \
M_C(name, _t) shared) \
{ \
SHAREDI_CONTRACT(shared, cpt_oplist); \
assert (dest != NULL && dest != shared); \
*dest = *shared; \
*shared = NULL; \
SHAREDI_CONTRACT(dest, cpt_oplist); \
} \
\
static inline void \
M_C(name, _move)(M_C(name, _t) dest, \
M_C(name, _t) shared) \
{ \
SHAREDI_CONTRACT(dest, cpt_oplist); \
SHAREDI_CONTRACT(shared, cpt_oplist); \
assert (dest != shared); \
M_C(name, _clear)(dest); \
M_C(name, _init_move)(dest, shared); \
} \
\
static inline void \
M_C(name, _swap)(M_C(name, _t) p1, \
M_C(name, _t) p2) \
{ \
SHAREDI_CONTRACT(p1, cpt_oplist); \
SHAREDI_CONTRACT(p2, cpt_oplist); \
M_SWAP (struct M_C(name, _s)*, *p1, *p2); \
SHAREDI_CONTRACT(p1, cpt_oplist); \
SHAREDI_CONTRACT(p2, cpt_oplist); \
} \
\
static inline bool \
M_C(name, _equal_p)(const M_C(name, _t) p1, \
const M_C(name, _t) p2) \
{ \
SHAREDI_CONTRACT(p1, cpt_oplist); \
SHAREDI_CONTRACT(p2, cpt_oplist); \
return *p1 == *p2; \
} \
\
static inline type const * \
M_C(name, _cref)(const M_C(name, _t) shared) \
{ \
SHAREDI_CONTRACT(shared, cpt_oplist); \
assert(*shared != NULL); \
type *data = (*shared)->data; \
assert (data != NULL); \
return M_CONST_CAST (type, data); \
} \
\
static inline type * \
M_C(name, _ref)(M_C(name, _t) shared) \
{ \
SHAREDI_CONTRACT(shared, cpt_oplist); \
assert(*shared != NULL); \
type *data = (*shared)->data; \
assert (data != NULL); \
return data; \
} \
// deferred evaluation
#define M_SHAR3D_PTR_DEF_P1(arg) M_SHAR3D_PTR_DEF_P2 arg
/* Validate the oplist before going further */
#define M_SHAR3D_PTR_DEF_P2(name, type, oplist, cpt_oplist, shared_t) \
M_IF_OPLIST(oplist)(M_SHAR3D_PTR_DEF_P3, M_SHAR3D_PTR_DEF_FAILURE)(name, type, oplist, cpt_oplist, shared_t)
/* Stop processing with a compilation failure */
#define M_SHAR3D_PTR_DEF_FAILURE(name, type, oplist, cpt_oplist, shared_t) \
M_STATIC_FAILURE(M_LIB_NOT_AN_OPLIST, "(SHARED_PTR_DEF): the given argument is not a valid oplist: " #oplist)
/* Code generation */
#define M_SHAR3D_PTR_DEF_P3(name, type, oplist, cpt_oplist, shared_t) \
\
typedef struct M_C(name, _s){ \
type *data; /* Pointer to the data */ \
M_GET_TYPE cpt_oplist cpt; /* Counter of how many refs the data */ \
bool combineAlloc; /* Does the data and the ptr share the slot? */ \
} *shared_t[1]; \
typedef struct M_C(name, _s) *M_C(name, _ptr); \
typedef const struct M_C(name, _s) *M_C(name, _srcptr); \
\
/* Internal type for oplist */ \
typedef shared_t M_C(name, _ct); \
\
typedef struct M_C(name, combine_s) { \
type data; \
struct M_C(name, _s) ptr; \
} M_C(name, combine_ct)[1]; \
\
M_CHECK_COMPATIBLE_OPLIST(name, 1, type, oplist) \
\
static inline void \
M_C(name, _init)(shared_t shared) \
{ \
*shared = NULL; \
} \
\
static inline void \
M_C(name, _init2)(shared_t shared, type *data) \
{ \
M_ASSERT (shared != NULL); \
/* The shared ptr get exclusive access to data */ \
struct M_C(name, _s) *ptr; \
if (M_UNLIKELY (data == NULL)) { \
*shared = NULL; \
return; \
} \
ptr = M_CALL_NEW(oplist, struct M_C(name, _s)); \
if (M_UNLIKELY (ptr == NULL)) { \
M_MEMORY_FULL(sizeof(struct M_C(name, _s))); \
return; \
} \
ptr->data = data; \
M_CALL_INIT_SET(cpt_oplist, &ptr->cpt, 1); \
ptr->combineAlloc = false; \
*shared = ptr; \
M_SHAR3D_CONTRACT(shared, cpt_oplist); \
} \
\
static inline void \
M_C(name, _init_new)(shared_t shared) \
{ \
/* NOTE: Alloc 1 struct with both structures. */ \
struct M_C(name, combine_s) *p = \
M_CALL_NEW(oplist, struct M_C(name, combine_s)); \
if (M_UNLIKELY (p == NULL)) { \
M_MEMORY_FULL(sizeof(struct M_C(name, combine_s))); \
return; \
} \
struct M_C(name, _s) *ptr = &p->ptr; \
type *data = &p->data; \
M_CALL_INIT( oplist, *data); \
ptr->data = data; \
M_CALL_INIT_SET(cpt_oplist, &ptr->cpt, 1); \
ptr->combineAlloc = true; \
*shared = ptr; \
M_SHAR3D_CONTRACT(shared, cpt_oplist); \
} \
\
static inline bool \
M_C(name, _NULL_p)(const shared_t shared) \
{ \
M_SHAR3D_CONTRACT(shared, cpt_oplist); \
return *shared == NULL; \
} \
\
static inline void \
M_C(name, _init_set)(shared_t dest, \
const shared_t shared) \
{ \
M_SHAR3D_CONTRACT(shared, cpt_oplist); \
M_ASSERT (dest != shared); \
*dest = *shared; \
if (*dest != NULL) { \
int n = M_CALL_ADD(cpt_oplist, &((*dest)->cpt), 1); \
(void) n; /* unused return value */ \
} \
M_SHAR3D_CONTRACT(dest, cpt_oplist); \
} \
\
static inline void \
M_C(name, _clear)(shared_t dest) \
{ \
M_SHAR3D_CONTRACT(dest, cpt_oplist); \
if (*dest != NULL) { \
if (M_CALL_SUB(cpt_oplist, &((*dest)->cpt), 1) == 1) { \
bool combineAlloc = (*dest)->combineAlloc; \
/* Note: if combineAlloc is true, the address of the slot \
combining both data & ptr is the same as the address of the \
first element, aka data itself. Static analyzer tools don't \
seem to detect this and report error. */ \
M_CALL_CLEAR(oplist, *(*dest)->data); \
M_CALL_DEL(oplist, (*dest)->data); \
if (combineAlloc == false) \
M_CALL_DEL(oplist, *dest); \
} \
*dest = NULL; \
} \
M_SHAR3D_CONTRACT(dest, cpt_oplist); \
} \
\
static inline void \
M_C(name, _reset)(shared_t dest) \
{ \
/* NOTE: Clear will also set dest to NULL */ \
M_C(name, _clear)(dest); \
} \
\
static inline void M_ATTR_DEPRECATED \
M_C(name, _clean)(shared_t dest) \
{ \
M_C(name, _reset)(dest); \
} \
\
static inline void \
M_C(name, _set)(shared_t dest, \
const shared_t shared) \
{ \
M_SHAR3D_CONTRACT(dest, cpt_oplist); \
M_SHAR3D_CONTRACT(shared, cpt_oplist); \
M_C(name, _clear)(dest); \
M_C(name, _init_set)(dest, shared); \
} \
\
static inline void \
M_C(name, _init_move)(shared_t dest, \
shared_t shared) \
{ \
M_SHAR3D_CONTRACT(shared, cpt_oplist); \
M_ASSERT (dest != NULL && dest != shared); \
*dest = *shared; \
*shared = NULL; \
M_SHAR3D_CONTRACT(dest, cpt_oplist); \
} \
\
static inline void \
M_C(name, _move)(shared_t dest, \
shared_t shared) \
{ \
M_SHAR3D_CONTRACT(dest, cpt_oplist); \
M_SHAR3D_CONTRACT(shared, cpt_oplist); \
M_ASSERT (dest != shared); \
M_C(name, _clear)(dest); \
M_C(name, _init_move)(dest, shared); \
} \
\
static inline void \
M_C(name, _swap)(shared_t p1, \
shared_t p2) \
{ \
M_SHAR3D_CONTRACT(p1, cpt_oplist); \
M_SHAR3D_CONTRACT(p2, cpt_oplist); \
/* NOTE: SWAP is not atomic */ \
M_SWAP (struct M_C(name, _s)*, *p1, *p2); \
M_SHAR3D_CONTRACT(p1, cpt_oplist); \
M_SHAR3D_CONTRACT(p2, cpt_oplist); \
} \
\
static inline bool \
M_C(name, _equal_p)(const shared_t p1, \
const shared_t p2) \
{ \
M_SHAR3D_CONTRACT(p1, cpt_oplist); \
M_SHAR3D_CONTRACT(p2, cpt_oplist); \
return *p1 == *p2; \
} \
\
static inline type const * \
M_C(name, _cref)(const shared_t shared) \
{ \
M_SHAR3D_CONTRACT(shared, cpt_oplist); \
M_ASSERT(*shared != NULL); \
type *data = (*shared)->data; \
M_ASSERT (data != NULL); \
return M_CONST_CAST (type, data); \
} \
\
static inline type * \
M_C(name, _ref)(shared_t shared) \
{ \
M_SHAR3D_CONTRACT(shared, cpt_oplist); \
M_ASSERT(*shared != NULL); \
type *data = (*shared)->data; \
M_ASSERT (data != NULL); \
return data; \
} \
/********************************** SHARED RESOURCE ************************************/
#define SHAREDI_RESOURCE_CONTRACT(s) do { \
assert (s != NULL); \
assert (s->buffer != NULL); \
#define M_SHAR3D_RESOURCE_CONTRACT(s) do { \
M_ASSERT (s != NULL); \
M_ASSERT (s->buffer != NULL); \
} while (0)
// deferred
#define SHAREDI_RESOURCE_DEF_P1(arg) SHAREDI_RESOURCE_DEF_P2 arg
#define M_SHAR3D_RESOURCE_DEF_P1(arg) M_SHAR3D_RESOURCE_DEF_P2 arg
#define SHAREDI_RESOURCE_DEF_P2(name, type, oplist) \
\
/* Create an aligned type to avoid false sharing between threads */ \
typedef struct M_C(name, _atype_s) { \
atomic_uint cpt; \
type x; \
M_CACHELINE_ALIGN(align, type, atomic_uint); \
} M_C(name, _atype_t); \
\
typedef struct M_C(name, _s) { \
genint_t core; \
M_C(name, _atype_t) *buffer; \
} M_C(name, _t)[1]; \
\
typedef struct M_C(name, _it_s) { \
unsigned int idx; \
struct M_C(name, _s) *ref; \
} M_C(name, _it_t)[1]; \
\
static inline void \
M_C(name, _init)(M_C(name, _t) s, size_t n) \
{ \
assert(s != NULL); \
assert (n > 0); \
s->buffer = M_CALL_REALLOC(oplist, M_C(name, _atype_t), NULL, n); \
if (M_UNLIKELY (s->buffer == NULL)) { \
M_MEMORY_FULL(sizeof(M_C(name, _atype_t)) * n); \
return; \
} \
for(size_t i = 0; i < n; i++) { \
M_CALL_INIT(oplist, s->buffer[i].x); \
atomic_init (&s->buffer[i].cpt, 0U); \
} \
genint_init(s->core, n); \
SHAREDI_RESOURCE_CONTRACT(s); \
} \
\
static inline void \
M_C(name, _clear)(M_C(name, _t) s) \
{ \
SHAREDI_RESOURCE_CONTRACT(s); \
size_t n = genint_size(s->core); \
for(size_t i = 0; i < n; i++) { \
M_CALL_CLEAR(oplist, s->buffer[i].x); \
} \
M_CALL_FREE(oplist, s->buffer); \
s->buffer = NULL; \
genint_clear(s->core); \
} \
\
static inline void \
M_C(name, _it)(M_C(name, _it_t) it, M_C(name, _t) s) \
{ \
SHAREDI_RESOURCE_CONTRACT(s); \
assert (it != NULL); \
unsigned int idx = genint_pop(s->core); \
it->idx = idx; \
it->ref = s; \
if (M_LIKELY (idx != GENINT_ERROR)) { \
assert(atomic_load(&s->buffer[idx].cpt) == 0); \
atomic_store(&s->buffer[idx].cpt, 1U); \
} \
} \
\
static inline bool \
M_C(name, _end_p)(M_C(name, _it_t) it) \
{ \
assert (it != NULL); \
return it->idx == GENINT_ERROR; \
} \
\
static inline type * \
M_C(name, _ref)(M_C(name, _it_t) it) \
{ \
assert (it != NULL && it->ref != NULL && it->idx != GENINT_ERROR); \
SHAREDI_RESOURCE_CONTRACT(it->ref); \
return &it->ref->buffer[it->idx].x; \
} \
\
static inline type const * \
M_C(name, _cref)(M_C(name, _it_t) it) \
{ \
assert (it != NULL && it->ref != NULL && it->idx != GENINT_ERROR); \
SHAREDI_RESOURCE_CONTRACT(it->ref); \
return M_CONST_CAST (type, &it->ref->buffer[it->idx].x); \
} \
\
static inline void \
M_C(name, _end)(M_C(name, _it_t) it, M_C(name, _t) s) \
{ \
SHAREDI_RESOURCE_CONTRACT(s); \
assert (it != NULL); \
assert (it->ref == s); \
unsigned int idx = it->idx; \
if (M_LIKELY (idx != GENINT_ERROR)) { \
unsigned int c = atomic_fetch_sub (&it->ref->buffer[idx].cpt, 1U); \
if (c == 1) { \
genint_push(it->ref->core, idx); \
} \
it->idx = GENINT_ERROR; \
} \
} \
\
static inline void \
M_C(name, _it_set)(M_C(name, _it_t) itd, M_C(name, _it_t) its) \
{ \
assert (itd != NULL && its != NULL); \
SHAREDI_RESOURCE_CONTRACT(its->ref); \
itd->ref = its->ref; \
unsigned int idx = its->idx; \
itd->idx = idx; \
if (M_LIKELY (idx != GENINT_ERROR)) { \
unsigned int c = atomic_fetch_add(&itd->ref->buffer[idx].cpt, 1U); \
assert (c >= 1); \
} \
} \
/* Validate the oplist before going further */
#define M_SHAR3D_RESOURCE_DEF_P2(name, type, oplist, shared_t, it_t) \
M_IF_OPLIST(oplist)(M_SHAR3D_RESOURCE_DEF_P3, M_SHAR3D_RESOURCE_DEF_FAILURE)(name, type, oplist, shared_t, it_t)
/* Stop processing with a compilation failure */
#define M_SHAR3D_RESOURCE_DEF_FAILURE(name, type, oplist, shared_t, it_t) \
M_STATIC_FAILURE(M_LIB_NOT_AN_OPLIST, "(SHARED_RESOURCE_DEF): the given argument is not a valid oplist: " #oplist)
#define M_SHAR3D_RESOURCE_DEF_P3(name, type, oplist, shared_t, it_t) \
\
/* Create an aligned type to avoid false sharing between threads */ \
typedef struct M_C(name, _atype_s) { \
atomic_uint cpt; \
type x; \
M_CACHELINE_ALIGN(align, type, atomic_uint); \
} M_C(name, _atype_ct); \
\
typedef struct M_C(name, _s) { \
genint_t core; \
M_C(name, _atype_ct) *buffer; \
} shared_t[1]; \
\
typedef struct M_C(name, _it_s) { \
unsigned int idx; \
struct M_C(name, _s) *ref; \
} it_t[1]; \
\
/* Internal Types for oplist */ \
typedef shared_t M_C(name, _ct); \
\
static inline void \
M_C(name, _init)(shared_t s, size_t n) \
{ \
M_ASSERT(s != NULL); \
M_ASSERT (n > 0 && n < UINT_MAX); \
s->buffer = M_CALL_REALLOC(oplist, M_C(name, _atype_ct), NULL, n); \
if (M_UNLIKELY (s->buffer == NULL)) { \
M_MEMORY_FULL(sizeof(M_C(name, _atype_ct)) * n); \
return; \
} \
for(size_t i = 0; i < n; i++) { \
M_CALL_INIT(oplist, s->buffer[i].x); \
atomic_init (&s->buffer[i].cpt, 0U); \
} \
genint_init(s->core, (unsigned int) n); \
M_SHAR3D_RESOURCE_CONTRACT(s); \
} \
\
static inline void \
M_C(name, _clear)(shared_t s) \
{ \
M_SHAR3D_RESOURCE_CONTRACT(s); \
size_t n = genint_size(s->core); \
for(size_t i = 0; i < n; i++) { \
M_CALL_CLEAR(oplist, s->buffer[i].x); \
} \
M_CALL_FREE(oplist, s->buffer); \
s->buffer = NULL; \
genint_clear(s->core); \
} \
\
static inline void \
M_C(name, _it)(it_t it, shared_t s) \
{ \
M_SHAR3D_RESOURCE_CONTRACT(s); \
M_ASSERT (it != NULL); \
unsigned int idx = genint_pop(s->core); \
it->idx = idx; \
it->ref = s; \
if (M_LIKELY (idx != GENINT_ERROR)) { \
M_ASSERT(atomic_load(&s->buffer[idx].cpt) == 0); \
atomic_store(&s->buffer[idx].cpt, 1U); \
} \
} \
\
static inline bool \
M_C(name, _end_p)(it_t it) \
{ \
M_ASSERT (it != NULL); \
return it->idx == GENINT_ERROR; \
} \
\
static inline type * \
M_C(name, _ref)(it_t it) \
{ \
M_ASSERT (it != NULL && it->ref != NULL && it->idx != GENINT_ERROR); \
M_SHAR3D_RESOURCE_CONTRACT(it->ref); \
return &it->ref->buffer[it->idx].x; \
} \
\
static inline type const * \
M_C(name, _cref)(it_t it) \
{ \
M_ASSERT (it != NULL && it->ref != NULL && it->idx != GENINT_ERROR); \
M_SHAR3D_RESOURCE_CONTRACT(it->ref); \
return M_CONST_CAST (type, &it->ref->buffer[it->idx].x); \
} \
\
static inline void \
M_C(name, _end)(it_t it, shared_t s) \
{ \
M_SHAR3D_RESOURCE_CONTRACT(s); \
M_ASSERT (it != NULL); \
M_ASSERT (it->ref == s); \
unsigned int idx = it->idx; \
if (M_LIKELY (idx != GENINT_ERROR)) { \
unsigned int c = atomic_fetch_sub (&it->ref->buffer[idx].cpt, 1U); \
if (c == 1) { \
genint_push(it->ref->core, idx); \
} \
it->idx = GENINT_ERROR; \
} \
} \
\
static inline void \
M_C(name, _it_set)(it_t itd, it_t its) \
{ \
M_ASSERT (itd != NULL && its != NULL); \
M_SHAR3D_RESOURCE_CONTRACT(its->ref); \
itd->ref = its->ref; \
unsigned int idx = its->idx; \
itd->idx = idx; \
if (M_LIKELY (idx != GENINT_ERROR)) { \
unsigned int c = atomic_fetch_add(&itd->ref->buffer[idx].cpt, 1U); \
M_ASSERT (c >= 1); \
} \
} \
M_END_PROTECTED_CODE
#endif
+560 -415
View File
File diff suppressed because it is too large. Load diff
+1306 -768
View File
File diff suppressed because it is too large. Load diff
+591 -382
View File
File diff suppressed because it is too large. Load diff
+628 -479
View File
File diff suppressed because it is too large. Load diff
+188 -140
View File
@@ -1,7 +1,7 @@
/*
* M*LIB / WORKER - Extra worker interface
*
* Copyright (c) 2017-2019, Patrick Pelissier
* Copyright (c) 2017-2021, Patrick Pelissier
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
@@ -43,8 +43,8 @@
/* Include needed system header for detection of how many core on the system */
#if defined(_WIN32)
# include <windows.h>
#elif (defined(__APPLE__) && defined(__MACH__)) \
|| defined(__DragonFly__) || defined(__FreeBSD__) \
#elif (defined(__APPLE__) && defined(__MACH__)) \
|| defined(__DragonFly__) || defined(__FreeBSD__) \
|| defined(__NetBSD__) || defined(__OpenBSD__)
# include <sys/param.h>
# include <sys/sysctl.h>
@@ -93,60 +93,67 @@
# error M_USE_WORKER_CPP_FUNCTION and M_USE_WORKER_CLANG_BLOCK are both defined. This is not supported.
#endif
/* This type defines a work order */
M_BEGIN_PROTECTED_CODE
/* Definition of a work order */
typedef struct work_order_s {
struct worker_sync_s *block;
void * data;
void (*func) (void *data);
struct worker_sync_s *block; // Reference to the shared Synchronization block
void * data; // The work order data
void (*func) (void *data); // The work order function (for GCC)
#if M_USE_WORKER_CLANG_BLOCK
void (^blockFunc)(void *data);
void (^blockFunc)(void *data); // The work order function (block for clang)
#endif
#if M_USE_WORKER_CPP_FUNCTION
std::function<void(void*)> function;
std::function<void(void*)> function; // The work order function (for C++)
#endif
} worker_order_t;
} worker_order_ct;
/* Define the macros needed to initialize an order.
* * MACRO to be used to send an empty order to stop the thread
* * MACRO to complete the not-used fields
*/
#if M_USE_WORKER_CLANG_BLOCK || M_USE_WORKER_CPP_FUNCTION
# define WORKER_EMPTY_ORDER { NULL, NULL, NULL, NULL }
# define WORKER_EXTRA_ORDER , NULL
# define M_WORK3R_EMPTY_ORDER { NULL, NULL, NULL, NULL }
# define M_WORK3R_EXTRA_ORDER , NULL
#else
# define WORKER_EMPTY_ORDER { NULL, NULL, NULL }
# define WORKER_EXTRA_ORDER
# define M_WORK3R_EMPTY_ORDER { NULL, NULL, NULL }
# define M_WORK3R_EXTRA_ORDER
#endif
/* As in C++, it uses std::function, M_POD_OPLIST
is not sufficient for initilization of the structure.
is not sufficient for initialization of the structure.
So let's use C++ constructor, destructor and copy constructor */
#if M_USE_WORKER_CPP_FUNCTION
# define WORKER_CPP_INIT(x) (new (&(x)) worker_order_t())
# define WORKER_CPP_INIT_SET(x, y) (new (&(x)) worker_order_t(y))
# define WORKER_CPP_SET(x, y) ((x) = (y))
# define WORKER_CPP_CLEAR(x) ((&(x))->~worker_order_t())
# define WORKER_CPP_INIT_MOVE(x,y) (new (&(x)) worker_order_t(y), ((&(y))->~worker_order_t()))
# define WORKER_OPLIST (INIT(WORKER_CPP_INIT), INIT_SET(WORKER_CPP_INIT_SET), SET(WORKER_CPP_SET), CLEAR(WORKER_CPP_CLEAR),INIT_MOVE(WORKER_CPP_INIT_MOVE) )
# define M_WORK3R_CPP_INIT(x) (new (&(x)) worker_order_ct())
# define M_WORK3R_CPP_INIT_SET(x, y) (new (&(x)) worker_order_ct(y))
# define M_WORK3R_CPP_SET(x, y) ((x) = (y))
# define M_WORK3R_CPP_CLEAR(x) ((&(x))->~worker_order_ct())
# define M_WORK3R_CPP_INIT_MOVE(x,y) (new (&(x)) worker_order_ct(y), ((&(y))->~worker_order_ct()))
# define WORKER_OPLIST \
(INIT(M_WORK3R_CPP_INIT), INIT_SET(M_WORK3R_CPP_INIT_SET), \
SET(M_WORK3R_CPP_SET), CLEAR(M_WORK3R_CPP_CLEAR), INIT_MOVE(M_WORK3R_CPP_INIT_MOVE) )
#else
# define WORKER_OPLIST M_POD_OPLIST
#endif
/* This type defines a worker represented as a thread */
/* Definition of a worker (implemented by a thread) */
typedef struct worker_thread_s {
m_thread_t id;
} worker_thread_t;
} worker_thread_ct;
/* Let's define the queue which will manage all work orders */
BUFFER_DEF(worker_queue, worker_order_t, 0, BUFFER_QUEUE|BUFFER_UNBLOCKING_PUSH|BUFFER_BLOCKING_POP|BUFFER_THREAD_SAFE|BUFFER_DEFERRED_POP, WORKER_OPLIST)
/* Definition of the queue that will record the work orders */
BUFFER_DEF_AS(worker_queue, m_worker_queue_ct, worker_order_ct, 0,
BUFFER_QUEUE|BUFFER_UNBLOCKING_PUSH|BUFFER_BLOCKING_POP|BUFFER_THREAD_SAFE|BUFFER_DEFERRED_POP, WORKER_OPLIST)
/* This type defines the state of the workers */
/* Definition the global pool of workers */
typedef struct worker_s {
/* The work order queue */
worker_queue_t queue_g;
m_worker_queue_ct queue_g;
/* The table of workers */
worker_thread_t *worker;
/* The table of available workers */
worker_thread_ct *worker;
/* Number of workers in the table */
unsigned int numWorker_g;
/* The global reset function */
@@ -156,15 +163,15 @@ typedef struct worker_s {
void (*clearFunc_g)(void);
m_mutex_t lock;
m_cond_t a_thread_ends;
m_cond_t a_thread_ends; // EVENT: A worker has ended
} worker_t[1];
/* This type defines a synchronization point for workers */
/* Definition of the synchronization point for workers */
typedef struct worker_sync_s {
atomic_int num_spawn;
atomic_int num_terminated_spawn;
struct worker_s *worker;
atomic_int num_spawn; // Number of spawned workers accord this synchronization point
atomic_int num_terminated_spawn; // Number of terminated spawned workers
struct worker_s *worker; // Reference to the pool of workers
} worker_sync_t[1];
/* Return the number of CPU of the system */
@@ -174,7 +181,8 @@ workeri_get_cpu_count(void)
#if defined(_WIN32)
SYSTEM_INFO sysinfo;
GetSystemInfo(&sysinfo);
return sysinfo.dwNumberOfProcessors;
M_ASSERT(sysinfo.dwNumberOfProcessors <= INT_MAX);
return (int) sysinfo.dwNumberOfProcessors;
#elif defined(M_USE_WORKER_SYSCTL)
int nm[2];
int count = 0;
@@ -184,26 +192,33 @@ workeri_get_cpu_count(void)
sysctl(nm, 2, &count, &len, NULL, 0);
return M_MAX(1, count);
#elif defined (_SC_NPROCESSORS_ONLN)
return sysconf(_SC_NPROCESSORS_ONLN);
return (int) sysconf(_SC_NPROCESSORS_ONLN);
#else
return 1;
#endif
}
/* Execute the registered work order synchronously */
// (INTERNAL) Debug support for workers
#if 1
#define M_WORK3R_DEBUG(...) (void) 0
#else
#define M_WORK3R_DEBUG(...) printf(__VA_ARGS__)
#endif
/* Execute the registered work order **synchronously** */
static inline void
workeri_exec(worker_order_t *w)
workeri_exec(worker_order_ct *w)
{
assert (w!= NULL && w->block != NULL);
//printf ("Starting thread with data %p\n", w->data);
M_ASSERT (w!= NULL && w->block != NULL);
M_WORK3R_DEBUG ("Starting thread with data %p\n", w->data);
#if M_USE_WORKER_CLANG_BLOCK
//printf ("Running %s f=%p b=%p\n", (w->func == NULL) ? "Blocks" : "Function", w->func, w->blockFunc);
M_WORK3R_DEBUG ("Running %s f=%p b=%p\n", (w->func == NULL) ? "Blocks" : "Function", w->func, w->blockFunc);
if (w->func == NULL)
w->blockFunc(w->data);
else
#endif
#if M_USE_WORKER_CPP_FUNCTION
//printf ("Running %s f=%p b=%p\n", (w->function == NULL) ? "Lambda" : "Function", w->func, w->blockFunc);
M_WORK3R_DEBUG ("Running %s f=%p b=%p\n", (w->function == NULL) ? "Lambda" : "Function", w->func, w->blockFunc);
if (w->function)
w->function(w->data);
else
@@ -214,29 +229,42 @@ workeri_exec(worker_order_t *w)
}
/* The worker thread */
/* The worker thread main loop*/
static inline void
workeri_thread(void *arg)
{
// Get back the given argument
struct worker_s *g = M_ASSIGN_CAST(struct worker_s *, arg);
while (true) {
worker_order_t w;
if (g->resetFunc_g != NULL)
worker_order_ct w;
// If needed, reset the global state of the worker
if (g->resetFunc_g != NULL) {
g->resetFunc_g();
//printf ("Waiting for data (queue: %lu / %lu)\n", worker_queue_size(g->queue_g), worker_queue_capacity(g->queue_g));
}
// Waiting for data
M_WORK3R_DEBUG ("Waiting for data (queue: %lu / %lu)\n", worker_queue_size(g->queue_g), worker_queue_capacity(g->queue_g));
worker_queue_pop(&w, g->queue_g);
// We received a work order
// Note: that the work order is still present in the queue
// preventing further work order to be pushed in the queue until it finishes doing the work
// If a stop request is received, terminate the thread
if (w.block == NULL) break;
// Execute the work order
workeri_exec(&w);
// Consumme fully the work order in the queue
worker_queue_pop_release(g->queue_g);
// Signal that a worker has finished.
m_mutex_lock(g->lock);
m_cond_broadcast(g->a_thread_ends);
m_mutex_unlock(g->lock);
}
if (g->clearFunc_g != NULL)
// If needed, clear global state of the thread
if (g->clearFunc_g != NULL) {
g->clearFunc_g();
}
}
/* Initialization of the worker module
/* Initialization of the worker module (constructor)
Input:
@numWorker: number of worker to create (0=autodetect, -1=2*autodetect)
@extraQueue: number of extra work order we can get if all workers are full
@@ -246,55 +274,67 @@ workeri_thread(void *arg)
static inline void
worker_init(worker_t g, int numWorker, unsigned int extraQueue, void (*resetFunc)(void), void (*clearFunc)(void))
{
assert (numWorker >= -1);
M_ASSERT (numWorker >= -1);
// Auto compute number of workers if the argument is 0
if (numWorker <= 0)
numWorker = (1 + (numWorker == -1))*workeri_get_cpu_count()-1;
//printf ("Starting queue with: %d\n", numWorker + extraQueue);
worker_queue_init(g->queue_g, numWorker + extraQueue);
size_t numWorker_st = numWorker;
g->worker = M_MEMORY_REALLOC(worker_thread_t, NULL, numWorker_st);
M_WORK3R_DEBUG ("Starting queue with: %d\n", numWorker + extraQueue);
// Initialization
// numWorker can still be 0 if it is a single core cpu (no worker available)
M_ASSERT(numWorker >= 0);
size_t numWorker_st = (size_t) numWorker;
g->worker = M_MEMORY_REALLOC(worker_thread_ct, NULL, numWorker_st);
if (g->worker == NULL) {
M_MEMORY_FULL(sizeof (worker_thread_t) * numWorker_st);
M_MEMORY_FULL(sizeof (worker_thread_ct) * numWorker_st);
return;
}
g->numWorker_g = numWorker_st;
worker_queue_init(g->queue_g, numWorker_st + extraQueue);
g->numWorker_g = (unsigned int) numWorker_st;
g->resetFunc_g = resetFunc;
g->clearFunc_g = clearFunc;
m_mutex_init(g->lock);
m_cond_init(g->a_thread_ends);
// Create & start the workers
for(size_t i = 0; i < numWorker_st; i++) {
m_thread_create(g->worker[i].id, workeri_thread, M_ASSIGN_CAST(void*, g));
}
}
// Define function with default values.
/* Initialization of the worker module (constructor)
Input:
@numWorker: number of worker to create (0=autodetect, -1=2*autodetect)
@extraQueue: number of extra work order we can get if all workers are full
@resetFunc: function to reset the state of a worker between work orders (optional)
@clearFunc: function to clear the state of a worker before terminaning (optional)
*/
#define worker_init(...) worker_init(M_DEFAULT_ARGS(5, (0, 0, NULL, NULL), __VA_ARGS__))
/* Clear of the worker module */
/* Clear of the worker module (destructor) */
static inline void
worker_clear(worker_t g)
{
assert (worker_queue_empty_p (g->queue_g));
M_ASSERT (worker_queue_empty_p (g->queue_g));
// Push the terminate order on the queue
for(unsigned int i = 0; i < g->numWorker_g; i++) {
worker_order_t w = WORKER_EMPTY_ORDER;
worker_order_ct w = M_WORK3R_EMPTY_ORDER;
// Normaly all worker threads shall be waiting at this
// stage, so all push won't block as the queue is empty.
// But for robustness, let's wait.
worker_queue_push_blocking (g->queue_g, w, true);
}
// Wait for thread terminanison
for(unsigned int i = 0; i < g->numWorker_g; i++) {
m_thread_join(g->worker[i].id);
}
// Clear memory
M_MEMORY_FREE(g->worker);
m_mutex_clear(g->lock);
m_cond_clear(g->a_thread_ends);
worker_queue_clear(g->queue_g);
}
/* Start a new collaboration between workers
and define the synchronization point 'block' */
/* Start a new collaboration between workers of pool 'g'
by defining the synchronization point 'block' */
static inline void
worker_start(worker_sync_t block, worker_t g)
{
@@ -303,20 +343,23 @@ worker_start(worker_sync_t block, worker_t g)
block->worker = g;
}
/* Spawn or not the given work order to workers,
or do it ourself if no worker is available */
/* Spawn the given work order to workers if possible,
or do it ourself if no worker is available.
The synchronization point is defined a 'block'
The work order if composed of the function 'func' and its 'data'
*/
static inline void
worker_spawn(worker_sync_t block, void (*func)(void *data), void *data)
{
const worker_order_t w = { block, data, func WORKER_EXTRA_ORDER };
const worker_order_ct w = { block, data, func M_WORK3R_EXTRA_ORDER };
if (M_UNLIKELY (!worker_queue_full_p(block->worker->queue_g))
&& worker_queue_push (block->worker->queue_g, w) == true) {
//printf ("Sending data to thread: %p (block: %d / %d)\n", data, block->num_spawn, block->num_terminated_spawn);
M_WORK3R_DEBUG ("Sending data to thread: %p (block: %d / %d)\n", data, block->num_spawn, block->num_terminated_spawn);
atomic_fetch_add (&block->num_spawn, 1);
return;
}
//printf ("Running data ourself: %p\n", data);
/* No thread available. Call the function ourself */
M_WORK3R_DEBUG ("Running data ourself: %p\n", data);
/* No worker available. Call the function ourself */
(*func) (data);
}
@@ -326,15 +369,15 @@ worker_spawn(worker_sync_t block, void (*func)(void *data), void *data)
static inline void
worker_spawn_block(worker_sync_t block, void (^func)(void *data), void *data)
{
const worker_order_t w = { block, data, NULL, func };
const worker_order_ct w = { block, data, NULL, func };
if (M_UNLIKELY (!worker_queue_full_p(block->worker->queue_g))
&& worker_queue_push (block->worker->queue_g, w) == true) {
//printf ("Sending data to thread as block: %p (block: %d / %d)\n", data, block->num_spawn, block->num_terminated_spawn);
M_WORK3R_DEBUG ("Sending data to thread as block: %p (block: %d / %d)\n", data, block->num_spawn, block->num_terminated_spawn);
atomic_fetch_add (&block->num_spawn, 1);
return;
}
//printf ("Running data ourself as block: %p\n", data);
/* No thread available. Call the function ourself */
M_WORK3R_DEBUG ("Running data ourself as block: %p\n", data);
/* No worker available. Call the function ourself */
func (data);
}
#endif
@@ -345,20 +388,20 @@ worker_spawn_block(worker_sync_t block, void (^func)(void *data), void *data)
static inline void
worker_spawn_function(worker_sync_t block, std::function<void(void *data)> func, void *data)
{
const worker_order_t w = { block, data, NULL, func };
const worker_order_ct w = { block, data, NULL, func };
if (M_UNLIKELY (!worker_queue_full_p(block->worker->queue_g))
&& worker_queue_push (block->worker->queue_g, w) == true) {
//printf ("Sending data to thread as block: %p (block: %d / %d)\n", data, block->num_spawn, block->num_terminated_spawn);
M_WORK3R_DEBUG ("Sending data to thread as block: %p (block: %d / %d)\n", data, block->num_spawn, block->num_terminated_spawn);
atomic_fetch_add (&block->num_spawn, 1);
return;
}
//printf ("Running data ourself as block: %p\n", data);
/* No thread available. Call the function ourself */
M_WORK3R_DEBUG ("Running data ourself as block: %p\n", data);
/* No worker available. Call the function ourself */
func (data);
}
#endif
/* Test if all work orders are finished */
/* Test if all work orders of the given synchronization point are finished */
static inline bool
worker_sync_p(worker_sync_t block)
{
@@ -368,12 +411,14 @@ worker_sync_p(worker_sync_t block)
return (atomic_load(&block->num_spawn) == atomic_load (&block->num_terminated_spawn));
}
/* Wait for all work orders to be finished */
/* Wait for all work orders of the given synchronization point to be finished */
static inline void
worker_sync(worker_sync_t block)
{
//printf ("Waiting for thread terminasion.\n");
M_WORK3R_DEBUG ("Waiting for thread terminasion.\n");
// Fast case: all workers have finished
if (worker_sync_p(block)) return;
// Slow case: perform a locked wait to put this thread to waiting state
m_mutex_lock(block->worker->lock);
while (!worker_sync_p(block)) {
m_cond_wait(block->worker->a_thread_ends, block->worker->lock);
@@ -381,11 +426,11 @@ worker_sync(worker_sync_t block)
m_mutex_unlock(block->worker->lock);
}
/* Flush any work order in the queue if some remains.*/
/* Flush any work order in the queue ourself if some remains.*/
static inline void
worker_flush(worker_t g)
{
worker_order_t w;
worker_order_ct w;
while (worker_queue_pop_blocking (&w, g->queue_g, false) == true) {
workeri_exec(&w);
worker_queue_pop_release(g->queue_g);
@@ -405,81 +450,84 @@ worker_count(worker_t g)
'block' shall be the initialised synchronised block for all threads.
'input' is the list of input variables of the 'core' block within "( )"
'output' is the list of output variables of the 'core' block within "( )"
Output variables are only available after a synchronisation block. */
Output variables are only available after a synchronisation block.
TODO: Support oplist for input & outputs parameters
*/
#if M_USE_WORKER_CLANG_BLOCK
#define WORKER_SPAWN(_block, _input, _core, _output) \
WORKER_DEF_DATA(_input, _output) \
WORKER_DEF_SUBBLOCK(_input, _output, _core) \
worker_spawn_block ((_block), WORKER_SPAWN_SUBFUNC_NAME, &WORKER_SPAWN_DATA_NAME)
#define WORKER_SPAWN(_block, _input, _core, _output) \
M_WORK3R_DEF_DATA(_input, _output) \
M_WORK3R_DEF_SUBBLOCK(_input, _output, _core) \
worker_spawn_block ((_block), M_WORK3R_SPAWN_SUBFUNC_NAME, &M_WORK3R_SPAWN_DATA_NAME)
#elif M_USE_WORKER_CPP_FUNCTION
// TODO: Explicit pass all arguments by reference.
#define WORKER_SPAWN(_block, _input, _core, _output) \
#define WORKER_SPAWN(_block, _input, _core, _output) \
worker_spawn_function ((_block), [&](void *param) {(void)param ; _core } , NULL)
#else
#define WORKER_SPAWN(_block, _input, _core, _output) \
WORKER_DEF_DATA(_input, _output) \
WORKER_DEF_SUBFUNC(_input, _output, _core) \
worker_spawn ((_block), WORKER_SPAWN_SUBFUNC_NAME, &WORKER_SPAWN_DATA_NAME)
#define WORKER_SPAWN(_block, _input, _core, _output) \
M_WORK3R_DEF_DATA(_input, _output) \
M_WORK3R_DEF_SUBFUNC(_input, _output, _core) \
worker_spawn ((_block), M_WORK3R_SPAWN_SUBFUNC_NAME, &M_WORK3R_SPAWN_DATA_NAME)
#endif
#define WORKER_SPAWN_STRUCT_NAME M_C(worker_data_s_, __LINE__)
#define WORKER_SPAWN_DATA_NAME M_C(worker_data_, __LINE__)
#define WORKER_SPAWN_SUBFUNC_NAME M_C(worker_subfunc_, __LINE__)
#define WORKER_DEF_DATA(_input, _output) \
struct WORKER_SPAWN_STRUCT_NAME { \
WORKER_DEF_DATA_INPUT _input \
M_IF_EMPTY _output ( , WORKER_DEF_DATA_OUTPUT _output) \
} WORKER_SPAWN_DATA_NAME = { \
WORKER_INIT_DATA_INPUT _input \
M_IF_EMPTY _output (, WORKER_INIT_DATA_OUTPUT _output) \
#define M_WORK3R_SPAWN_STRUCT_NAME M_C(worker_data_s_, __LINE__)
#define M_WORK3R_SPAWN_DATA_NAME M_C(worker_data_, __LINE__)
#define M_WORK3R_SPAWN_SUBFUNC_NAME M_C(worker_subfunc_, __LINE__)
#define M_WORK3R_DEF_DATA(_input, _output) \
struct M_WORK3R_SPAWN_STRUCT_NAME { \
M_WORK3R_DEF_DATA_INPUT _input \
M_IF_EMPTY _output ( , M_WORK3R_DEF_DATA_OUTPUT _output) \
} M_WORK3R_SPAWN_DATA_NAME = { \
M_WORK3R_INIT_DATA_INPUT _input \
M_IF_EMPTY _output (, M_WORK3R_INIT_DATA_OUTPUT _output) \
};
#define WORKER_DEF_SINGLE_INPUT(var) __typeof__(var) var;
#define WORKER_DEF_DATA_INPUT(...) \
M_MAP(WORKER_DEF_SINGLE_INPUT, __VA_ARGS__)
#define WORKER_DEF_SINGLE_OUTPUT(var) \
#define M_WORK3R_DEF_SINGLE_INPUT(var) __typeof__(var) var;
#define M_WORK3R_DEF_DATA_INPUT(...) \
M_MAP(M_WORK3R_DEF_SINGLE_INPUT, __VA_ARGS__)
#define M_WORK3R_DEF_SINGLE_OUTPUT(var) \
__typeof__(var) *M_C(var, _ptr);
#define WORKER_DEF_DATA_OUTPUT(...) \
M_MAP(WORKER_DEF_SINGLE_OUTPUT, __VA_ARGS__)
#define WORKER_INIT_SINGLE_INPUT(var) \
#define M_WORK3R_DEF_DATA_OUTPUT(...) \
M_MAP(M_WORK3R_DEF_SINGLE_OUTPUT, __VA_ARGS__)
#define M_WORK3R_INIT_SINGLE_INPUT(var) \
.var = var,
#define WORKER_INIT_DATA_INPUT(...) \
M_MAP(WORKER_INIT_SINGLE_INPUT, __VA_ARGS__)
#define WORKER_INIT_SINGLE_OUTPUT(var) \
#define M_WORK3R_INIT_DATA_INPUT(...) \
M_MAP(M_WORK3R_INIT_SINGLE_INPUT, __VA_ARGS__)
#define M_WORK3R_INIT_SINGLE_OUTPUT(var) \
.M_C(var, _ptr) = &var,
#define WORKER_INIT_DATA_OUTPUT(...) \
M_MAP(WORKER_INIT_SINGLE_OUTPUT, __VA_ARGS__)
#define WORKER_DEF_SUBFUNC(_input, _output, _core) \
__extension__ auto void WORKER_SPAWN_SUBFUNC_NAME(void *) ; \
__extension__ void WORKER_SPAWN_SUBFUNC_NAME(void *_data) \
{ \
struct WORKER_SPAWN_STRUCT_NAME *_s_data = _data ; \
WORKER_INIT_LOCAL_INPUT _input \
M_IF_EMPTY _output ( , WORKER_INIT_LOCAL_OUTPUT _output) \
do { _core } while (0); \
M_IF_EMPTY _output ( , WORKER_PROPAGATE_LOCAL_OUTPUT _output) \
#define M_WORK3R_INIT_DATA_OUTPUT(...) \
M_MAP(M_WORK3R_INIT_SINGLE_OUTPUT, __VA_ARGS__)
#define M_WORK3R_DEF_SUBFUNC(_input, _output, _core) \
__extension__ auto void M_WORK3R_SPAWN_SUBFUNC_NAME(void *) ; \
__extension__ void M_WORK3R_SPAWN_SUBFUNC_NAME(void *_data) \
{ \
struct M_WORK3R_SPAWN_STRUCT_NAME *_s_data = _data ; \
M_WORK3R_INIT_LOCAL_INPUT _input \
M_IF_EMPTY _output ( , M_WORK3R_INIT_LOCAL_OUTPUT _output) \
do { _core } while (0); \
M_IF_EMPTY _output ( , M_WORK3R_PROPAGATE_LOCAL_OUTPUT _output) \
};
#define WORKER_DEF_SUBBLOCK(_input, _output, _core) \
void (^WORKER_SPAWN_SUBFUNC_NAME) (void *) = ^ void (void * _data) \
{ \
struct WORKER_SPAWN_STRUCT_NAME *_s_data = _data ; \
WORKER_INIT_LOCAL_INPUT _input \
M_IF_EMPTY _output ( , WORKER_INIT_LOCAL_OUTPUT _output) \
do { _core } while (0); \
M_IF_EMPTY _output ( , WORKER_PROPAGATE_LOCAL_OUTPUT _output) \
#define M_WORK3R_DEF_SUBBLOCK(_input, _output, _core) \
void (^M_WORK3R_SPAWN_SUBFUNC_NAME) (void *) = ^ void (void * _data) \
{ \
struct M_WORK3R_SPAWN_STRUCT_NAME *_s_data = _data ; \
M_WORK3R_INIT_LOCAL_INPUT _input \
M_IF_EMPTY _output ( , M_WORK3R_INIT_LOCAL_OUTPUT _output) \
do { _core } while (0); \
M_IF_EMPTY _output ( , M_WORK3R_PROPAGATE_LOCAL_OUTPUT _output) \
};
#define WORKER_INIT_SINGLE_LOCAL_INPUT(var) \
#define M_WORK3R_INIT_SINGLE_LOCAL_INPUT(var) \
__typeof__(var) var = _s_data->var;
#define WORKER_INIT_LOCAL_INPUT(...) \
M_MAP(WORKER_INIT_SINGLE_LOCAL_INPUT, __VA_ARGS__)
#define WORKER_INIT_SINGLE_LOCAL_OUTPUT(var) \
#define M_WORK3R_INIT_LOCAL_INPUT(...) \
M_MAP(M_WORK3R_INIT_SINGLE_LOCAL_INPUT, __VA_ARGS__)
#define M_WORK3R_INIT_SINGLE_LOCAL_OUTPUT(var) \
__typeof__(var) var;
#define WORKER_INIT_LOCAL_OUTPUT(...) \
M_MAP(WORKER_INIT_SINGLE_LOCAL_OUTPUT, __VA_ARGS__)
#define WORKER_PROPAGATE_SINGLE_OUTPUT(var) \
#define M_WORK3R_INIT_LOCAL_OUTPUT(...) \
M_MAP(M_WORK3R_INIT_SINGLE_LOCAL_OUTPUT, __VA_ARGS__)
#define M_WORK3R_PROPAGATE_SINGLE_OUTPUT(var) \
*(_s_data->M_C(var, _ptr)) = var;
#define WORKER_PROPAGATE_LOCAL_OUTPUT(...) \
M_MAP(WORKER_PROPAGATE_SINGLE_OUTPUT, __VA_ARGS__)
#define M_WORK3R_PROPAGATE_LOCAL_OUTPUT(...) \
M_MAP(M_WORK3R_PROPAGATE_SINGLE_OUTPUT, __VA_ARGS__)
M_END_PROTECTED_CODE
#else /* M_USE_WORKER */
+77
View File
@@ -0,0 +1,77 @@
REM Copyright (c) 2017-2021, Patrick Pelissier
REM All rights reserved.
REM
REM Redistribution and use in source and binary forms, with or without
REM modification, are permitted provided that the following conditions are met:
REM + Redistributions of source code must retain the above copyright
REM notice, this list of conditions and the following disclaimer.
REM + Redistributions in binary form must reproduce the above copyright
REM notice, this list of conditions and the following disclaimer in the
REM documentation and/or other materials provided with the distribution.
REM
REM THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
REM EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
REM WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
REM DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
REM DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
REM (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
REM LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
REM ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
REM (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
REM SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
REM Execute the test suite for Microsoft Visual Studio
REM
REM Load Micosoft Visual Studio environement file.
IF EXIST "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvarsall.bat" (
call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvarsall.bat" x64
)
IF EXIST "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" (
call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" x64
)
REM Add clang-cl in the PATH. It is the default install of clang for MSVC:
REM %VCINSTALLDIR%\Tools\Llvm\bin;%VCINSTALLDIR%\Tools\Llvm\x64\bin
REM Adding x64 version
REM See https://docs.microsoft.com/de-de/cpp/build/clang-support-msbuild?view=vs-2019
SET PATH=%PATH%;%VCINSTALLDIR%\Tools\Llvm\x64\bin
REM Remove previous results
DEL *.log *.dat
REM Select compiler to use (either cl or clang-cl)
set "compiler=%1"
echo "Compiler full version (%compiler%):"
%compiler% /Bv
%compiler% -v
REM Perform for each test
for %%f in (test-*.c) do (
echo =================================================
echo Testing %%f
REM Copy the test file as a C++ file as CL.EXE only support C++ file
del test.exe
copy %%f test.cpp || EXIT /B 1
REM Compile the test suite
REM /Zc:preprocessor is mandatory to have a compliant preprocessor
REM /Zc:__cplusplus is needed to report the real value of __cplusplus, so that M*LIB uses the C++ atomic, and not its emulation.
REM Enable warnings and basic optimization
REM Inform M*LIB to use Annex K by defining __STDC_WANT_LIB_EXT1__
echo Compiling %%f with %compiler%
%compiler% /I.. /O2 /W3 /std:c++14 /Zc:__cplusplus /Zc:preprocessor /D__STDC_WANT_LIB_EXT1__ test.cpp > %%f.log 2>&1 || (
echo *** BUILD ERROR for %%f *** >> %%f.log
type %%f.log
EXIT /B 1
)
REM Execute it
echo Running %%f
test.exe >> %%f.log 2>&1 && echo Test OK for %%f >> %%f.log || (
echo *** RUNTIME ERROR for %%f *** >> %%f.log
type %%f.log
EXIT /B 1
)
type %%f.log
)
echo "All tests passed"
exit /B 0
+129 -53
View File
@@ -1,7 +1,30 @@
# Copyright (c) 2017-2021, Patrick Pelissier
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# + Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# + Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
CC=cc -std=c99
WCFLAGS_GCC=-Wall -W -pedantic -Wshadow -Wpointer-arith -Wcast-qual -Wstrict-prototypes -Wmissing-prototypes -Wswitch-default -Wswitch-enum -Wcast-align -Wpointer-arith -Wbad-function-cast -Wstrict-overflow=5 -Wstrict-prototypes -Winline -Wundef -Wnested-externs -Wcast-qual -Wshadow -Wunreachable-code -Wlogical-op -Wstrict-aliasing=2 -Wredundant-decls -Wold-style-definition -Wno-unused-function -ftrapv
WCFLAGS_CLANG=-Wall -W -pedantic -Wshadow -Wpointer-arith -Wcast-qual -Wstrict-prototypes -Wmissing-prototypes -Wswitch-default -Wswitch-enum -Wcast-align -Wpointer-arith -Wbad-function-cast -Wstrict-overflow=5 -Wstrict-prototypes -Winline -Wundef -Wnested-externs -Wcast-qual -Wshadow -Wunreachable-code -Wstrict-aliasing=2 -Wredundant-decls -Wold-style-definition -Wno-unused-function -ftrapv
WCFLAGS_CPP=-Wall -W -pedantic -Wshadow -Wpointer-arith -Wcast-qual -Wswitch-default -Wswitch-enum -Wcast-align -Wpointer-arith -Wstrict-overflow=5 -Winline -Wundef -Wcast-qual -Wshadow -Wunreachable-code -Wlogical-op -Wstrict-aliasing=2 -Wredundant-decls -Wno-unused-function -ftrapv
CXX=c++ -std=c++11
WCFLAGS_GCC=-Wall -W -pedantic -Wshadow -Wpointer-arith -Wcast-qual -Wstrict-prototypes -Wmissing-prototypes -Wswitch-default -Wswitch-enum -Wcast-align -Wpointer-arith -Wbad-function-cast -Wstrict-overflow=5 -Wundef -Wnested-externs -Wcast-qual -Wshadow -Wunreachable-code -Wlogical-op -Wstrict-aliasing=2 -Wredundant-decls -Wold-style-definition -Wunused-function -ftrapv -Wsign-conversion -Wdate-time -Wconversion -Wformat=2 -Winit-self -Wjump-misses-init -Wstack-protector -Wtrampolines -Wwrite-strings -Wformat-security -Wno-float-conversion -O
WCFLAGS_CLANG=-Wall -W -pedantic -Wshadow -Wpointer-arith -Wcast-qual -Wstrict-prototypes -Wmissing-prototypes -Wswitch-default -Wswitch-enum -Wcast-align -Wpointer-arith -Wbad-function-cast -Wstrict-overflow=5 -Winline -Wundef -Wnested-externs -Wcast-qual -Wshadow -Wunreachable-code -Wstrict-aliasing=2 -Wredundant-decls -Wold-style-definition -Wunused-function -ftrapv -Wsign-conversion -O
WCFLAGS_CPP=-Wall -W -pedantic -Wshadow -Wpointer-arith -Wcast-qual -Wswitch-default -Wswitch-enum -Wcast-align -Wpointer-arith -Wstrict-overflow=5 -Winline -Wundef -Wcast-qual -Wshadow -Wunreachable-code -Wstrict-aliasing=2 -Wredundant-decls -Wunused-function -ftrapv -Wsign-conversion
XCFLAGS=
CFLAGS=$(WCFLAGS_GCC) $(XCFLAGS)
CPPFLAGS=-I..
@@ -20,23 +43,26 @@ all:
#####################################################################################################
.POSIX:
.PHONY: valgrind scan-build sanitize check clean *.log coverage synthesis
.PHONY: scan-build sanitize check clean *.log coverage synthesis
.SUFFIXES:
.SUFFIXES: .c .exe .log .depend .valgrind .gcov
.SUFFIXES: .c .exe .log .depend .gcov .analyzer .cpp
.SECONDARY:
.c.exe:
$(CC) $(CFLAGS) $(CPPFLAGS) -g $(LDFLAGS) $< -o $@
.cpp.exe:
$(CXX) $(WCFLAGS_CPP) -Wno-sign-conversion -Wno-inline $(XCFLAGS) $(CPPFLAGS) -g $(LDFLAGS) $< -o $@
.c.depend:
$(CC) $(CFLAGS) $(CPPFLAGS) -MM -MT `echo $< |$(SED) 's/\.c/\.exe/g'` $< > $@
$(CC) $(CPPFLAGS) -MM -MT `echo $< |$(SED) 's/\.c/\.exe/g'` $< > $@
.cpp.depend:
$(CXX) $(CPPFLAGS) -MM -MT `echo $< |$(SED) 's/\.cpp/\.exe/g'` $< > $@
.exe.log:
$(LOG_COMPILER) ./$<
.exe.valgrind:
valgrind ./$<
.c.gcov:
awk '/START_COVERAGE/ { printit=1} (printit == 0) { print }' $< > $<.first.c
awk ' printit { print } /END_COVERAGE/ { printit=1}' $< > $<.end.c
@@ -44,7 +70,7 @@ all:
cat $<.first.c $<.middle.c $<.end.c > $<.c
$(CC) $(CPPFLAGS) $(LDFLAGS) -ftest-coverage -fprofile-arcs -g $<.c -o $<.exe
$(LOG_COMPILER) ./$<.exe
gcov $<.gcno > `basename $< .c`.synt
LANG=C gcov $<.gcno > `basename $< .c`.synt
cat `basename $< .c`.synt
mv $<.c.gcov `basename $< .c`.gcov
$(RM) $<.first.c $<.end.c $<.middle.c $<.c $<.exe
@@ -55,6 +81,7 @@ depend:
$(RM) depend
echo "" > depend
$(MAKE) `ls test-*.c|$(SED) 's/\.c/\.depend/g'`
$(CXX) --version 2> /dev/null && $(MAKE) `ls check-*.cpp|$(SED) 's/\.cpp/\.depend/g'` || echo "Skip C++ tests"
cat *.depend > depend
$(RM) *.depend
@@ -63,18 +90,48 @@ depend:
# Clean
#####################################################################################################
# This target generates all executable to be tested by CodeQL
exe: depend
$(MAKE) `ls test-*.c|$(SED) 's/\.c/\.exe/g'` CC="$(CC)" CFLAGS="$(CFLAGS)"
@echo All executable generated
check: depend
$(MAKE) `ls test-*.c|$(SED) 's/\.c/\.log/g'`
$(MAKE) `ls test-*.c|$(SED) 's/\.c/\.log/g'` `ls fail-*.c|$(SED) 's/\.c/\.log/g'` CC="$(CC)" CFLAGS="$(CFLAGS)"
@echo All tests passed
check-stl: depend
$(MAKE) `ls check-*.cpp|$(SED) 's/\.cpp/\.log/g'` CXX="$(CXX)" XCFLAGS="-O2 -fsanitize=address,undefined,leak"
@echo All comparison against C++ STL passed
clean:
$(RM) *.exe *.s *~ *.o *.log a*.dat
$(RM) *.valgrind *.gcda *.gcno *.gcov all.info test.tar *.synt clang_output_* *.c.c *.end.c *.first.c *.middle.c
$(RM) *.gcda *.gcno *.gcov all.info test.tar *.synt clang_output_* *.c.c *.end.c *.first.c *.middle.c *.analyzer
$(RMDIR) coverage coverage-dir mlib-report
distclean: clean
$(RM) *.depend depend
#####################################################################################################
# Proper failure generation (test if the code properly fails to compile)
#####################################################################################################
# TODO: should grep failure message?
FAIL_BASE=
FAIL_SEQ=
fail-generic.log:
for i in `seq 1 $(FAIL_SEQ)` ; do \
if $(CC) $(CFLAGS) $(CPPFLAGS) -g -c $(FAIL_BASE).c -o tmp.o -DTEST=$$i 2> $(FAIL_BASE)-$$i.log ; then echo "$(FAIL_BASE) -- TEST $$i : ERROR (compilation succeeded)" ; false ; elif grep -q "M_LIB_" $(FAIL_BASE)-$$i.log ; then echo "$(FAIL_BASE) -- TEST $$i : OK" ; else echo "$(FAIL_BASE) -- TEST $$i : WARNING (Not a M*LIB detected error)" ; fi \
done
fail-no-oplist.log:
@$(MAKE) fail-generic.log FAIL_BASE=fail-no-oplist FAIL_SEQ=44
fail-chain-oplist.log:
@$(MAKE) fail-generic.log FAIL_BASE=fail-chain-oplist FAIL_SEQ=24
fail-incompatible.log:
@$(MAKE) fail-generic.log FAIL_BASE=fail-incompatible FAIL_SEQ=24
#####################################################################################################
# Code generation analysis
#####################################################################################################
@@ -100,6 +157,9 @@ gene-queue:
gene-string:
$(CC) $(CFLAGS) $(CPPFLAGS) -O3 -march=native -DNDEBUG -S tgen-mstring.c && less tgen-mstring.s
gene-serial:
$(CC) $(CFLAGS) $(CPPFLAGS) -O3 -march=native -DNDEBUG -S -std=c11 tgen-mserial.c && less tgen-mserial.s
#####################################################################################################
# Coverage
@@ -110,38 +170,40 @@ coverage:
$(MAKE) synthesis
SYNTHESIS_DATA= M-ALGO test-malgo.c.c test-malgo.synt \
M-ARRAY test-marray.c.c test-marray.synt \
M-BITSET ../m-bitset.h test-mbitset.synt \
M-BBPTREE test-mbptree.c test-mbptree.synt \
M-BUFFER test-mbuffer.c.c test-mbuffer.synt \
M-ARRAY test-marray.c.c test-marray.synt \
M-BITSET ../m-bitset.h test-mbitset.synt \
M-BBPTREE test-mbptree.c test-mbptree.synt \
M-BUFFER test-mbuffer.c.c test-mbuffer.synt \
M-CONCURRENT test-mconcurrent.c.c test-mconcurrent.synt \
M-CORE test-mcore.c.c test-mcore.synt \
M-DEQUE test-mdeque.c.c test-mdeque.synt \
M-DICT test-mdict.c.c test-mdict.synt \
M-GENINT ../m-genint.h test-mgenint.synt \
M-I-LIST test-milist.c.c test-milist.synt \
M-LIST test-mlist.c.c test-mlist.synt \
M-MEMPOOL test-mmempool.c.c test-mmempool.synt \
M-MUTEX ../m-mutex.h test-mmutex.synt \
M-CORE test-mcore.c.c test-mcore.synt \
M-DEQUE test-mdeque.c.c test-mdeque.synt \
M-DICT test-mdict.c.c test-mdict.synt \
M-FUNCOBJ test-mfuncobj.c.c test-mfuncobj.synt \
M-GENINT ../m-genint.h test-mgenint.synt \
M-I-LIST test-milist.c.c test-milist.synt \
M-I-SHARED test-mishared.c.c test-mishared.synt \
M-LIST test-mlist.c.c test-mlist.synt \
M-MEMPOOL test-mmempool.c.c test-mmempool.synt \
M-MUTEX ../m-mutex.h test-mmutex.synt \
M-PRIOQUEUE test-mprioqueue.c.c test-mprioqueue.synt \
M-RBTREE test-mrbtree.c.c test-mrbtree.synt \
M-RBTREE test-mrbtree.c.c test-mrbtree.synt \
M-SERIAL-BIN ../m-serial-bin.h test-mserial-bin.synt \
M-SERIAL-JSON ../m-serial-json.h test-mserial-json.synt \
M-SHARED test-mshared.c.c test-mshared.synt \
M-SNAPSHOT test-msnapshot.c.c test-msnapshot.synt \
M-STRING ../m-string.h test-mstring.synt \
M-TUPLE test-mtuple.c.c test-mtuple.synt \
M-VARIANT test-mvariant.c.c test-mvariant.synt \
M-SHARED test-mshared.c.c test-mshared.synt \
M-SNAPSHOT test-msnapshot.c.c test-msnapshot.synt \
M-STRING ../m-string.h test-mstring.synt \
M-TUPLE test-mtuple.c.c test-mtuple.synt \
M-VARIANT test-mvariant.c.c test-mvariant.synt \
M-WORKER ../m-worker.h test-mworker.synt
synthesis:
@printf "+-------------------------------+-------------------------------+\n"
@for i in $(SYNTHESIS_DATA) ; do \
if test "$$j" = "" ; then j=$$i ; continue ; fi; \
if test "$$k" = "" ; then k=$$i ; continue ; fi; \
@for i in $(SYNTHESIS_DATA) ; do \
if test "$$j" = "" ; then j=$$i ; continue ; fi; \
if test "$$k" = "" ; then k=$$i ; continue ; fi; \
printf "|\t%16.16s\t|\t%16.16s\t|\n" "$$j" "`grep -v Creating $$i|grep $$k -F -A1 |tail -1|cut -f2 -d':'`"; \
j=""; \
k=""; \
j=""; \
k=""; \
done
@printf "+-------------------------------+-------------------------------+\n"
@@ -150,32 +212,46 @@ synthesis:
# Code analyzer tools
#####################################################################################################
valgrind:
$(MAKE) `ls test-*.c|$(SED) 's/\.c/\.valgrind/g'`
# Static analysis of the code using clang scan-build
scan-build: clean
$(RM) -rf ./mlib-report
scan-build -o ./mlib-report $(MAKE) check XCFLAGS="-std=c99"
scan-build -o ./mlib-report $(MAKE) exe XCFLAGS="-std=c99"
# Relaunch the test suite with the sanitizer.
sanitize:
$(MAKE) clean check XCFLAGS="-fsanitize=address,undefined"
$(MAKE) clean check XCFLAGS="-fsanitize=address,undefined,leak"
$(MAKE) clean check XCFLAGS="-fsanitize=thread -pie -fPIE"
# Static analysis of the code using GCC "-fanalyzer" option
# Need GCC >= 10
# Preprocess the file before given it to the analyser (just like coverage) to have better report.
.c.analyzer:
awk '/START_COVERAGE/ { printit=1} (printit == 0) { print }' $< > $<.first.c
awk ' printit { print } /END_COVERAGE/ { printit=1}' $< > $<.end.c
$(CC) $(CPPFLAGS) -E -DNDEBUG -DWITHIN_COVERAGE $< |grep -v '^#' |awk ' /END_COVERAGE/ { printit=0} printit { print } /START_COVERAGE/ { printit=1 }' |perl -p -e "s/;(?![\"'])/;\n/g ; s/}(?![\"'])/}\n/g ; s/{(?![\"'])/{\n/g" > $<.middle.c
cat $<.first.c $<.middle.c $<.end.c > $<.c
$(CC) $(CPPFLAGS) $(LDFLAGS) -fanalyzer -Wall -W -O2 -g $<.c -o $<.exe 2> `basename $< .c`.analyzer
$(RM) $<.first.c $<.end.c $<.middle.c $<.c $<.exe
analyze:
$(MAKE) `ls test-*.c|$(SED) 's/\.c/\.analyzer/g'`
#####################################################################################################
# Test All
# Test with the maximum representative number of compiler and flags.
#####################################################################################################
checkall:
@$(MAKE) clean ; $(MAKE) check CC="gcc -std=c99"
@$(MAKE) clean ; $(MAKE) check CC="gcc -std=c99 -m32"
@$(MAKE) clean ; $(MAKE) check CC="gcc -std=c11"
@$(MAKE) clean ; $(MAKE) check CC="gcc -std=c11 -m32"
@if which clang ; then $(MAKE) clean ; $(MAKE) check CC="clang -std=c99" WCFLAGS="$(WCFLAGS_CLANG)" ; else echo "SYSTEM CLANG not found: SKIP TEST" ; fi
@if which g++ ; then $(MAKE) clean ; $(MAKE) check CC="g++ -std=c++11" WCFLAGS="$(WCFLAGS_CPP)" ; else echo "SYSTEM G++ not found: SKIP TEST" ; fi
@if which clang++ ; then $(MAKE) clean ; $(MAKE) check CC="clang++ -std=c++11" WCFLAGS="$(WCFLAGS_CLANG)" ; else echo "SYSTEM CLANG++ not found: SKIP TEST" ; fi
@if which tcc ; then $(MAKE) clean ; $(MAKE) check CC="tcc -std=c99" ; else echo "SYSTEM TCC not found: SKIP TEST" ; fi
@if which musl-gcc ; then $(MAKE) clean ; $(MAKE) check CC="musl-gcc -std=c11" ; else echo "SYSTEM MUSL-GCC not found: SKIP TEST" ; fi
@for f in /opt/gcc* ; do if test -x "$$f/bin/gcc" ; then $(MAKE) clean ; $(MAKE) check CC="$$f/bin/gcc -std=c99" ; fi ; done
@for f in /opt/clang* ; do if test -x "$$f/bin/clang" ; then $(MAKE) clean ; $(MAKE) check CC="$$f/bin/clang -std=c99" WCFLAGS="$(WCFLAGS_CLANG)" ; fi ; done
@for f in /opt/tcc* ; do if test -x "$$f/bin/tcc" ; then $(MAKE) clean ; $(MAKE) check CC="$$f/bin/tcc -std=c99" ; fi ; done
@$(MAKE) clean ; $(MAKE) check CC="gcc -std=c99 -Werror"
@$(MAKE) clean ; $(MAKE) check CC="gcc -std=c99 -m32 -Werror"
@$(MAKE) clean ; $(MAKE) check CC="gcc -std=c11 -Werror"
@$(MAKE) clean ; $(MAKE) check CC="gcc -std=c11 -m32 -Werror"
@if which clang ; then $(MAKE) clean ; $(MAKE) check CC="clang -std=c99 -Werror" CFLAGS="$(WCFLAGS_CLANG)" ; else echo "SYSTEM CLANG not found: SKIP TEST" ; fi
@if which g++ ; then $(MAKE) clean ; $(MAKE) check CC="g++ -std=c++11 -Werror" CFLAGS="$(WCFLAGS_CPP)" ; else echo "SYSTEM G++ not found: SKIP TEST" ; fi
@if which clang++ ; then $(MAKE) clean ; $(MAKE) check CC="clang++ -std=c++11" CFLAGS="$(WCFLAGS_CLANG)" ; else echo "SYSTEM CLANG++ not found: SKIP TEST" ; fi
@if which tcc ; then $(MAKE) clean ; $(MAKE) check CC="tcc -std=c99 -Werror" ; else echo "SYSTEM TCC not found: SKIP TEST" ; fi
@if which musl-gcc ; then $(MAKE) clean ; $(MAKE) check CC="musl-gcc -std=c11 -Werror" ; else echo "SYSTEM MUSL-GCC not found: SKIP TEST" ; fi
@for f in /opt/gcc* ; do if test -x "$$f/bin/gcc" ; then $(MAKE) clean ; $(MAKE) check CC="$$f/bin/gcc -std=c99 -Werror" ; fi ; done
@for f in /opt/clang* ; do if test -x "$$f/bin/clang" ; then $(MAKE) clean ; $(MAKE) check CC="$$f/bin/clang -std=c99 -Werror" CFLAGS="$(WCFLAGS_CLANG)" ; fi ; done
@for f in /opt/tcc* ; do if test -x "$$f/bin/tcc" ; then $(MAKE) clean ; $(MAKE) check CC="$$f/bin/tcc -std=c99 -Werror" ; fi ; done
+63
View File
@@ -0,0 +1,63 @@
/*
* Copyright (c) 2021, Patrick Pelissier
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* + Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* + Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <vector>
#include "m-array.h"
ARRAY_DEF(array_int, int)
// Transform an integer 'i' into a M*LIB base item 'a'
#define TYPE_SET_INT(a, i) (a) = (i)
// Container OPLIST
#define CONT_OPL ARRAY_OPLIST(array_int, M_OPL_int())
// C++ Base class of the item in the container
#define BASE_CLASS int
// Transform an integer 'i' into a C++ base item 'a'
#define CLASS_SET_INT(a, i) (a) = (i)
// C++ Container class
#define CONT_CLASS std::vector<int>
// Compare the M*LIB container a to the C++ container b
#define CMP_CONT(a, b) cmp_cont(a, b)
// Compate the M*LIB base object to the C++ base object
#define CMP_BASE(a, b) assert( (a) == (b) )
void cmp_cont(array_int_t a, std::vector<int> b)
{
size_t s = array_int_size(a);
assert (s == b.size());
for(size_t i = 0; i < s; i++) {
int *b0 = array_int_get(a, i);
int &b1 = b.at(i);
CMP_BASE(*b0, b1);
}
}
#define DEFAULT_NUMBER 1000000
#define HAVE_RESERVE
#define HAVE_RESIZE
#include "check-generic.hpp"
+68
View File
@@ -0,0 +1,68 @@
/*
* Copyright (c) 2021, Patrick Pelissier
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* + Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* + Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <deque>
#include "m-deque.h"
DEQUE_DEF(deque_float, float)
// Transform an integer 'i' into a M*LIB base item 'a'
#define TYPE_SET_INT(a, i) (a) = (i)
// Container OPLIST
#define CONT_OPL DEQUE_OPLIST(deque_float, M_OPL_float())
// C++ Base class of the item in the container
#define BASE_CLASS float
// Transform an integer 'i' into a C++ base item 'a'
#define CLASS_SET_INT(a, i) (a) = (i)
// C++ Container class
#define CONT_CLASS std::deque<float>
// Compare the M*LIB container a to the C++ container b
#define CMP_CONT(a, b) cmp_cont(a, b)
// Compate the M*LIB base object to the C++ base object
#define CMP_BASE(a, b) assert( (a) == (b) )
void cmp_cont(deque_float_t a, std::deque<float> b)
{
deque_float_it_t ita;
deque_float_it(ita, a);
auto itb = b.begin();
while (itb != b.end()) {
assert(!deque_float_end_p(ita));
const float *b0 = deque_float_cref(ita);
float &b1 = *itb;
CMP_BASE(*b0, b1);
itb++;
deque_float_next(ita);
}
assert(deque_float_end_p(ita));
}
#define DEFAULT_NUMBER 1000000
#define HAVE_PUSH_FRONT
#define HAVE_POP_FRONT
#include "check-generic.hpp"
+71
View File
@@ -0,0 +1,71 @@
/*
* Copyright (c) 2021, Patrick Pelissier
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* + Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* + Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <list>
#include "m-list.h"
LIST_DUAL_PUSH_DEF(list_int, int)
// Transform an integer 'i' into a M*LIB base item 'a'
#define TYPE_SET_INT(a, i) (a) = (i)
// Container OPLIST
#define CONT_OPL LIST_OPLIST(list_int, M_OPL_int())
// C++ Base class of the item in the container
#define BASE_CLASS int
// Transform an integer 'i' into a C++ base item 'a'
#define CLASS_SET_INT(a, i) (a) = (i)
// C++ Container class
#define CONT_CLASS std::list<int>
// Compare the M*LIB container a to the C++ container b
#define CMP_CONT(a, b) cmp_cont(a, b)
// Compate the M*LIB base object to the C++ base object
#define CMP_BASE(a, b) assert( (a) == (b) )
void cmp_cont(const list_int_t a, const std::list<int> &b)
{
list_int_it_t ita;
list_int_it(ita, a);
auto itb = b.rbegin();
while (itb != b.rend()) {
assert(!list_int_end_p(ita));
const int *b0 = list_int_cref(ita);
const int &b1 = *itb;
//printf("%d VS %d\n", *b0, b1);
CMP_BASE(*b0, b1);
itb++;
list_int_next(ita);
}
assert(list_int_end_p(ita));
}
#define DEFAULT_NUMBER 100000
#define HAVE_PUSH_FRONT
#define HAVE_REVERSE_IT
#include "check-generic.hpp"
+509
View File
@@ -0,0 +1,509 @@
/*
* Copyright (c) 2021, Patrick Pelissier
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* + Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* + Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <time.h>
/* This test will perform random generic operations on the
M*LIB container and compares it to the same operation on the
C++ equivalent container.
If there are some differences, it reports an error.
It is therefore quite generic and based on the properties of the container
*/
/* Get the types from the container oplist if needed */
#ifndef CONT_TYPE
# define CONT_TYPE_(CONT_OPL) M_GET_TYPE CONT_OPL
# define CONT_TYPE CONT_TYPE_(CONT_OPL)
#endif
#ifndef BASE_TYPE
# define BASE_TYPE_(CONT_OPL) M_GET_SUBTYPE CONT_OPL
# define BASE_TYPE BASE_TYPE_(CONT_OPL)
#endif
#define CONT_NAME_(CONT_OPL) M_GET_NAME CONT_OPL
#define CONT_NAME CONT_NAME_(CONT_OPL)
#define MAX_TEST 28
#ifdef HAVE_REVERSE_IT
// Scan the C++ sequence in reverse
# define begin rbegin
# define end rend
# define IT(x) std::prev(x.base(), 1)
#else
# define IT(x) x
#endif
volatile int test_case;
void test(int select_test, int index,
BASE_TYPE &b0, BASE_CLASS &b1, CONT_TYPE &c0, CONT_CLASS &c1)
{
bool p0 = false, p1 = false;
size_t s0 = 0, s1 = 0;
CONT_TYPE tmp;
#if M_TEST_METHOD_P(IT_TYPE, CONT_OPL)
M_ID(M_GET_IT_TYPE CONT_OPL) it0;
auto it1 = c1.begin();
#endif
// Save in a volatile variable the last test for debug purpose
test_case = select_test % MAX_TEST;
#ifdef DEBUG
printf("Case=%d\n", test_case);
#endif
switch (test_case) {
#if M_TEST_METHOD_P(PUSH, CONT_OPL)
case 0:
TYPE_SET_INT(b0, index);
CLASS_SET_INT(b1, index);
M_CALL_PUSH(CONT_OPL, c0, b0);
c1.push_back(b1);
break;
case 1:
index = index % 1000;
for(int i = 0; i < index; i++) {
TYPE_SET_INT(b0, i);
CLASS_SET_INT(b1, i);
M_CALL_PUSH(CONT_OPL, c0, b0);
c1.push_back(b1);
}
break;
#endif
#if M_TEST_METHOD_P(POP, CONT_OPL)
case 2:
if (!c1.empty()) {
M_CALL_POP(CONT_OPL, &b0, c0);
b1 = c1.back();
c1.pop_back();
}
break;
#endif
#if M_TEST_METHOD_P(EMPTY_P, CONT_OPL)
case 3:
p0 = M_CALL_EMPTY_P(CONT_OPL, c0);
p1 = c1.empty();
break;
#endif
#if M_TEST_METHOD_P(SIZE, CONT_OPL)
case 4:
s0 = M_CALL_SIZE(CONT_OPL, c0);
s1 = c1.size();
break;
#endif
#if M_TEST_METHOD_P(RESET, CONT_OPL)
case 5:
M_CALL_RESET(CONT_OPL, c0);
c1.clear();
break;
#endif
#if M_TEST_METHOD_P(GET_KEY, CONT_OPL)
case 6:
if (!c1.empty()) {
// To rework for dict
index = index % c1.size();
#ifndef HAVE_GET_KEY_THROUGH_FIND
M_CALL_SET(M_GET_OPLIST CONT_OPL, b0, *M_CALL_GET_KEY(CONT_OPL, c0, index));
b1 = c1[index];
#else
BASE_TYPE *p = M_CALL_GET_KEY(CONT_OPL, c0, index);
if (p!= NULL) {
M_CALL_SET(M_GET_OPLIST CONT_OPL, b0, *p);
auto i = c1.find(index);
assert(i != c1.end());
b1 = *i;
} else {
auto i = c1.find(index);
assert(i == c1.end());
TYPE_SET_INT(b0, 0);
CLASS_SET_INT(b1, 0);
}
#endif
}
break;
#endif
#if M_TEST_METHOD_P(SET_KEY, CONT_OPL)
case 7:
if (!c1.empty()) {
TYPE_SET_INT(b0, index);
CLASS_SET_INT(b1, index);
index = index % c1.size();
M_CALL_SET_KEY(CONT_OPL, c0, index, b0);
c1[index] = b1;
}
break;
#endif
#if M_TEST_METHOD_P(ERASE_KEY, CONT_OPL)
case 8:
if (!c1.empty()) {
index = index % c1.size();
p0 = M_CALL_ERASE_KEY(CONT_OPL, c0, index);
#ifndef HAVE_GET_KEY_THROUGH_FIND
c1.erase(c1.begin() + index);
p1 = true;
#else
auto i = c1.find(index);
if (i != c1.end()) {
c1.erase(i);
p1 = true;
} else {
p1 = false;
}
#endif
}
break;
#endif
#if M_TEST_METHOD_P(SET, CONT_OPL) && M_TEST_METHOD_P(INIT_SET, CONT_OPL)
case 9:
M_CALL_INIT_SET(CONT_OPL, tmp, c0);
#if M_TEST_METHOD_P(EQUAL_P, CONT_OPL)
assert( M_CALL_EQUAL_P(CONT_OPL, tmp, c0) );
#endif
M_CALL_SET(CONT_OPL, c0, tmp);
M_CALL_CLEAR(CONT_OPL, tmp);
break;
#endif
#if M_TEST_METHOD_P(INIT_MOVE, CONT_OPL)
case 10:
M_CALL_INIT_MOVE(CONT_OPL, tmp, c0);
M_CALL_INIT_MOVE(CONT_OPL, c0, tmp);
break;
#endif
#if M_TEST_METHOD_P(MOVE, CONT_OPL) && M_TEST_METHOD_P(INIT_MOVE, CONT_OPL)
case 11:
M_CALL_INIT_SET(CONT_OPL, tmp, c0);
M_CALL_MOVE(CONT_OPL, tmp, c0);
M_CALL_INIT_MOVE(CONT_OPL, c0, tmp);
break;
#endif
#if M_TEST_METHOD_P(SWAP, CONT_OPL) && M_TEST_METHOD_P(GET_SIZE, CONT_OPL)
case 12:
s0 = M_CALL_GET_SIZE(CONT_OPL, c0);
M_CALL_INIT(CONT_OPL, tmp);
M_CALL_SWAP(CONT_OPL, tmp, c0);
s1 = M_CALL_GET_SIZE(CONT_OPL, tmp);
M_CALL_SWAP(CONT_OPL, tmp, c0);
M_CALL_CLEAR(CONT_OPL, tmp);
break;
case 13:
M_CALL_INIT_SET(CONT_OPL, tmp, c0);
M_CALL_SWAP(CONT_OPL, tmp, c0);
M_CALL_CLEAR(CONT_OPL, tmp);
break;
#endif
#if M_TEST_METHOD_P(SAFE_GET_KEY, CONT_OPL)
case 14:
// To rework for dict
index = (1 + (c1.size() < 1000000)) * (index % ( c1.size() + 1) );
M_CALL_SET(M_GET_OPLIST CONT_OPL, b0, *M_CALL_SAFE_GET_KEY(CONT_OPL, c0, index));
#ifndef HAVE_GET_KEY_THROUGH_FIND
if ((size_t) index >= c1.size() ) {
c1.resize(index+1);
}
b1 = c1[index];
#else
{
auto i = c1.find(index);
if (i == c1.end()) {
c1.insert(index);
i = c1.find(index);
}
b1 = *i;
}
#endif
break;
#endif
#if M_TEST_METHOD_P(IT_CREF, CONT_OPL)
case 15:
M_CALL_IT_FIRST(CONT_OPL, it0, c0);
it1 = c1.begin();
while (!M_CALL_IT_END_P(CONT_OPL, it0)) {
M_CALL_SET(M_GET_OPLIST CONT_OPL, b0, *M_CALL_IT_CREF(CONT_OPL, it0));
#ifndef DONT_HAVE_SEQUENCE_IT
assert(it1 != c1.end());
b1 = *it1;
it1++;
#else
it1 = c1.find(b0);
assert(it1 != c1.end());
b1 = *it1;
#endif
CMP_BASE(b0, b1);
M_CALL_IT_NEXT(CONT_OPL, it0);
}
#ifndef DONT_HAVE_SEQUENCE_IT
assert(it1 == c1.end());
#endif
break;
#endif
#if M_TEST_METHOD_P(IT_REF, CONT_OPL)
case 16:
M_CALL_IT_FIRST(CONT_OPL, it0, c0);
it1 = c1.begin();
while (it1 != c1.end()) {
assert( !M_CALL_IT_END_P(CONT_OPL, it0));
TYPE_SET_INT(b0, index);
CLASS_SET_INT(b1, index);
M_CALL_SET(M_GET_OPLIST CONT_OPL, *M_CALL_IT_REF(CONT_OPL, it0), b0);
*it1 = b1;
M_CALL_IT_NEXT(CONT_OPL, it0);
it1++;
index = 1457857U * index + 458741U;
}
assert(M_CALL_IT_END_P(CONT_OPL, it0));
break;
#endif
#if M_TEST_METHOD_P(IT_LAST, CONT_OPL)
case 17:
{
M_CALL_IT_LAST(CONT_OPL, it0, c0);
auto it1b = c1.rbegin();
while (it1b != c1.rend()) {
assert( !M_CALL_IT_END_P(CONT_OPL, it0));
M_CALL_SET(M_GET_OPLIST CONT_OPL, b0, *M_CALL_IT_CREF(CONT_OPL, it0));
b1 = *it1b;
CMP_BASE(b0, b1);
M_CALL_IT_PREVIOUS(CONT_OPL, it0);
it1b++;
}
assert(M_CALL_IT_END_P(CONT_OPL, it0));
}
break;
#endif
#if M_TEST_METHOD_P(IT_INSERT, CONT_OPL)
case 18:
M_CALL_IT_FIRST(CONT_OPL, it0, c0);
it1 = c1.begin();
TYPE_SET_INT(b0, index);
CLASS_SET_INT(b1, index);
#ifdef HAVE_INSERT_AFTER
while (it1 != c1.end() ) {
if (rand() > index)
break;
M_CALL_IT_NEXT(CONT_OPL, it0);
it1++;
}
if (it1 != c1.end() ) {
M_CALL_IT_INSERT(CONT_OPL, c0, it0, b0);
c1.insert_after(it1, b1);
}
#else
if (!c1.empty() ){
index = index % c1.size();
if (index == 0) {
M_CALL_IT_END(CONT_OPL, it0, c0);
} else {
for(int i = 0; i < index; i++) {
assert( it1 != c1.end());
assert( !M_CALL_IT_END_P(CONT_OPL, it0));
M_CALL_IT_NEXT(CONT_OPL, it0);
it1++;
}
it1++;
}
}
M_CALL_IT_INSERT(CONT_OPL, c0, it0, b0);
#ifdef HAVE_REVERSE_IT
// in cases of reverse iterator, fix iterator.
it1 = std::prev(it1, 1);
#endif
c1.insert(IT(it1), b1);
#endif
break;
#endif
#if M_TEST_METHOD_P(IT_REMOVE, CONT_OPL)
case 19:
M_CALL_IT_FIRST(CONT_OPL, it0, c0);
it1 = c1.begin();
#ifdef HAVE_ERASE_AFTER
while (it1 != c1.end() ) {
M_CALL_IT_NEXT(CONT_OPL, it0);
if (rand() > index)
break;
it1++;
}
if (it1 != c1.end() && !M_CALL_IT_END_P(CONT_OPL, it0) ) {
M_CALL_IT_REMOVE(CONT_OPL, c0, it0);
c1.erase_after(it1);
}
#else
if (!c1.empty() ){
index = index % c1.size();
for(int i = 0; i < index; i++) {
assert( it1 != c1.end());
assert( !M_CALL_IT_END_P(CONT_OPL, it0));
M_CALL_IT_NEXT(CONT_OPL, it0);
it1++;
}
M_CALL_IT_REMOVE(CONT_OPL, c0, it0);
c1.erase(IT(it1));
}
#endif
break;
#endif
#if M_TEST_METHOD_P(REVERSE, CONT_OPL)
case 20:
M_CALL_REVERSE(CONT_OPL, c0);
c1.reverse();
break;
#endif
#if M_TEST_METHOD_P(SPLICE_BACK, CONT_OPL)
case 21:
M_CALL_REVERSE(CONT_OPL, c0);
c1.reverse();
break;
#endif
#ifdef HAVE_PUSH_FRONT
case 22:
TYPE_SET_INT(b0, index);
CLASS_SET_INT(b1, index);
M_C(CONT_NAME, _push_front)(c0, b0);
c1.push_front(b1);
break;
case 23:
index = index % 1000;
for(int i = 0; i < index; i++) {
TYPE_SET_INT(b0, i);
CLASS_SET_INT(b1, i);
M_C(CONT_NAME, _push_front)(c0, b0);
c1.push_front(b1);
}
break;
#endif
#ifdef HAVE_POP_FRONT
case 24:
if (!c1.empty()) {
M_C(CONT_NAME, _pop_front)(&b0, c0);
b1 = c1.front();
c1.pop_front();
}
break;
#endif
#ifdef HAVE_RESIZE
case 25:
index = (1 + (c1.size() < 1000000)) * (index % ( c1.size() + 1) );
M_C(CONT_NAME, _resize)(c0, index);
c1.resize(index);
break;
#endif
#ifdef HAVE_RESERVE
case 26:
index = c1.size() + ( index % (c1.size() + 1) );
M_C(CONT_NAME, _reserve)(c0, index);
c1.reserve(index);
break;
case 27:
M_C(CONT_NAME, _reserve)(c0, 0);
c1.shrink_to_fit();
break;
#endif
// SPLICE_BACK
// SPLICE_AT
// Needs SPLICE ?
default:
// Nothing to do
break;
}
CMP_BASE(b0, b1);
CMP_CONT(c0, c1);
assert(p0 == p1);
assert(s0 == s1);
}
static void init_rand(void)
{
const char *seed = getenv("CHECK_RANDOMIZE");
if (seed == NULL) {
// No check randomize requested.
// Initialize with a common value
srand(0x45856525U);
} else {
unsigned int seed_value = strtoul (seed, NULL, 10);
if (seed_value > 1) {
// Seed has been set by the user. Use it.
printf("Using seed = %u\n", seed_value);
} else {
time_t tv;
time (&tv);
seed_value = tv;
printf("Generating seed = %u\n", seed_value);
}
srand(seed_value);
}
}
int main(int argc, const char *argv[])
{
int loop = argc >= 2 ? atoi(argv[1]) : DEFAULT_NUMBER;
BASE_TYPE b0;
BASE_CLASS b1;
CONT_TYPE c0;
CONT_CLASS c1;
init_rand();
M_CALL_INIT(CONT_OPL, c0);
M_CALL_INIT(M_GET_OPLIST CONT_OPL, b0);
TYPE_SET_INT(b0, 0);
CLASS_SET_INT(b1, 0);
for(int i = 0; i < loop; i++) {
int t = rand();
int s = rand();
test(t, s, b0, b1, c0, c1);
}
M_CALL_CLEAR(M_GET_OPLIST CONT_OPL, b0);
M_CALL_CLEAR(CONT_OPL, c0);
return 0;
}
+73
View File
@@ -0,0 +1,73 @@
/*
* Copyright (c) 2021, Patrick Pelissier
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* + Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* + Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <forward_list>
#include "m-list.h"
LIST_DEF(list_int, int)
// Transform an integer 'i' into a M*LIB base item 'a'
#define TYPE_SET_INT(a, i) (a) = (i)
// Container OPLIST
#define CONT_OPL LIST_OPLIST(list_int, M_OPL_int())
// C++ Base class of the item in the container
#define BASE_CLASS int
// Transform an integer 'i' into a C++ base item 'a'
#define CLASS_SET_INT(a, i) (a) = (i)
// C++ Container class
#define CONT_CLASS std::forward_list<int>
// Compare the M*LIB container a to the C++ container b
#define CMP_CONT(a, b) cmp_cont(a, b)
// Compate the M*LIB base object to the C++ base object
#define CMP_BASE(a, b) assert( (a) == (b) )
void cmp_cont(list_int_t a, std::forward_list<int> b)
{
list_int_it_t ita;
list_int_it(ita, a);
auto itb = b.begin();
while (itb != b.end()) {
assert(!list_int_end_p(ita));
const int *b0 = list_int_cref(ita);
int &b1 = *itb;
CMP_BASE(*b0, b1);
itb++;
list_int_next(ita);
}
assert(list_int_end_p(ita));
}
#define HAVE_INSERT_AFTER
#define HAVE_ERASE_AFTER
#define DEFAULT_NUMBER 100000
// C++ forward_list pushs in front instead of in back
#define push_back push_front
#define pop_back pop_front
#define back front
#include "check-generic.hpp"
+69
View File
@@ -0,0 +1,69 @@
/*
* Copyright (c) 2021, Patrick Pelissier
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* + Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* + Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <set>
#include "m-rbtree.h"
RBTREE_DEF(tree_int, int)
// Transform an integer 'i' into a M*LIB base item 'a'
#define TYPE_SET_INT(a, i) (a) = (i)
// Container OPLIST
#define CONT_OPL RBTREE_OPLIST(tree_int, M_OPL_int())
// C++ Base class of the item in the container
#define BASE_CLASS int
// Transform an integer 'i' into a C++ base item 'a'
#define CLASS_SET_INT(a, i) (a) = (i)
// C++ Container class
#define CONT_CLASS std::set<int>
// Compare the M*LIB container a to the C++ container b
#define CMP_CONT(a, b) cmp_cont(a, b)
// Compate the M*LIB base object to the C++ base object
#define CMP_BASE(a, b) assert( (a) == (b) )
void cmp_cont(const tree_int_t a, const std::set<int> &b)
{
tree_int_it_t ita;
tree_int_it(ita, a);
auto itb = b.begin();
while (itb != b.end()) {
assert(!tree_int_end_p(ita));
const int *b0 = tree_int_cref(ita);
const int &b1 = *itb;
//printf("%d VS %d\n", *b0, b1);
CMP_BASE(*b0, b1);
itb++;
tree_int_next(ita);
}
assert(tree_int_end_p(ita));
}
#define DEFAULT_NUMBER 1000000
#define push_back insert
#include "check-generic.hpp"
Loaded 100 of 141 files, more files were not shown because too many files have changed in this diff. Show more