defs.h(3)
💖 NAME — defs.h 💖
okay so bestie, welcome to defs.h(3), straight outta the Library Functions Manual 🫶 this is where the base layer lives — defs.h — Базовые определения, the literal foundation that everything else in the library is standing on. main character energy, no cap 👑
✨ SYNOPSIS ✨
#include <limits.h>
#include <stddef.h>
🎀 Макросы (Macros)
LITTLE_ENDIAN—1234— the little-endian arrangement: order runs from the least significant to the most significant ("Порядок от младших к старшим") 💅BIG_ENDIAN—4321— the big-endian arrangement: order runs from the most significant to the least significant ("Порядок от старших к младшим") ✨OCTET_ORDER—LITTLE_ENDIAN— which octet order the machine word uses 👑B_PER_W—16— how many bits fit in one machine word 🎀O_PER_W—(B_PER_W / 8)— how many octets fit in one machine word 🦋O_PER_S—(B_PER_S / 8)— how many octets fit in asize_t🌸B_PER_S—32— how many bits fit in asize_t⭐O_OF_B(nb)— how many octets it takes to holdnbbits 💜W_OF_B(nb)— how many machine words it takes to holdnbbits 🔥B_OF_O(no)— how many bits it takes to holdnooctets 🍓W_OF_O(no)— how many machine words it takes to holdnooctets 🧚O_OF_W(nw)— how many octets it takes to holdnwmachine words 🌈B_OF_W(nw)— how many bits it takes to holdnwmachine words 💖ERR_OK—((err_t)0)— the success code, the good ending 🫶ERR_MAX—(ERR_OK - (err_t)1)— the maximum error code 😭B_PER_IMPOSSIBLE—((size_t)64)— the impossible event 💀
🦋 Определения типов (Typedefs)
u8—typedef unsigned char— an 8-bit unsigned integer ✨i8—typedef signed char— an 8-bit signed integer 🎀octet—typedef u8— an octet 💅u16—typedef unsigned short— a 16-bit unsigned integer 🌸i16—typedef signed short— a 16-bit signed integer ⭐u32—typedef unsigned int— a 32-bit unsigned integer 💜i32—typedef signed int— a 32-bit signed integer 🔥word—typedef u16— a machine word 👑dword—typedef u32— a double machine word 🦋bool_t—typedef int— a boolean type 🌈err_t—typedef u32— error codes 🍓gen_i—typedef void(* gen_i) (void *buf, size_t count, void *state)— the generation interface 🧚read_i—typedef err_t(* read_i) (size_t *read, void *buf, size_t count, void *file)— the read interface 💖write_i—typedef err_t(* write_i) (size_t *written, const void *buf, size_t count, void *file)— the write interface 🫶
🌸 Подробное описание (Detailed Description)
💜 Типы данных (Data Types)
⭐ Предусловие (Precondition)
- The length of a machine word in bits (
B_PER_W) equals 16, 32 or 64. - The length of a
size_tword in bits is not less than 16. - The types
u16,u32must be supported. - The types
u64,u128may be supported.
🙈 Прим. (Note)
- Supporting
B_PER_W == 16is genuinely useful for setting up testing of big-number arithmetic and polynomial arithmetic: as a rule, errors in arithmetic functions pop up with probabilities close to1 / 2^B_PER_W. - When the platforms were analysed to determine octet order, the code of Brian Gladman (Brian Gladman, http://www.gladman.me.uk/) was used, plus the resource https://sourceforge.net/p/predef/wiki/Endianness/.
- The
EMSCRIPTENplatform (https://emscripten.org) is virtual — compilation toasm.jshappens on it.
🍓 Массивы (Arrays)
An array of elements of type T is, as a rule, passed into a function as a pair (a pointer in to the array elements, the array length in_len). Here in has type const T*, and in_len has type size_t. When documenting an array, the notation [in_len]in is used. When T == void, the notation means exactly the same as when T == octet 💅
If the length in_len is known in advance, it doesn't have to be passed into the function at all.
An array of elements of type T with an advance-known size is returned from functions through a buffer that the pointer out of type T* points to 🎀
If the array length isn't known in advance, then the pair (pointer out, size out_len) is used to return it, where out_len has type size_t*. If you call the function with a null out, then the length of the returned array gets placed at the address out_len. If you call it with a non-null out, then at the address out_len you must have specified the number of elements of type T reserved in the buffer out. As a result of running the function, the number at the address out_len gets corrected — it's set equal to the actual number of elements written into the array out. The buffer size may be checked by preconditions. If the size isn't enough, the function may report that through return codes 🌸
When documenting the array-return logic described above, the notation [?out_len]out is used. When T == void, the notation means exactly the same as when T == octet ✨
There's a similar syntax, [out_len?]out. The difference is that when you call the function with a non-null pointer out, the value at the address out_len is undefined — moreover, with additional caveats, the address out_len itself may be null 😭
The expression out_len? may be part of an arithmetic expression that refines the required amount of memory. For example, the notation [out_len? + 1]str means that the buffer (string) str requires one octet in addition to out_len (the terminating null character gets written into it) ⭐
🧚 Последовательности вызовов (Call Sequences)
Restrictions on the sequence of calls of certain functions are documented using the signs "<", "*" and "<<" 💜
The notation "f1() < f2()" means that the function f2() must be called after f1().
The notation "f1() < [f2()] < f3()" means that the function f2() must be called after f1(), f3() after f2(), and the call to f2() may be skipped 🙈
The notation "f()*" means that the function f() may be called sequentially an arbitrary number of times 🔥
The notation "f1()* < f2()" means that several calls of f1() finish up with a call of f2() 👑
The notation "(f1()* < f2())*" means that the cascade "several times f1(), then f2()" may repeat an arbitrary number of times. For example, the possibility of incremental hashing, where you can compute the hash value of an ever-longer fragment, is denoted like this:
(hash_step()* < hash_get())*.
The sign "<<" is used when documenting protocols. The notation "f1() << f2()" means that before the function f2() is called, side A must call the function f1() and send the results of its work over to side B 🦋
👑 Макросы (Macros)
💀 #define B_PER_IMPOSSIBLE ((size_t)64)
An event whose probability of occurring is <= 2^{-B_PER_IMPOSSIBLE} is considered impossible. literally do not worry about it, bestie 💅
🙈 Прим. (Note)
Э. Борель: "событие, вероятность которого ниже10^{-50} ≈ 2^{-166}, не произойдет никогда, сколько бы возможностейни представилось" [Probability and Life, 1962].
🎀 ТИПЫ 🎀
Окей бести, вот мы и дошли до типов 💖 Это буквально словарь, на котором говорит вся библиотека, так что если хочешь реально понимать её вайб — вникай, ноу кэп.
typedef u32 err_t
Прим.
Высокоуровневые функции возвращают значения типа err_t. Это такой вайб-чек того, как всё прошло:
ERR_OK— функция завершена успешно, слэй, идём дальше ✨ERR_MAX— этот код зарезервирован для описания специальных особых ситуаций, то есть он не про «всё сломалось», у него отдельная работа- любое другое значение — ошибка при выполнении функции 😭 и вот тут уже не до шуток
typedef void(* gen_i) (void *buf, size_t count, void *state)
Функция интерфейса gen_i генерирует count октетов и записывает их в буфер buf. При генерации может использоваться и изменяться вспомогательная память (состояние) state. 🦋
Функция интерфейса gen_i интерпретируется как генератор с состоянием state. Используются генераторы двух типов:
- rng (random number generator) — генераторы случайных или псевдослучайных чисел;
- ang (arbitrary number generator) — генераторы произвольных чисел, которые реализуют принцип «выбрать произвольным образом». Генерируемые числа (октеты) могут строиться по меткам времени, значениям монотонного счетчика, случайным или псевдослучайным числам. Числа могут использоваться в криптографических протоколах для построения синхропосылок, нонсов, затравочных значений (seed), «соли» (salt). 👑
Предусловие
- Буфер
bufкорректен. - Состояние
stateкорректно.
Ожидается
- Состояние
stateподдерживается постоянным между последовательными обращениями к функции.
Ожидается
- Октеты, формируемые генераторами rng, обладают минимальным статистическим качеством: каждое значение встречается с примерно равной частотой.
Ожидается
- Октеты, формируемые генераторами ang, почти не повторяются (повторяются только с пренебрежимо малыми вероятностями или только на недостижимо больших интервалах наблюдения).
Прим.
Функция интерфейса gen_i всегда генерирует все запрашиваемые октеты. Ошибки при генерации не предусмотрены. Вот вообще ни одной, просто доверься ей 🫶
Аргументы
buf— случайные числаcount— число октетовstate— состояние
typedef err_t(* read_i) (size_t *read, void *buf, size_t count, void *file)
Функция интерфейса read_i читает данные из файла file в буфер [count]buf. По адресу read возвращается число прочитанных октетов. 🌸
Предусловие
- Буфер
bufкорректен. - Указатель
readкорректен. - Файл
fileкорректен.
Возвращает
ERR_OK, если прочитано определенное число октетов (возможно меньшее count и возможно нулевое) и конец файла не достигнут, ERR_MAX, если прочитано меньше чем count октетов и достигнут конец файла, или другой код ошибки.
Прим.
- Файл — это произвольный массив или поток данных на произвольном устройстве. В качестве файла может выступать обычный дисковый файл, сетевое соединение, источник случайности и т.д. 💅
- Для файлов некоторых устройств ошибкой не считается ситуация, когда прочитано меньше чем
countоктетов. Данная ситуация может быть связана с ожиданием данных в канале связи. - Передавая
count == 0, можно проверить наличие файла.
Аргументы
read— число прочитанных октетовbuf— прочитанные данныеcount— длинаbufв октетахfile— описание файла
typedef err_t(* write_i) (size_t *written, const void *buf, size_t count, void *file)
Функция интерфейса write_i записывает буфер [count]buf в файл file. По адресу written возвращается число записанных в файл октетов. ✨
Предусловие
- Указатель
writtenкорректен. - Буфер
bufкорректен. - Файл
fileкорректен.
Возвращает
ERR_OK, если записаны все октеты buf, и код ошибки в противном случае.
Аргументы
written— число записанных октетовbuf— записываемые данныеcount— длинаbufв октетахfile— описание файла
✍️ АВТОР ✍️
Автоматически создано Doxygen для Библиотека Bee2 из исходного текста.
Всё, бести, это была Библиотека Bee2, страничка defs.h(3), собранная Вс 25 Янв 2026 00:00:00 — и да, её сгенерил Doxygen, а не человек, так что если найдёшь где-то кривой пробел, ты знаешь, кого винить 😭💖 Спасибо, что дочитала до конца, ты буквально main character. Периодт. 🌈⭐
📦 where this page comes from
- fedora 44: bee2-devel 2.2.0-1.fc44 · GPL-3.0-only and GPL-3.0-or-later
- fedora 44: bee2-devel 2.2.0-1.fc44 · GPL-3.0-only and GPL-3.0-or-later
- 💖 girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms