Одиночный распределитель арены. C89 Совместим.
arena.h Распределители арены - это простой способ достижения более легкого, более быстрого и более безопасного динамического управления памятью, позволяя освободить множественные распределения в качестве группы. Это делается путем распределения памяти в больших областях, а затем распределяя части этой памяти по мере необходимости, уменьшая количество вызовов malloc (которые медленные по сравнению с простой арифметикой указателя).
Когда вы уничтожаете арену, вы также освобождаете ее и все его содержимое, уменьшая количество free вызовов, которые также являются медленными. Идя дальше, вы можете очистить арены, просто сбросив их указатели памяти на 0 , позволяя вам повторно использовать их и устраняя необходимость в еще большем количестве malloc и free '.
Вы можете узнать больше о распределителях арены/зоны/региона, прочитав эту фантастическую статью.
Я оставлю это коротким. Я поддерживаю соответствие C89 для развлечения, а не потому, что использую его. Лично я наслаждаюсь C11. Если вы думаете, C89 - единственный способ, хорошо, хорошо для вас! Но ты ошибаешься.
Всякий раз, когда я делюсь этим проектом с другими программистами, один из самых распространенных ответов, которые я получаю, - это что -то вроде: Вы никогда не должны помещать код реализации/логики в файл заголовка! Я не согласен с этим заявлением по трем причинам ...
Это показывает, что устаревшая и, как следствие, вредная конструкция все еще применяется в системе образования, где обычно вводится указанная конструкция.
Очень редко у человека, делающего это утверждение, есть фактическая причина поверить в это. Этот человек когда -нибудь задумывался о том, почему он никогда не должен «никогда не помещать код реализации/логики в файл заголовка»? Простое извержение того, что они слышали без какой -либо основы, почему они решили согласиться с этим, не поможет мне никоим образом, и этот человек не должен ожидать, что я просто приму это, как он это сделал.
Самая большая и наиболее достоверная критика библиотек только для заголовков/одноголовки заключается в том, что изменение заголовка требует повторной компиляции всех файлов, которые включают его. В случае моего проекта, внесение изменений в arena.h , хотя фактическая реализация содержится только в блоке перевода, что #define 's на макрос ARENA_IMPLEMENTATION приведет к восстановлению всех файлов, которые включают его. Решение? Как только arena.h
Связывание вяло и сложно. Многие новички часто борются с изучением процесса связывания, и они также являются самым большим виновником, когда дело доходит до написания небезопасного кода. Одно это достаточно, чтобы я сделал этот распределитель Arena в библиотеке только для заголовков. Мой код (в его текущем состоянии) очень маленький, примерно 300 строк. Зачем мне заставлять вас создавать и связать такую небольшую реализацию, когда вы могли бы просто #include ее один раз и начать использовать ее из коробки? Если у вас действительно есть проблема с этим, этот распределитель в формате с одним заголовком не мешает вам следить за конструкцией заголовка источника+, если вы этого хотите. Черт возьми, не стесняйтесь раскошелить его и сделать источник+заголовок, это открытый исходный код по причине!
Это не реализует распределитель на уровне ядра, но вместо этого завершает malloc и free (стандартная библиотека или пользователь, ваш выбор).
Хотя я считаю, что программное обеспечение должно быть с открытым исходным кодом, я не считаю, что этично потребует программного обеспечения, которое использует эту библиотеку, чтобы также быть открытым исходным кодом. В современную эпоху технологий и текущего состояния мира написание, безопасного для памяти кода, более важное, чем когда-либо. По этой причине это программное обеспечение лицензировано в соответствии с версией 2.0 Apache. Вам настоятельно рекомендуется прочитать LICENSE (включенную ниже, в arena.h , и ее собственный файл в этом репо), если вы рассматриваете возможность использования программного обеспечения, если вы не считаете, что вы на 100% знакомы с условиями.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Copyright 2024 Carter Dugan
Документация для распределения арены может быть найдена на arena.h . В верхней части заголовка есть комментарий с быстрыми инструкциями для использования для вашего удобства.
Для одного файла в одном блоке перевода вам нужно следующее:
#define ARENA_IMPLEMENTATION
#include "arena.h" С этого момента другие файлы в других переводах могут просто #include "arena.h" обычно. Есть дополнительные макросы, которые вы можете определить/использовать. См. Раздел о функциях и макросах.
Есть две структуры, определенные на arena.h . Это перечисляет каждый вместе с его членами.
Arena_Allocation Структура данных для распределения арены. Доступно только тогда, когда определяется ARENA_DEBUG .
size_t index Индекс на арене, на которой находится начало распределения.size_t size Размер памяти, выделенной на это распределение в байтах.char *pointer указатель, связанный для распределения.struct Arena_Allocation_s *next следующее распределение в связанном списке. Arena Структура данных для арены.
char *region региона выделенной памяти.size_t index индекс области для следующего указателя, который будет распределен.size_t size размер памяти, выделенной на арену в байтах.unsigned long allocations количество распределения арены, которые были сделаны. Доступно только тогда, когда определяется ARENA_DEBUG .Arena_Allocation *head_allocation Первое распределение, сделанное на арене (используется для связанного списка). Доступно только тогда, когда определяется ARENA_DEBUG . /*
Allocate and return a pointer to memory to the arena
with a region with the specified size. Providing a
size of zero results in a failure.
Parameters:
size_t size | The size (in bytes) of the arena
memory region.
Return:
Pointer to arena on success, NULL on failure
*/
Arena * arena_create ( size_t size );
/*
Return a pointer to a portion of specified size of the
specified arena's region. Nothing will restrict you
from allocating more memory than you specified, so be
mindful of your memory (as you should anyways) or you
will get some hard-to-track bugs. By default, memory is
aligned by alignof(size_t), but you can change this by
#defining ARENA_DEFAULT_ALIGNMENT before #include'ing
arena.h. Providing a size of zero results in a failure.
Parameters:
Arena *arena | The arena of which the pointer
from the region will be
distributed
size_t size | The size (in bytes) of
allocated memory planned to be
used.
Return:
Pointer to arena region segment on success, NULL on
failure.
*/
ARENA_INLINE void * arena_alloc ( Arena * arena , size_t size );
/*
Same as arena_alloc, except you can specify a memory
alignment for allocations.
Return a pointer to a portion of specified size of the
specified arena's region. Nothing will restrict you
from allocating more memory than you specified, so be
mindful of your memory (as you should anyways) or you
will get some hard-to-track bugs. Providing a size of
zero results in a failure.
Parameters:
Arena *arena | The arena of which the pointer
from the region will be
distributed
size_t size | The size (in bytes) of
allocated memory planned to be
used.
unsigned int alignment | Alignment (in bytes) for each
memory allocation.
Return:
Pointer to arena region segment on success, NULL on
failure.
*/
void * arena_alloc_aligned ( Arena * arena , size_t size , unsigned int alignment );
/*
Copy the memory contents of one arena to another.
Parameters:
Arena *src | The arena being copied, the source.
Arena *dest | The arena being copied to. Must be created/allocated
already.
Return:
Number of bytes copied.
*/
ARENA_INLINE size_t arena_copy ( Arena * dest , Arena * src );
/*
Reset the pointer to the arena region to the beginning
of the allocation. Allows reuse of the memory without
realloc or frees.
Parameters:
Arena *arena | The arena to be cleared.
*/
ARENA_INLINE void arena_clear ( Arena * arena );
/*
Free the memory allocated for the entire arena region.
Parameters:
Arena *arena | The arena to be destroyed.
*/
ARENA_INLINE void arena_destroy ( Arena * arena );
/*
Returns a pointer to the allocation struct associated
with a pointer to a segment in the specified arena's
region.
Parameters:
Arena *arena | The arena whose region should
have a portion pointed to by
ptr.
void *ptr | The ptr being searched for
within the arena in order to
find an allocation struct
associated with it.
*/
Arena_Allocation * arena_get_allocation_struct ( Arena * arena , void * ptr );
/*
Adds an arena allocation to the arena's linked list of
allocations under debug.
Parameters:
Arena *arena | The arena whose allocation list
should be added to
size_t size | The size of the allocation being
added.
*/
void arena_add_allocation ( Arena * arena , size_t size );
/*
Deletes the arena's linked list of allocations under
debug.
Parameters:
Arena *arena | The arena whose allocation list
is being deleted.
*/
void arena_delete_allocation_list ( Arena * arena ); В вашем коде вы можете определить некоторые дополнительные макросы. ARENA_MALLOC , ARENA_FREE и ARENA_MEMCPY может быть назначен альтернативным функциям, похожим на malloc , free и memcpy , соответственно, и arena.h будет использовать их вместо стандартных библиотечных функций. Вы можете получить доступ к дополнительной функциональности отладки для отслеживания распределения, определяя ARENA_DEBUG . Наконец, вы также можете указать значение по умолчанию для выравнивания распределения, определив значение для ARENA_DEFAULT_ALIGNMENT . Смотрите ниже для примеров.
// All of these are optional
// Replace standard library functions
#define ARENA_MALLOC <stdlib_malloc_like_allocator>
#define ARENA_FREE <stdlib_free_like_deallocator>
#define ARENA_MEMCPY <stdlib_memcpy_like_copier>
// for debug functionality:
#define ARENA_DEBUG
// If you would like to change the default alignment for
// allocations:
#define ARENA_DEFAULT_ALIGNMENT <alignment_value> Существует также макрос для определения выравнивания типов. Как и все остальное, это также является C89, хотя при компиляции в C11 он будет использовать alignof stdalign.h .
ARENA_ALIGNOF ( type ) // Gives alignment of `type` Код был написан для создания с любым компилятором, который поддерживает стандарт C89 и работает на любой платформе. Тем не менее, есть некоторые проблемы с строительством в окнах с помощью Makefile . Пожалуйста, прочитайте всю ниже информацию.
Тесты и примеры были скомпилированы и успешно запускаются под следующими компиляторами и версиями:
Тесты и примеры были скомпилированы и успешно запускаются в следующих операционных системах:
Обратите внимание, что Makefile в настоящее время не была настроена на работу в Windows при запуске $ make test из -за использования Valgrind и отсутствия расширений .exe . Это должно быть простое исправление и находится в моем списке Todo (не стесняйтесь открывать проблему и исправить это самостоятельно!).
Этот проект имеет очень простые руководящие принципы для участия.
Для любых вкладов в код arena.h , пожалуйста, откройте запрос на вытяжку, только если вы решаете проблему для выполнения запроса функции или исправления ошибки . Следуйте стилю кода и запустите автоматические тесты перед открытием запроса на вытяжение. Все тесты должны быть проведены.
Для запросов на функции или ошибок откройте проблему . Затем вы можете решить эту проблему самостоятельно.
Для чего угодно , откройте проблему, и мы обсудим ее.
arena.hНа данный момент нет документации для стиля кода, но он должен быть достаточно простым, чтобы привлечь через чтение существующего кода для большинства вещей. Если у вас проблемы, не стесняйтесь открывать проблему для FR. Если это уже существует, прокомментируйте это, описывая, что вы смущены.
Если вы измените arena.h вообще, вы должны запустить тесты. Смотрите следующий раздел.
Если вы добавите функцию в arena.h , вы должны создать адекватный тест или тесты в test.c
Если вы добавите функцию в arena.h , вы должны адекватный пример в code_examples/ и добавить ее в makefile , но это не требуется.
Если вы измените arena.h вообще, запустите тесты перед открытием PR . Если вы откроете PR с модификациями кода, и тесты не все пройдут, сделайте комментарий о своем пиаре, заявив, что, по вашему мнению, является неправильным, и не позволяет вам пройти все тесты. Если какой -либо тест не пройдет, и у вашего пиара нет комментариев, который утверждает, что исправляет неудачный тест, ваш PR будет игнорироваться закрыто.
Помимо адресации ошибок и запросов функций, выполнение запроса функции или исправления ошибки для функциональности на arena.h позволяет изменять или добавлять соответствующий код тестирования в test.c , и вы должны сделать это, если вы хотите, чтобы ваш пиар был признан. Существует документация для тестирования кода в test.c в верхней части файла в форме комментариев.
Тесты также должны пройти через valgrind без утечки, а arena.h должен соответствовать C89. Вы должны проверить это с помощью Makefile , но если по какой -то причине вы не можете или не хотите, скомпилируйте test.c с
-Werror -Wall -Wextra -Wstrict-prototypes -Wold-style-definition -Wmissing-prototypes -Wmissing-declarations -Wdeclaration-after-statement
И для соответствия, компилируйте test_compliance.c с
-pedantic -std=c89 -Werror -Wall -Wextra -Wstrict-prototypes -Wold-style-definition -Wmissing-prototypes -Wmissing-declarations -Wdeclaration-after-statement
Как я уже сказал, вы можете сделать все это с помощью Makefile
$ make test
Идентификаторы
variable_name . Для указателей звездочка ( * ) должна быть прикреплена к имени переменной, а не тип, например, type *variable_name .type function_name(p1, p2, ...) . В случае указателей звездочка ( * ) должна быть прикреплена к типу для плотности, например type* function_name(p1, p2, ...) . Функции должны иметь прямое объявление с комментарием к документации над ней вокруг вершины файла, убедитесь, что порядок относительно других функций является согласованным.struct StructName . Они должны быть напечатаны и расположены вокруг верхней части файла заголовка.ARENA_ , например, ARENA_MACRO_NAME . Пожалуйста, не добавляйте макросов, не консультируясь со мной в первую очередь . Не стесняйтесь вносить изменения в существующие макросы, хотя.Белое пространство основано на актуальности линии кода для окружающих. Если вы не понимаете, что означают эти пункты, пожалуйста, посмотрите на код. Это должно быть отформатировано следующим образом:
Проверка ошибок должна быть выполнена по возможности, и имитируйте поведение стандартных реализаций библиотеки, таких как возврат NULL по ошибке в функциях, которые возвращают указатели или возвращение целочисленных значений ошибок из целочисленных функций. Вы должны использовать раннюю проверку ошибок , что означает проверку ошибок, как только они могут быть произведены, например. Проверка на NULL возвращение после неудачного вызова malloc .
Комментарии должны описать, почему вы что -то сделали, а не то , что вы сделали. Другими словами, ваш код должен быть самостоятельным. Документация для функций в форме комментариев должна быть расположена над функцией в следующем формате:
/*
Description of function, description of function description of function.
Description of function description of function, description of function
description of function.
Parameters:
paramter1_type paramter1_name | Description of parameter 1, description
of parameter one description of paramter
1.
paramter2_type paramter2_name | Description of parameter 2, description
of parameter one description of paramter
2.
Return:
Description of return value, description of return value description of return value.
*/