Compare commits

..
21 Commits
Author SHA1 Message Date
aZholtikov 1a1351b60f doc: added wiki 2026-10-17 09:08:58 +03:00
aZholtikov 9e81485984 perf: updated error checks 2026-10-03 11:09:07 +03:00
aZholtikov 1891599e66 fix: allocate new item in push_front before shifting 2026-09-25 18:49:41 +03:00
aZholtikov 288aca9905 style: updated comments 2026-09-12 12:20:45 +03:00
aZholtikov 865acc77a2 doc: updated readme 2026-08-30 17:37:50 +03:00
aZholtikov fb17cd1844 style: updated comments 2026-08-02 07:49:04 +03:00
aZholtikov f17658bcff style: updated comments 2026-08-01 10:41:33 +03:00
aZholtikov e0d0a2894d style: removed unused macros 2026-07-19 19:53:38 +03:00
aZholtikov 1632cb4d28 feat: added deletion of the first or last element 2026-07-19 17:51:09 +03:00
aZholtikov f46ab3f5fb fix: incorrect found index value size 2026-07-18 09:31:54 +03:00
aZholtikov b61ea6f80b doc: style 2026-07-15 20:51:38 +03:00
aZholtikov 847cccc34e feat: added finding specific field in a vector of structures 2026-07-15 11:51:59 +03:00
aZholtikov c0267639e5 style: zeroing out pointers 2026-07-13 16:51:36 +03:00
aZholtikov 0b800218f2 style: updated error macros 2026-07-12 19:10:24 +03:00
aZholtikov 684b38e52d perf: updated error checks 2026-07-12 12:45:22 +03:00
aZholtikov da07ed2114 feat: added finding item 2026-07-12 10:22:24 +03:00
aZholtikov 5fecd800e6 doc: typo 2026-07-12 09:59:21 +03:00
aZholtikov f83572e0e8 feat: added duplicate removing 2026-07-12 09:48:58 +03:00
aZholtikov 6263d23d65 feat: added getting vector capacity 2026-07-05 11:49:43 +03:00
aZholtikov e4a842508a refactor: refactored by pvs-studio 2026-07-05 10:20:20 +03:00
aZholtikov c76486fa82 feat!: main structure of vector changed to double pointer 2026-07-05 10:14:16 +03:00
8 changed files with 1159 additions and 996 deletions

No files matched your search

+312 -20
View File
@@ -1,31 +1,20 @@
# ESP32 ESP-IDF component for vector (dynamic array) # ESP32 ESP-IDF component for vector (dynamic array)
## Note
This version is outdated and will be updated from the "dev" branch at the end of the year. Please use the "dev" branch for new development.
## Wiki
[EN](WIKI_EN.md) | [RU](WIKI_RU.md)
## Tested on
1. [ESP32 ESP-IDF v6.0.0](https://docs.espressif.com/projects/esp-idf/en/v6.0/esp32/index.html)
## SAST Tools
[PVS-Studio](https://pvs-studio.com/pvs-studio/?utm_source=website&utm_medium=github&utm_campaign=open_source) - static analyzer for C, C++, C#, and Java code.
## Features ## Features
1. Support of any data types. 1. Support for any data types through void pointers.
2. The maximum size of the veсtor is 65535 elements. 2. Dynamic capacity with automatic growth and shrinkage.
3. Maximum capacity of 65,535 elements (16-bit index).
4. Thread-safe implementation using FreeRTOS mutex.
5. Automatic memory management with ESP-IDF heap_caps functions.
6. Flexible insertion at front or back.
7. Duplicate removal and item search capabilities.
## Using ## Using
In an existing project, run the following command to install the component: In an existing project, run the following command to install the component:
```text ```bash
cd ../your_project/components cd ../your_project/components
git clone https://github.com/aZholtikov/zh_vector git clone https://github.com/aZholtikov/zh_vector
``` ```
@@ -38,4 +27,307 @@ In the application, add the component:
## Examples ## Examples
See Wiki [EN](WIKI_EN.md#usage-examples) | [RU](WIKI_RU.md#примеры-использования) ### Basic Example: Integer Vector
```c
#include "zh_vector.h"
zh_vector_t *vector = NULL;
void app_main(void)
{
esp_log_level_set("zh_vector", ESP_LOG_ERROR);
esp_err_t ret = zh_vector_init(&vector, sizeof(int));
if (ret != ESP_OK)
{
printf("Vector initialization error\n");
return;
}
int val1 = 10;
int val2 = 20;
int val3 = 30;
zh_vector_push_front(&vector, &val1);
zh_vector_push_back(&vector, &val2);
zh_vector_push_back(&vector, &val3);
uint16_t size = 0;
ret = zh_vector_get_size(&vector, &size);
if (ret == ESP_OK)
{
printf("Vector size: %u\n", size);
}
for (int i = 0; i < size; i++)
{
int item_value = 0;
esp_err_t err = zh_vector_get_item(&vector, (uint16_t)i, &item_value);
if (err == ESP_OK)
{
printf("Element %d: %d\n", i, item_value);
}
else
{
printf("Error getting element %d: %s\n", i, esp_err_to_name(err));
}
}
int new_val = 100;
zh_vector_change_item(&vector, 1, &new_val);
zh_vector_delete_item(&vector, 0);
zh_vector_free(&vector);
}
```
### Struct Example
```c
#include "zh_vector.h"
typedef struct
{
int id;
char name[32];
float value;
} my_struct_t;
zh_vector_t *vector = NULL;
void app_main(void)
{
esp_log_level_set("zh_vector", ESP_LOG_ERROR);
esp_err_t ret = zh_vector_init(&vector, sizeof(my_struct_t));
if (ret != ESP_OK)
{
printf("Vector initialization error\n");
return;
}
my_struct_t item1 = {1, "Item 1", 1.5f};
my_struct_t item2 = {2, "Item 2", 2.5f};
zh_vector_push_front(&vector, &item1);
zh_vector_push_back(&vector, &item2);
my_struct_t item_value = {0};
esp_err_t err = zh_vector_get_item(&vector, 0, &item_value);
if (err == ESP_OK)
{
item_value.value = 10.5f;
zh_vector_change_item(&vector, 0, &item_value);
}
zh_vector_free(&vector);
}
```
### String Example (Char Arrays)
```c
#include "zh_vector.h"
zh_vector_t *vector = NULL;
void app_main(void)
{
esp_log_level_set("zh_vector", ESP_LOG_ERROR);
esp_err_t ret = zh_vector_init(&vector, 100);
if (ret != ESP_OK)
{
printf("Vector initialization error\n");
return;
}
char *str1 = malloc(100);
char *str2 = malloc(100);
if (str1 && str2)
{
strcpy(str1, "Hello");
strcpy(str2, "World");
zh_vector_push_back(&vector, str1);
zh_vector_push_back(&vector, str2);
free(str1);
free(str2);
}
uint16_t size = 0;
ret = zh_vector_get_size(&vector, &size);
if (ret == ESP_OK)
{
for (int i = 0; i < size; i++)
{
char str_value[100] = {0};
esp_err_t err = zh_vector_get_item(&vector, (uint16_t)i, str_value);
if (err == ESP_OK)
{
printf("String %d: %s\n", i, str_value);
}
else
{
printf("Error getting string %d: %s\n", i, esp_err_to_name(err));
}
}
}
zh_vector_remove_duplicates(&vector);
zh_vector_free(&vector);
}
```
### Remove Duplicates Example
```c
#include "zh_vector.h"
zh_vector_t *vector = NULL;
void app_main(void)
{
esp_log_level_set("zh_vector", ESP_LOG_ERROR);
esp_err_t ret = zh_vector_init(&vector, sizeof(int));
if (ret != ESP_OK)
{
printf("Vector initialization error\n");
return;
}
int val1 = 10;
int val2 = 20;
int val3 = 10;
int val4 = 30;
int val5 = 20;
zh_vector_push_back(&vector, &val1);
zh_vector_push_back(&vector, &val2);
zh_vector_push_back(&vector, &val3);
zh_vector_push_back(&vector, &val4);
zh_vector_push_back(&vector, &val5);
uint16_t size = 0;
ret = zh_vector_get_size(&vector, &size);
if (ret == ESP_OK)
{
printf("Vector size before removing duplicates: %u\n", size);
}
zh_vector_remove_duplicates(&vector);
ret = zh_vector_get_size(&vector, &size);
if (ret == ESP_OK)
{
printf("Vector size after removing duplicates: %u\n", size);
}
for (int i = 0; i < size; ++i)
{
int item_value = 0;
esp_err_t err = zh_vector_get_item(&vector, (uint16_t)i, &item_value);
if (err == ESP_OK)
{
printf("Element %d: %d\n", i, item_value);
}
else
{
printf("Error getting element %d: %s\n", i, esp_err_to_name(err));
}
}
zh_vector_free(&vector);
}
```
---
### Find Item Example
```c
#include "zh_vector.h"
zh_vector_t *vector = NULL;
void app_main(void)
{
esp_log_level_set("zh_vector", ESP_LOG_ERROR);
esp_err_t ret = zh_vector_init(&vector, sizeof(int));
if (ret != ESP_OK)
{
printf("Vector initialization error\n");
return;
}
int val1 = 10;
int val2 = 20;
int val3 = 30;
zh_vector_push_back(&vector, &val1);
zh_vector_push_back(&vector, &val2);
zh_vector_push_back(&vector, &val3);
int search_item = 20;
int32_t found_index = -1;
ret = zh_vector_find_item(&vector, &search_item, &found_index);
if (ret == ESP_OK)
{
printf("Element %d found at index %d\n", search_item, (int)found_index);
}
else
{
printf("Element %d not found (index=%d)\n", search_item, (int)found_index);
}
search_item = 100;
found_index = -1;
ret = zh_vector_find_item(&vector, &search_item, &found_index);
if (ret == ESP_OK)
{
printf("Element %d found at index %d\n", search_item, (int)found_index);
}
else
{
printf("Element %d not found (index=%d)\n", search_item, (int)found_index);
}
zh_vector_free(&vector);
}
```
---
### Find Item in Field Example
```c
#include "zh_vector.h"
typedef struct
{
int id;
char name[32];
float value;
} my_struct_t;
zh_vector_t *vector = NULL;
void app_main(void)
{
esp_log_level_set("zh_vector", ESP_LOG_ERROR);
esp_err_t ret = zh_vector_init(&vector, sizeof(my_struct_t));
if (ret != ESP_OK)
{
printf("Vector initialization error\n");
return;
}
my_struct_t item1 = {1, "Item 1", 1.5f};
my_struct_t item2 = {2, "Item 2", 2.5f};
my_struct_t item3 = {3, "Item 3", 3.5f};
zh_vector_push_back(&vector, &item1);
zh_vector_push_back(&vector, &item2);
zh_vector_push_back(&vector, &item3);
int search_id = 2;
int32_t found_index = -1;
my_struct_t sample = {0};
ret = zh_vector_find_item_in_field(&vector, &sample, &sample.id, sizeof(sample.id), &search_id, 0, &found_index);
if (ret == ESP_OK)
{
printf("Struct with id=%d found at index %d\n", search_id, (int)found_index);
my_struct_t found_item = {0};
ret = zh_vector_get_item(&vector, (uint16_t)found_index, &found_item);
if (ret == ESP_OK)
{
printf("Found item: id=%d, name=%s, value=%.1f\n", found_item.id, found_item.name, found_item.value);
}
}
else
{
printf("Struct with id=%d not found (index=%d)\n", search_id, (int)found_index);
}
search_id = 100;
found_index = -1;
ret = zh_vector_find_item_in_field(&vector, &sample, &sample.id, sizeof(sample.id), &search_id, 0, &found_index);
if (ret == ESP_OK)
{
printf("Struct with id=%d found at index %d\n", search_id, (int)found_index);
}
else
{
printf("Struct with id=%d not found (index=%d)\n", search_id, (int)found_index);
}
zh_vector_free(&vector);
}
```
-408
View File
@@ -1,408 +0,0 @@
# zh_vector - Vector (Dynamic Array) Component for ESP-IDF
## Table of Contents
- [Overview](#overview)
- [Features](#features)
- [Installation](#installation)
- [API Reference](#api-reference)
- [Usage Examples](#usage-examples)
- [Technical Specifications](#technical-specifications)
- [Error Codes](#error-codes)
- [Contributing](#contributing)
- [License](#license)
---
## Overview
`zh_vector` is a lightweight, efficient vector (dynamic array) component for ESP-IDF (Espressif IoT Development Framework). It provides a flexible container that can store elements of any data type with automatic memory management. The vector automatically resizes as items are added or removed, making it ideal for dynamic data management in embedded systems.
The component is designed specifically for ESP32 microcontrollers and uses ESP-IDF's heap management functions for optimal memory allocation with different memory caps (internal/external RAM).
---
## Features
1. **Type Agnostic**: Supports any data type (integers, floats, structs, custom types, etc.)
2. **Automatic Memory Management**: Automatic memory allocation and deallocation
3. **Dynamic Resizing**: Vector capacity grows and shrinks as needed
4. **Maximum Capacity**: Up to 65,535 elements (16-bit index limit)
5. **ESP-IDF Optimized**: Uses heap_caps functions for memory allocation with memory caps
6. **Error Handling**: Comprehensive error checking with detailed logging
7. **Thread-Safe**: Thread-safe (uses FreeRTOS mutex)
8. **Minimal Overhead**: Low memory and CPU overhead
---
## Installation
1. Navigate to your project's components directory:
```bash
cd ../your_project/components
```
2. Clone the repository:
```bash
git clone https://github.com/aZholtikov/zh_vector
```
3. In your application, include the header:
```c
#include "zh_vector.h"
```
4. The component will be automatically built with your project.
---
## API Reference
### zh_vector_t Structure
```c
typedef struct
{
void **items; // Array of pointers of vector items
uint16_t capacity; // Maximum capacity of the vector
uint16_t size; // Number of items in the vector
uint16_t unit; // Vector item size (in bytes)
bool is_initialized; // Vector initialization status flag
SemaphoreHandle_t mutex; // FreeRTOS mutex for thread safety
} zh_vector_t;
```
---
### zh_vector_init()
Initializes the vector.
**Parameters:**
- `vector` - Pointer to the vector structure
- `unit` - Size of each element in bytes
**Returns:**
- `ESP_OK` - Success
- `ESP_ERR_INVALID_ARG` - Invalid argument (NULL vector or zero unit size)
- `ESP_ERR_INVALID_STATE` - Vector already initialized
**Example:**
```c
zh_vector_t vector = {0};
zh_vector_init(&vector, sizeof(int)); // For integers
```
---
### zh_vector_free()
Deinitializes the vector and frees all allocated memory.
**Parameters:**
- `vector` - Pointer to the vector structure
**Returns:**
- `ESP_OK` - Success
- `ESP_ERR_INVALID_ARG` - Invalid argument (NULL vector)
- `ESP_ERR_INVALID_STATE` - Vector not initialized
**Note:** All dynamically allocated element memory is also freed.
---
### zh_vector_get_size()
Gets the current number of elements in the vector.
**Parameters:**
- `vector` - Pointer to the vector structure
**Returns:**
- `>= 0` - Number of elements (success)
- `ESP_FAIL` - Error (NULL vector or not initialized)
---
### zh_vector_push_front()
Adds an element to the beginning of the vector.
**Parameters:**
- `vector` - Pointer to the vector structure
- `item` - Pointer to the element to add
**Returns:**
- `ESP_OK` - Success
- `ESP_ERR_INVALID_ARG` - Invalid argument (NULL vector or item)
- `ESP_ERR_INVALID_STATE` - Vector not initialized
- `ESP_ERR_NO_MEM` - Memory allocation failed
**Note:** The function allocates memory for a copy of the item and copies the data. All existing elements are shifted right by one position.
---
### zh_vector_push_back()
Adds an element to the end of the vector.
**Parameters:**
- `vector` - Pointer to the vector structure
- `item` - Pointer to the element to add
**Returns:**
- `ESP_OK` - Success
- `ESP_ERR_INVALID_ARG` - Invalid argument (NULL vector or item)
- `ESP_ERR_INVALID_STATE` - Vector not initialized
- `ESP_ERR_NO_MEM` - Memory allocation failed
**Note:** The function allocates memory for a copy of the item and copies the data.
---
### zh_vector_change_item()
Changes an element at a specific index.
**Parameters:**
- `vector` - Pointer to the vector structure
- `index` - Index of the element to change (0-based)
- `item` - Pointer to the new element data
**Returns:**
- `ESP_OK` - Success
- `ESP_ERR_INVALID_ARG` - Invalid argument (NULL vector, item, or invalid index)
- `ESP_ERR_INVALID_STATE` - Vector not initialized
- `ESP_FAIL` - Index out of bounds
---
### zh_vector_get_item()
Gets an element at a specific index.
**Parameters:**
- `vector` - Pointer to the vector structure
- `index` - Index of the element to get (0-based)
**Returns:**
- Pointer to the element (success)
- `NULL` - Error (NULL vector, not initialized, or invalid index)
**Note:** Returns a pointer to the internal data. Do not free this pointer.
---
### zh_vector_delete_item()
Deletes an element at a specific index and shifts all subsequent elements.
**Parameters:**
- `vector` - Pointer to the vector structure
- `index` - Index of the element to delete (0-based)
**Returns:**
- `ESP_OK` - Success
- `ESP_ERR_INVALID_ARG` - Invalid argument (NULL vector)
- `ESP_ERR_INVALID_STATE` - Vector not initialized
- `ESP_FAIL` - Index out of bounds
**Note:** All elements after the deleted index are shifted left by one position.
---
## Usage Examples
### Basic Example: Integer Vector
```c
#include "zh_vector.h"
zh_vector_t int_vector = {0};
void app_main(void)
{
esp_log_level_set("zh_vector", ESP_LOG_ERROR);
// Initialize vector for integers
zh_vector_init(&int_vector, sizeof(int));
// Add elements
int val1 = 10;
int val2 = 20;
int val3 = 30;
zh_vector_push_front(&int_vector, &val1);
zh_vector_push_back(&int_vector, &val2);
zh_vector_push_back(&int_vector, &val3);
printf("Vector size: %d\n", zh_vector_get_size(&int_vector));
// Access elements
for (int i = 0; i < zh_vector_get_size(&int_vector); i++) {
int *item = (int *)zh_vector_get_item(&int_vector, i);
printf("Element %d: %d\n", i, *item);
}
// Change element
int new_val = 100;
zh_vector_change_item(&int_vector, 1, &new_val);
// Delete element
zh_vector_delete_item(&int_vector, 0);
// Cleanup
zh_vector_free(&int_vector);
}
```
### Struct Example
```c
#include "zh_vector.h"
typedef struct {
int id;
char name[32];
float value;
} my_struct_t;
zh_vector_t struct_vector = {0};
void app_main(void)
{
esp_log_level_set("zh_vector", ESP_LOG_ERROR);
// Initialize vector for structs
zh_vector_init(&struct_vector, sizeof(my_struct_t));
// Add struct elements
my_struct_t item1 = {1, "Item 1", 1.5f};
my_struct_t item2 = {2, "Item 2", 2.5f};
zh_vector_push_front(&struct_vector, &item1);
zh_vector_push_back(&struct_vector, &item2);
// Access and modify
my_struct_t *ptr = (my_struct_t *)zh_vector_get_item(&struct_vector, 0);
ptr->value = 10.5f;
// Cleanup
zh_vector_free(&struct_vector);
}
```
### String Example (Char Arrays)
```c
#include "zh_vector.h"
#include "string.h"
zh_vector_t string_vector = {0};
void app_main(void)
{
esp_log_level_set("zh_vector", ESP_LOG_ERROR);
// Initialize vector for strings (100 char max)
char buffer[100] = {0};
zh_vector_init(&string_vector, sizeof(buffer));
// Add strings
strcpy(buffer, "Hello");
zh_vector_push_front(&string_vector, &buffer);
strcpy(buffer, "World");
zh_vector_push_back(&string_vector, &buffer);
// Print all strings
for (int i = 0; i < zh_vector_get_size(&string_vector); i++) {
char *str = (char *)zh_vector_get_item(&string_vector, i);
printf("String %d: %s\n", i, str);
}
// Cleanup
zh_vector_free(&string_vector);
}
```
---
## Technical Specifications
| Parameter | Value |
|-----------|-------|
| **Maximum Capacity** | 65,535 elements |
| **Index Type** | uint16_t (16-bit) |
| **Memory Management** | heap_caps_calloc, heap_caps_realloc, heap_caps_free |
| **Memory Caps** | MALLOC_CAP_8BIT |
| **Thread Safety** | Thread-safe (uses FreeRTOS mutex) |
| **ESP-IDF Version** | >= 5.0 |
| **Platform** | ESP32 series |
| **Language** | C (C99) |
---
## Error Codes
| Error Code | Description |
|------------|-------------|
| `ESP_OK` | Operation successful |
| `ESP_ERR_INVALID_ARG` | Invalid argument (NULL pointer or zero size) |
| `ESP_ERR_INVALID_STATE` | Vector not initialized or already initialized |
| `ESP_ERR_NO_MEM` | Memory allocation failed (out of memory) |
| `ESP_FAIL` | General failure (e.g., index out of bounds) |
---
## Contributing
Contributions are welcome! To contribute:
1. Fork the repository
2. Create a feature branch (`git checkout -b feature/AmazingFeature`)
3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request
Please ensure your code follows the existing style and includes appropriate documentation.
---
## License
This project is licensed under the Apache License, Version 2.0 - see the [LICENSE](LICENSE) file for details.
### Apache License, Version 2.0
Copyright (c) 2026 Alexey Zholtikov
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.
---
## Additional Notes
- **Memory Overhead**: Each element requires additional memory for the pointer in the internal pointer array
- **Performance**: O(1) for get/set by index, O(n) for insert/delete in the middle
- **Best Practices**:
- Always initialize the vector before use
- Free the vector when done to avoid memory leaks
- Consider the maximum size limit (65,535 elements)
- For string handling, consider using fixed-size buffers
---
*Generated for zh_vector v1.3.0*
-408
View File
@@ -1,408 +0,0 @@
# zh_vector - Компонент вектора (динамического массива) для ESP-IDF
## Содержание
- [Обзор](#обзор)
- [Возможности](#возможности)
- [Установка](#установка)
- [Справочник API](#справочник-api)
- [Примеры использования](#примеры-использования)
- [Технические характеристики](#технические-характеристики)
- [Коды ошибок](#коды-ошибок)
- [Вклад в проект](#вклад-в-проект)
- [Лицензия](#лицензия)
---
## Обзор
`zh_vector` — это легковесный и эффективный компонент вектора (динамического массива) для ESP-IDF (Espressif IoT Development Framework). Он предоставляет гибкий контейнер, который может хранить элементы любого типа данных с автоматическим управлением памятью. Вектор автоматически изменяет размер при добавлении или удалении элементов, что делает его идеальным для динамического управления данными во встраиваемых системах.
Компонент разработан специально для микроконтроллеров ESP32 и использует функции управления кучей ESP-IDF для оптимального выделения памяти с различными параметрами памяти (внутренняя/внешняя RAM).
---
## Возможности
1. **Независимость от типа данных**: Поддерживает любой тип данных (целые числа, числа с плавающей точкой, структуры, пользовательские типы и т.д.)
2. **Автоматическое управление памятью**: Автоматическое выделение и освобождение памяти
3. **Динамическое изменение размера**: Емкость вектора увеличивается и уменьшается по мере необходимости
4. **Максимальная емкость**: До 65 535 элементов (ограничение 16-битного индекса)
5. **Оптимизировано под ESP-IDF**: Использует функции heap_caps для выделения памяти с параметрами памяти
6. **Обработка ошибок**: Комплексная проверка ошибок с детальным логированием
7. **Потокобезопасность**: Является потокобезопасным (использует FreeRTOS mutex)
8. **Минимальные накладные расходы**: Низкие накладные расходы на память и процессор
---
## Установка
1. Перейдите в каталог компонентов вашего проекта:
```bash
cd ../ваш_проект/components
```
2. Клонируйте репозиторий:
```bash
git clone https://github.com/aZholtikov/zh_vector
```
3. В вашем приложении подключите заголовочный файл:
```c
#include "zh_vector.h"
```
4. Компонент будет автоматически собран вместе с вашим проектом.
---
## Справочник API
### Структура zh_vector_t
```c
typedef struct
{
void **items; // Массив указателей на элементы вектора
uint16_t capacity; // Максимальная емкость вектора
uint16_t size; // Количество элементов в векторе
uint16_t unit; // Размер элемента вектора (в байтах)
bool is_initialized; // Флаг состояния инициализации вектора
SemaphoreHandle_t mutex; // FreeRTOS mutex для потокобезопасности
} zh_vector_t;
```
---
### zh_vector_init()
Инициализирует вектор.
**Параметры:**
- `vector` - Указатель на структуру вектора
- `unit` - Размер каждого элемента в байтах
**Возвращает:**
- `ESP_OK` - Успех
- `ESP_ERR_INVALID_ARG` - Неверный аргумент (NULL вектор или нулевой размер unit)
- `ESP_ERR_INVALID_STATE` - Вектор уже инициализирован
**Пример:**
```c
zh_vector_t vector = {0};
zh_vector_init(&vector, sizeof(int)); // Для целых чисел
```
---
### zh_vector_free()
Деинициализирует вектор и освобождает всю выделенную память.
**Параметры:**
- `vector` - Указатель на структуру вектора
**Возвращает:**
- `ESP_OK` - Успех
- `ESP_ERR_INVALID_ARG` - Неверный аргумент (NULL вектор)
- `ESP_ERR_INVALID_STATE` - Вектор не инициализирован
**Примечание:** Вся динамически выделенная память элементов также освобождается.
---
### zh_vector_get_size()
Получает текущее количество элементов в векторе.
**Параметры:**
- `vector` - Указатель на структуру вектора
**Возвращает:**
- `>= 0` - Количество элементов (успех)
- `ESP_FAIL` - Ошибка (NULL вектор или не инициализирован)
---
### zh_vector_push_front()
Добавляет элемент в начало вектора.
**Параметры:**
- `vector` - Указатель на структуру вектора
- `item` - Указатель на элемент для добавления
**Возвращает:**
- `ESP_OK` - Успех
- `ESP_ERR_INVALID_ARG` - Неверный аргумент (NULL вектор или item)
- `ESP_ERR_INVALID_STATE` - Вектор не инициализирован
- `ESP_ERR_NO_MEM` - Ошибка выделения памяти
**Примечание:** Функция выделяет память для копии элемента и копирует данные. Все существующие элементы сдвигаются на одну позицию вправо.
---
### zh_vector_push_back()
Добавляет элемент в конец вектора.
**Параметры:**
- `vector` - Указатель на структуру вектора
- `item` - Указатель на элемент для добавления
**Возвращает:**
- `ESP_OK` - Успех
- `ESP_ERR_INVALID_ARG` - Неверный аргумент (NULL вектор или item)
- `ESP_ERR_INVALID_STATE` - Вектор не инициализирован
- `ESP_ERR_NO_MEM` - Ошибка выделения памяти
**Примечание:** Функция выделяет память для копии элемента и копирует данные.
---
### zh_vector_change_item()
Изменяет элемент по определенному индексу.
**Параметры:**
- `vector` - Указатель на структуру вектора
- `index` - Индекс элемента для изменения (начиная с 0)
- `item` - Указатель на новые данные элемента
**Возвращает:**
- `ESP_OK` - Успех
- `ESP_ERR_INVALID_ARG` - Неверный аргумент (NULL вектор, item или неверный индекс)
- `ESP_ERR_INVALID_STATE` - Вектор не инициализирован
- `ESP_FAIL` - Индекс вне границ
---
### zh_vector_get_item()
Получает элемент по определенному индексу.
**Параметры:**
- `vector` - Указатель на структуру вектора
- `index` - Индекс элемента для получения (начиная с 0)
**Возвращает:**
- Указатель на элемент (успех)
- `NULL` - Ошибка (NULL вектор, не инициализирован или неверный индекс)
**Примечание:** Возвращает указатель на внутренние данные. Не освобождайте этот указатель.
---
### zh_vector_delete_item()
Удаляет элемент по определенному индексу и сдвигает все последующие элементы.
**Параметры:**
- `vector` - Указатель на структуру вектора
- `index` - Индекс элемента для удаления (начиная с 0)
**Возвращает:**
- `ESP_OK` - Успех
- `ESP_ERR_INVALID_ARG` - Неверный аргумент (NULL вектор)
- `ESP_ERR_INVALID_STATE` - Вектор не инициализирован
- `ESP_FAIL` - Индекс вне границ
**Примечание:** Все элементы после удаляемого индекса сдвигаются влево на одну позицию.
---
## Примеры использования
### Базовый пример: Вектор целых чисел
```c
#include "zh_vector.h"
zh_vector_t int_vector = {0};
void app_main(void)
{
esp_log_level_set("zh_vector", ESP_LOG_ERROR);
// Инициализация вектора для целых чисел
zh_vector_init(&int_vector, sizeof(int));
// Добавление элементов
int val1 = 10;
int val2 = 20;
int val3 = 30;
zh_vector_push_front(&int_vector, &val1);
zh_vector_push_back(&int_vector, &val2);
zh_vector_push_back(&int_vector, &val3);
printf("Размер вектора: %d\n", zh_vector_get_size(&int_vector));
// Доступ к элементам
for (int i = 0; i < zh_vector_get_size(&int_vector); i++) {
int *item = (int *)zh_vector_get_item(&int_vector, i);
printf("Элемент %d: %d\n", i, *item);
}
// Изменение элемента
int new_val = 100;
zh_vector_change_item(&int_vector, 1, &new_val);
// Удаление элемента
zh_vector_delete_item(&int_vector, 0);
// Очистка
zh_vector_free(&int_vector);
}
```
### Пример со структурой
```c
#include "zh_vector.h"
typedef struct {
int id;
char name[32];
float value;
} my_struct_t;
zh_vector_t struct_vector = {0};
void app_main(void)
{
esp_log_level_set("zh_vector", ESP_LOG_ERROR);
// Инициализация вектора для структур
zh_vector_init(&struct_vector, sizeof(my_struct_t));
// Добавление элементов-структур
my_struct_t item1 = {1, "Item 1", 1.5f};
my_struct_t item2 = {2, "Item 2", 2.5f};
zh_vector_push_front(&struct_vector, &item1);
zh_vector_push_back(&struct_vector, &item2);
// Доступ и модификация
my_struct_t *ptr = (my_struct_t *)zh_vector_get_item(&struct_vector, 0);
ptr->value = 10.5f;
// Очистка
zh_vector_free(&struct_vector);
}
```
### Пример со строками (массивы символов)
```c
#include "zh_vector.h"
#include "string.h"
zh_vector_t string_vector = {0};
void app_main(void)
{
esp_log_level_set("zh_vector", ESP_LOG_ERROR);
// Инициализация вектора для строк (макс. 100 символов)
char buffer[100] = {0};
zh_vector_init(&string_vector, sizeof(buffer));
// Добавление строк
strcpy(buffer, "Привет");
zh_vector_push_front(&string_vector, &buffer);
strcpy(buffer, "Мир");
zh_vector_push_back(&string_vector, &buffer);
// Печать всех строк
for (int i = 0; i < zh_vector_get_size(&string_vector); i++) {
char *str = (char *)zh_vector_get_item(&string_vector, i);
printf("Строка %d: %s\n", i, str);
}
// Очистка
zh_vector_free(&string_vector);
}
```
---
## Технические характеристики
| Параметр | Значение |
|----------|----------|
| **Максимальная емкость** | 65 535 элементов |
| **Тип индекса** | uint16_t (16-бит) |
| **Управление памятью** | heap_caps_calloc, heap_caps_realloc, heap_caps_free |
| **Параметры памяти** | MALLOC_CAP_8BIT |
| **Потокобезопасность** | Является потокобезопасным (использует FreeRTOS mutex) |
| **Версия ESP-IDF** | >= 5.0 |
| **Платформа** | Серия ESP32 |
| **Язык** | C (C99) |
---
## Коды ошибок
| Код ошибки | Описание |
|------------|----------|
| `ESP_OK` | Операция выполнена успешно |
| `ESP_ERR_INVALID_ARG` | Неверный аргумент (NULL указатель или нулевой размер) |
| `ESP_ERR_INVALID_STATE` | Вектор не инициализирован или уже инициализирован |
| `ESP_ERR_NO_MEM` | Ошибка выделения памяти (не хватает памяти) |
| `ESP_FAIL` | Общий сбой (например, индекс вне границ) |
---
## Вклад в проект
Вклад приветствуется! Чтобы внести свой вклад:
1. Сделайте форк репозитория
2. Создайте ветку функции (`git checkout -b feature/AmazingFeature`)
3. Закоммитьте ваши изменения (`git commit -m 'Add some AmazingFeature'`)
4. Отправьте в ветку (`git push origin feature/AmazingFeature`)
5. Откройте Pull Request
Пожалуйста, убедитесь, что ваш код следует существующему стилю и включает соответствующую документацию.
---
## Лицензия
Этот проект лицензирован по лицензии Apache, версия 2.0 - см. файл [LICENSE](LICENSE) для подробной информации.
### Apache License, Version 2.0
Авторское право (c) 2026 Алексей Жолтиков
Лицензировано по лицензии Apache License, Version 2.0 (далее — "Лицензия");
вы не можете использовать этот файл, кроме случаев, предусмотренных Лицензией.
Копию Лицензии можно получить по адресу:
http://www.apache.org/licenses/LICENSE-2.0
Если иное не требуется действующим законодательством или не согласовано в письменном виде,
программное обеспечение, распространяемое по Лицензии, распространяется на условиях "КАК ЕСТЬ",
БЕЗ КАКИХ-ЛИБО ГАРАНТИЙ, явных или подразумеваемых, включая, но не ограничиваясь, гарантии
ТОВАРНОГО СОСТОЯНИЯ, ПРИГОДНОСТИ ДЛЯ КОНКРЕТНОЙ ЦЕЛИ И НЕНАРУШЕНИЯ ПРАВ.
Смотрите Лицензию для получения конкретных прав и ограничений.
---
## Дополнительные заметки
- **Накладные расходы памяти**: Каждый элемент требует дополнительной памяти для указателя во внутреннем массиве указателей
- **Производительность**: O(1) для получения/установки по индексу, O(n) для вставки/удаления в середине
- **Лучшие практики**:
- Всегда инициализируйте вектор перед использованием
- Освобождайте вектор по завершении, чтобы избежать утечек памяти
- Учитывайте ограничение максимального размера (65 535 элементов)
- Для обработки строк рассмотрите использование буферов фиксированного размера
---
*Сгенерировано для zh_vector v1.3.0*
+1 -1
View File
@@ -1,6 +1,6 @@
description: ESP32 ESP-IDF component for vector (dynamic array) description: ESP32 ESP-IDF component for vector (dynamic array)
url: https://github.com/aZholtikov/zh_vector url: https://github.com/aZholtikov/zh_vector
version: "1.3.0" version: "2.5.1"
license: "Apache-2.0" license: "Apache-2.0"
maintainers: maintainers:
- "Alexey Zholtikov <alexey.zholtikov@yandex.ru>" - "Alexey Zholtikov <alexey.zholtikov@yandex.ru>"
+206 -50
View File
@@ -1,10 +1,29 @@
/** /**
* @file zh_vector.h * @file zh_vector.h
*
* @brief Dynamic vector implementation with memory management and thread safety.
*
* This module provides a generic dynamic vector data structure with automatic
* memory management, element insertion/deletion at any position, duplicate
* removal, and item search capabilities. The implementation is thread-safe
* using FreeRTOS mutexes for all public operations.
*
* Key features:
* - Dynamic capacity with automatic growth and shrinkage
* - Thread-safe operations via FreeRTOS mutex
* - Support for arbitrary data types through void pointers
* - Flexible insertion at front or back
* - Duplicate removal and item search functionality
* - Memory allocation with ESP32 heap capabilities
*
* @note All public functions require a valid vector pointer obtained through zh_vector_init().
* @note All operations are protected by internal mutex for thread safety.
*/ */
#pragma once #pragma once
#include "string.h" #include "stdint.h"
#include "stddef.h"
#include "esp_err.h" #include "esp_err.h"
#include "esp_log.h" #include "esp_log.h"
#include "esp_heap_caps.h" #include "esp_heap_caps.h"
@@ -17,96 +36,233 @@ extern "C"
#endif #endif
/** /**
* @brief Main structure of vector data. * @brief Forward declaration of the vector structure.
*
* Opaque handle representing a dynamic vector with internal state
* including items storage, capacity, size, element size, and mutex.
*/ */
typedef struct typedef struct _zh_vector_t zh_vector_t;
{
void **items; /*!< Array of pointers of vector items. */
uint16_t capacity; /*!< Maximum capacity of the vector. @note Used to control the size of allocated memory for array of pointers of vector items. Usually equal to the current number of items in the vector. Automatically changes when items are added or deleted. */
uint16_t size; /*!< Number of items in the vector. */
uint16_t unit; /*!< Vector item size. */
bool is_initialized; /*!< Vector initialization status flag. */
SemaphoreHandle_t mutex; /*!< FreeRTOS mutex. */
} zh_vector_t;
/** /**
* @brief Initialize vector. * @brief Initialize a new vector with specified element size.
* *
* @param[in] vector Pointer to main structure of vector data. * Allocates memory for the vector structure and creates an internal mutex.
* @param[in] unit Size of vector item. * The vector starts with zero capacity and will grow dynamically on first use.
* *
* @return ESP_OK if success or an error code otherwise. * @param[out] vector Pointer to receive the initialized vector handle (must be NULL)
* @param[in] unit Size of each element in bytes (must be > 0)
*
* @return ESP_OK on success
* @return ESP_ERR_INVALID_ARG if vector is NULL or unit is zero
* @return ESP_ERR_INVALID_STATE if vector is already initialized
* @return ESP_ERR_NO_MEM if memory allocation fails
*/ */
esp_err_t zh_vector_init(zh_vector_t *vector, uint16_t unit, ...); esp_err_t zh_vector_init(zh_vector_t **vector, uint16_t unit);
/** /**
* @brief Deinitialize vector. Free all allocated memory. * @brief Free all resources associated with the vector.
* *
* @param[in] vector Pointer to main structure of vector data. * Frees all allocated elements, the items array, the mutex, and the vector
* structure itself. The vector pointer is set to NULL after deletion.
* The vector is marked as deleting and the function waits until all
* operations in progress finish (reference counter drops to zero).
* *
* @return ESP_OK if success or an error code otherwise. * @param[in,out] vector Pointer to the pointer to the vector handle to be freed (must not be NULL)
*
* @return ESP_OK on success
* @return ESP_ERR_INVALID_ARG if vector or *vector is NULL
* @return ESP_ERR_INVALID_STATE if the vector is being deleted, mutex acquisition fails or deletion is already in progress
*/ */
esp_err_t zh_vector_free(zh_vector_t *vector); esp_err_t zh_vector_free(zh_vector_t **vector);
/** /**
* @brief Get current vector size. * @brief Get the current number of elements in the vector.
* *
* @param[in] vector Pointer to main structure of vector data. * @param[in] vector Pointer to the pointer to the vector handle (must not be NULL)
* @param[out] size Pointer to receive the current size (must not be NULL)
* *
* @return Vector size if success or ESP_FAIL otherwise. * @return ESP_OK on success
* @return ESP_ERR_INVALID_ARG if any parameter is NULL
* @return ESP_ERR_INVALID_STATE if the vector is being deleted or mutex acquisition fails
*/ */
esp_err_t zh_vector_get_size(zh_vector_t *vector); esp_err_t zh_vector_get_size(zh_vector_t **vector, uint16_t *size);
/** /**
* @brief Add item at beginning of vector. * @brief Get the current capacity of the vector.
* *
* @param[in] vector Pointer to main structure of vector data. * @param[in] vector Pointer to the pointer to the vector handle (must not be NULL)
* @param[in] item Pointer to item for add. * @param[out] capacity Pointer to receive the current capacity (must not be NULL)
* *
* @return ESP_OK if success or an error code otherwise. * @return ESP_OK on success
* @return ESP_ERR_INVALID_ARG if any parameter is NULL
* @return ESP_ERR_INVALID_STATE if the vector is being deleted or mutex acquisition fails
*/ */
esp_err_t zh_vector_push_front(zh_vector_t *vector, void *item); esp_err_t zh_vector_get_capacity(zh_vector_t **vector, uint16_t *capacity);
/** /**
* @brief Add item at end of vector. * @brief Insert an element at the beginning of the vector.
* *
* @param[in] vector Pointer to main structure of vector data. * Shifts all existing elements one position forward and inserts
* @param[in] item Pointer to item for add. * a copy of the provided item at index 0. The vector capacity
* will be increased if necessary.
* *
* @return ESP_OK if success or an error code otherwise. * @param[in,out] vector Pointer to the pointer to the vector handle (must not be NULL)
* @param[in] item Pointer to the item to insert (must not be NULL)
*
* @return ESP_OK on success
* @return ESP_ERR_INVALID_ARG if any parameter is NULL
* @return ESP_ERR_INVALID_STATE if the vector is being deleted or mutex acquisition fails
* @return ESP_ERR_NO_MEM if vector is full or element allocation fails
*/ */
esp_err_t zh_vector_push_back(zh_vector_t *vector, void *item); esp_err_t zh_vector_push_front(zh_vector_t **vector, const void *item);
/** /**
* @brief Change item by index. * @brief Append an element to the end of the vector.
* *
* @param[in] vector Pointer to main structure of vector data. * Creates a copy of the provided item and adds it to the end of the vector.
* @param[in] index Index of item for change. * The vector capacity will be increased if necessary.
* @param[in] item Pointer to new data of item.
* *
* @return ESP_OK if success or an error code otherwise. * @param[in,out] vector Pointer to the pointer to the vector handle (must not be NULL)
* @param[in] item Pointer to the item to append (must not be NULL)
*
* @return ESP_OK on success
* @return ESP_ERR_INVALID_ARG if any parameter is NULL
* @return ESP_ERR_INVALID_STATE if the vector is being deleted or mutex acquisition fails
* @return ESP_ERR_NO_MEM if vector is full or element allocation fails
*/ */
esp_err_t zh_vector_change_item(zh_vector_t *vector, uint16_t index, void *item); esp_err_t zh_vector_push_back(zh_vector_t **vector, const void *item);
/** /**
* @brief Get item by index. * @brief Replace an element at the specified index.
* *
* @param[in] vector Pointer to main structure of vector data. * Copies the provided item into the existing element at the given index.
* @param[in] index Index of item for get. * The element must already exist and be non-NULL.
* *
* @return Pointer to item or NULL otherwise. * @param[in,out] vector Pointer to the pointer to the vector handle (must not be NULL)
* @param[in] index Index of the element to replace (must be < size)
* @param[in] item Pointer to the new item data (must not be NULL)
*
* @return ESP_OK on success
* @return ESP_ERR_INVALID_ARG if any parameter is NULL or index is out of bounds
* @return ESP_ERR_INVALID_STATE if the vector is being deleted, mutex acquisition fails or the element at index is NULL
*/ */
void *zh_vector_get_item(zh_vector_t *vector, uint16_t index); esp_err_t zh_vector_change_item(zh_vector_t **vector, uint16_t index, const void *item);
/** /**
* @brief Delete item by index and shifts all elements in vector. * @brief Retrieve a copy of the element at the specified index.
* *
* @param[in] vector Pointer to main structure of vector data. * @param[in] vector Pointer to the pointer to the vector handle (must not be NULL)
* @param[in] index Index of item for delete. * @param[in] index Index of the element to retrieve (must be < size)
* @param[out] item Pointer to buffer where the element will be copied (must not be NULL)
* *
* @return ESP_OK if success or an error code otherwise. * @return ESP_OK on success
* @return ESP_ERR_INVALID_ARG if any parameter is NULL or index is out of bounds
* @return ESP_ERR_INVALID_STATE if the vector is being deleted or mutex acquisition fails
*
* @note The element at the specified index must exist and be non-NULL.
* This is guaranteed if the vector was properly initialized and no
* internal corruption occurred.
*/ */
esp_err_t zh_vector_delete_item(zh_vector_t *vector, uint16_t index); esp_err_t zh_vector_get_item(zh_vector_t **vector, uint16_t index, void *item);
/**
* @brief Delete the element at the specified index.
*
* Frees the element's memory, shifts remaining elements, and updates size.
* Capacity may be reduced if it exceeds twice the current size.
*
* @param[in,out] vector Pointer to the pointer to the vector handle (must not be NULL)
* @param[in] index Index of the element to delete (must be < size)
*
* @return ESP_OK on success
* @return ESP_ERR_INVALID_ARG if vector or *vector is NULL or index is out of bounds
* @return ESP_ERR_INVALID_STATE if the vector is being deleted or mutex acquisition fails
*/
esp_err_t zh_vector_delete_item(zh_vector_t **vector, uint16_t index);
/**
* @brief Delete the last element of the vector.
*
* Frees the last element's memory and updates size.
* Capacity may be reduced if it exceeds twice the current size.
*
* @param[in,out] vector Pointer to the pointer to the vector handle (must not be NULL)
*
* @return ESP_OK on success
* @return ESP_ERR_INVALID_ARG if vector or *vector is NULL or vector is empty
* @return ESP_ERR_INVALID_STATE if the vector is being deleted or mutex acquisition fails
*/
esp_err_t zh_vector_delete_back(zh_vector_t **vector);
/**
* @brief Delete the first element of the vector.
*
* Frees the first element's memory, shifts remaining elements, and updates size.
* Capacity may be reduced if it exceeds twice the current size.
*
* @param[in,out] vector Pointer to the pointer to the vector handle (must not be NULL)
*
* @return ESP_OK on success
* @return ESP_ERR_INVALID_ARG if vector or *vector is NULL or vector is empty
* @return ESP_ERR_INVALID_STATE if the vector is being deleted or mutex acquisition fails
*/
esp_err_t zh_vector_delete_front(zh_vector_t **vector);
/**
* @brief Remove duplicate elements from the vector.
*
* Compares elements using memcmp and removes subsequent duplicates.
* Elements are compared based on their raw binary content.
*
* @param[in,out] vector Pointer to the pointer to the vector handle (must not be NULL)
*
* @return ESP_OK on success
* @return ESP_ERR_INVALID_ARG if vector or *vector is NULL
* @return ESP_ERR_INVALID_STATE if the vector is being deleted or mutex acquisition fails
*/
esp_err_t zh_vector_remove_duplicates(zh_vector_t **vector);
/**
* @brief Find the index of the first matching element.
*
* Searches for an element whose binary content matches the provided item
* using memcmp. Returns the index of the first match or -1 if not found.
*
* @param[in] vector Pointer to the pointer to the vector handle (must not be NULL)
* @param[in] item Pointer to the item to search for (must not be NULL)
* @param[out] index Pointer to receive the found index (-1 if not found) (must not be NULL)
*
* @return ESP_OK on success
* @return ESP_ERR_INVALID_ARG if any parameter is NULL
* @return ESP_ERR_INVALID_STATE if the vector is being deleted or mutex acquisition fails
* @return ESP_ERR_NOT_FOUND if item is not found in the vector
*/
esp_err_t zh_vector_find_item(zh_vector_t **vector, const void *item, int32_t *index);
/**
* @brief Find an element by comparing a specific field within structures.
*
* Searches for an element where a specified field (identified by offset
* and size) matches the provided value. The offset is derived from the
* address difference between `item` and `sample_struct` and must lie
* within the element together with the field size. Comparison starts
* from the specified index.
*
* @param[in] vector Pointer to the pointer to the vector handle containing structures (must not be NULL)
* @param[in] sample_struct Pointer to a sample structure (used for field offset calculation) (must not be NULL)
* @param[in] item Pointer to the field within the structure (e.g., `&sample.id`). Used to calculate the field offset (must not be NULL)
* @param[in] size Size of the field in bytes (must be > 0 and the field must fit within the element)
* @param[in] value Pointer to the value to match against the field (must not be NULL)
* @param[in] start Index to begin searching from (must be < size)
* @param[out] index Pointer to receive the found index (-1 if not found) (must not be NULL)
*
* @return ESP_OK on success
* @return ESP_ERR_INVALID_ARG if any parameter is invalid, the field offset with size exceeds the element size,
* or *index is NULL when size is zero
* @return ESP_ERR_INVALID_STATE if the vector is being deleted or mutex acquisition fails
* @return ESP_ERR_NOT_FOUND if no matching element is found
*/
esp_err_t zh_vector_find_item_in_field(zh_vector_t **vector, const void *sample_struct, const void *item, uint16_t size, const void *value, uint16_t start, int32_t *index);
#ifdef __cplusplus #ifdef __cplusplus
} }
+1 -1
View File
@@ -1 +1 @@
1.3.0 2.5.1
+217
View File
@@ -0,0 +1,217 @@
# Описание компонента zh_vector
## Общие сведения
**zh_vector** — это компонент для ESP-IDF (фреймворк для программирования микроконтроллеров ESP32), реализующий динамический вектор (динамический массив) с автоматическим управлением памятью и потокобезопасностью.
Компонент предоставляет универсальную структуру данных «вектор», которая может хранить элементы любого типа через указатели `void`, автоматически увеличивает и уменьшает свою ёмкость, а также обеспечивает потокобезопасную работу с помощью мьютексов FreeRTOS.
## Основные возможности
1. **Универсальность типов** — поддержка любых типов данных через указатели `void`.
2. **Динамическая ёмкость** — автоматическое увеличение и уменьшение выделенной памяти.
3. **Максимальная ёмкость** — до 65 535 элементов (используется 16-битный индекс `uint16_t`).
4. **Потокобезопасность** — все операции защищены мьютексом FreeRTOS.
5. **Автоматическое управление памятью** — используется ESP-IDF функция `heap_caps` для работы с кучей ESP32.
6. **Гибкая вставка** — поддержка вставки элементов как в начало, так и в конец вектора.
7. **Удаление дубликатов и поиск** — возможность удаления дубликатов и поиска элементов по содержимому или по полю внутри структуры.
## Внутреннее устройство
### Структура `zh_vector_t`
Внутренняя структура вектора содержит следующие поля:
| Поле | Тип | Описание |
|------|-----|----------|
| `items` | `void **` | Массив указателей, каждый из которых указывает на отдельно выделенную память для фактических данных элемента |
| `capacity` | `uint16_t` | Текущая выделенная ёмкость массива `items` (максимум 65 535) |
| `size` | `uint16_t` | Текущее количество элементов в векторе |
| `unit` | `uint16_t` | Размер одного элемента в байтах |
| `mutex` | `SemaphoreHandle_t` | Мьютекс FreeRTOS для потокобезопасности |
| `lock` | `portMUX_TYPE` | Секция критической защиты для флагов удаления и счётчика ссылок |
| `deleting` | `bool` | Флаг, указывающий, что вектор удаляется и новые операции должны быть отклонены |
| `refcount` | `uint16_t` | Счётчик операций, находящихся в процессе выполнения |
### Управление памятью
Каждый элемент вектора хранится как **отдельное выделение памяти**. Это означает, что:
- Массив `items` содержит указатели на элементы.
- Каждый элемент выделяется отдельно через `heap_caps_calloc()`.
- При удалении элемента его память освобождается через `heap_caps_free()`.
- При удалении всего вектора последовательно освобождаются все элементы, затем массив `items` и сама структура `zh_vector_t`.
## API (интерфейс)
### Инициализация и освобождение
| Функция | Описание |
|---------|----------|
| `zh_vector_init()` | Инициализирует новый вектор. Принимает указатель на указатель вектора и размер элемента в байтах. Создаёт структуру, выделяет нулевую ёмкость и создаёт мьютекс. |
| `zh_vector_free()` | Освобождает все ресурсы: элементы, массив, мьютекс и структуру. Устанавливает флаг `deleting` и ожидает завершения всех текущих операций (до тех пор, пока `refcount` не станет нулём). |
### Получение информации
| Функция | Описание |
|---------|----------|
| `zh_vector_get_size()` | Возвращает текущее количество элементов в векторе. |
| `zh_vector_get_capacity()` | Возвращает текущую выделенную ёмкость (максимальное количество элементов, для которого выделена память). |
### Вставка элементов
| Функция | Описание |
|---------|----------|
| `zh_vector_push_front()` | Вставляет копию элемента в начало вектора (индекс 0). Все существующие элементы сдвигаются на одну позицию вправо. Если ёмкость исчерпана, массив увеличивается. |
| `zh_vector_push_back()` | Вставляет копию элемента в конец вектора. Если ёмкость исчерпана, массив увеличивается. |
### Доступ и модификация
| Функция | Описание |
|---------|----------|
| `zh_vector_get_item()` | Копирует элемент по указанному индексу в предоставленный буфер. |
| `zh_vector_change_item()` | Заменяет содержимое элемента по указанному индексу новыми данными. |
### Удаление элементов
| Функция | Описание |
|---------|----------|
| `zh_vector_delete_item()` | Удаляет элемент по указанному индексу. Освобождает память элемента, сдвигает оставшиеся элементы влево. Обновляет `size`. |
| `zh_vector_delete_back()` | Удаляет последний элемент вектора. |
| `zh_vector_delete_front()` | Удаляет первый элемент вектора. Сдвигает оставшиеся элементы влево. |
### Поиск и очистка
| Функция | Описание |
|---------|----------|
| `zh_vector_remove_duplicates()` | Удаляет дубликаты элементов. Сравнивает элементы побайтово через `memcmp`. При обнаружении дубликата он удаляется. |
| `zh_vector_find_item()` | Ищет первый элемент, побайтово совпадающий с заданным. Возвращает индекс или `-1`, если элемент не найден. |
| `zh_vector_find_item_in_field()` | Ищет элемент по значению конкретного поля внутри структуры. Позволяет искать по любому полю структуры, вычисляя смещение поля от начала структуры. |
## Потокобезопасность
Все публичные функции работают с вектором через двухуровневую систему синхронизации:
1. **`_zh_vector_take()` / `_zh_vector_give()`** — механизм счётчика ссылок.
- Перед началом любой операции вызывается `_zh_vector_take()`, который увеличивает `refcount` и проверяет, что вектор не удаляется (флаг `deleting` равен `false`).
- После завершения операции вызывается `_zh_vector_give()`, который уменьшает `refcount`.
- Функция `zh_vector_free()` устанавливает `deleting = true` и ожидает, пока `refcount` не станет нулём. Это гарантирует, что все текущие операции завершатся перед освобождением памяти.
2. **Мьютекс FreeRTOS** — защищает внутренние данные вектора (`items`, `capacity`, `size`) от одновременного доступа из разных потоков.
3. **Критическая секция (`portMUX_TYPE`)** — используется для атомарных операций со счётчиком ссылок и флагом удаления (на уровне одного ядра, без блокировки других ядер).
## Алгоритмы изменения ёмкости
### Увеличение ёмкости
- При первой вставке элемента начальная ёмкость устанавливается в **4 элемента**.
- При каждом последующем заполнении ёмкость удваивается (`capacity * 2`).
- Максимальная ёмкость ограничена значением `UINT16_MAX` (65 535).
### Уменьшение ёмкости
- Ёмкость уменьшается при удалении элемента, если:
- `capacity > 4` и `capacity / 2 >= size * 2` (то есть выделенная память больше нужной более чем в 2 раза).
- Новая ёмкость рассчитывается как `size * 2`, но не менее 4.
- При достижении `size == 0` вся память полностью освобождается.
## Примеры использования
### Базовый пример (целые числа)
```c
zh_vector_t *vector = NULL;
zh_vector_init(&vector, sizeof(int));
int val1 = 10, val2 = 20, val3 = 30;
zh_vector_push_back(vector, &val1);
zh_vector_push_back(vector, &val2);
zh_vector_push_back(vector, &val3);
// Получение элемента
int item_value = 0;
zh_vector_get_item(vector, 1, &item_value); // item_value = 20
// Изменение элемента
int new_val = 100;
zh_vector_change_item(vector, 1, &new_val); // элемент по индексу 1 теперь = 100
// Удаление элемента
zh_vector_delete_item(vector, 0); // удалён элемент со значением 10
// Очистка
zh_vector_free(&vector);
```
### Работа со структурами
```c
typedef struct {
int id;
char name[32];
float value;
} my_struct_t;
zh_vector_t *vector = NULL;
zh_vector_init(&vector, sizeof(my_struct_t));
my_struct_t item1 = {1, "Item 1", 1.5f};
zh_vector_push_back(vector, &item1);
// Поиск по полю структуры
int search_id = 1;
int32_t found_index = -1;
my_struct_t sample = {0};
zh_vector_find_item_in_field(vector, &sample, &sample.id, sizeof(sample.id), &search_id, 0, &found_index);
// found_index = 0, так как элемент с id=1 находится по индексу 0
zh_vector_free(&vector);
```
## Логирование
Компонент использует ESP-IDF логирование с тегом `"zh_vector"`. Уровень логирования можно настроить:
```c
esp_log_level_set("zh_vector", ESP_LOG_ERROR); // только ошибки
```
## Ошибки
Все функции возвращают `esp_err_t`. Основные коды ошибок:
| Код | Описание |
|-----|----------|
| `ESP_OK` | Успех |
| `ESP_ERR_INVALID_ARG` | Неверный аргумент (NULL-указатель, некорректный индекс и т.д.) |
| `ESP_ERR_INVALID_STATE` | Неверное состояние (вектор удаляется, мьютекс не получен) |
| `ESP_ERR_NO_MEM` | Не удалось выделить память |
| `ESP_ERR_NOT_FOUND` | Элемент не найден |
## Ограничения
1. **Максимум 65 535 элементов** — из-за использования `uint16_t` для индексов и ёмкости.
2. **Побайтовое сравнение** — `memcmp` сравнивает сырые байты, что может не учитывать выравнивание структур.
3. **Копирование данных** — все операции вставки и получения копируют данные, что может быть неэффективно для очень больших элементов.
4. **Зависимость от ESP-IDF** — компонент работает только в среде ESP-IDF с FreeRTOS.
## Требования для сборки
- ESP-IDF (фреймворк для ESP32)
- FreeRTOS (входит в состав ESP-IDF)
- Компонент должен находиться в директории `components/zh_vector` проекта
## Установка
Для добавления компонента в проект:
```bash
cd ваш_проект/components
git clone https://github.com/aZholtikov/zh_vector
```
Затем в коде подключить заголовочный файл:
```c
#include "zh_vector.h"
```
+422 -108
View File
@@ -13,183 +13,443 @@ static const char *TAG = "zh_vector";
return err; \ return err; \
} }
/**
* @brief Internal structure representing a dynamic vector.
*
* Contains a dynamically allocated array of item pointers, capacity tracking,
* element size, and a FreeRTOS mutex for thread-safe operations.
* Each element in the items array points to separately allocated memory
* containing the actual item data.
*
* @note All public operations acquire the mutex before accessing internal state.
* @warning The items array uses separate allocations for each element to support
* variable-sized data structures stored within the vector.
*/
struct _zh_vector_t
{
void **items; /*!< Array of pointers to individual item allocations */
uint16_t capacity; /*!< Current allocated capacity of the items array */
uint16_t size; /*!< Current number of elements in the vector */
uint16_t unit; /*!< Size of each element in bytes */
SemaphoreHandle_t mutex; /*!< FreeRTOS mutex for thread-safe operations */
portMUX_TYPE lock; /*!< Critical section guard for deleting flag and reference counter */
bool deleting; /*!< Flag indicating the vector is being deleted and new operations must be rejected */
uint16_t refcount; /*!< Number of public operations currently in progress */
};
/**
* @brief Register an in-progress operation on the vector.
*
* Increments the reference counter unless the vector is already being
* deleted. The check and the increment are performed atomically within
* a critical section.
*
* @param vector Pointer to the vector
*
* @return true if the operation is allowed and the reference counter was incremented
* @return false if the vector is being deleted
*/
static bool _zh_vector_take(zh_vector_t *vector);
/**
* @brief Unregister a finished operation on the vector.
*
* Decrements the reference counter within a critical section so that
* a pending deletion can proceed once no operations remain in progress.
*
* @param vector Pointer to the vector
*/
static void _zh_vector_give(zh_vector_t *vector);
/**
* @brief Resize the vector's internal items array.
*
* Allocates a new array with the specified capacity. When capacity is zero,
* all elements and the array itself are freed. When growing, new slots
* are initialized to NULL.
*
* @param vector Pointer to the vector to resize
* @param capacity New capacity for the items array
*
* @return ESP_OK on success
* @return ESP_ERR_INVALID_ARG if capacity is less than current size
* @return ESP_ERR_NO_MEM if memory reallocation fails
*/
static esp_err_t _resize(zh_vector_t *vector, uint16_t capacity); static esp_err_t _resize(zh_vector_t *vector, uint16_t capacity);
esp_err_t zh_vector_init(zh_vector_t *vector, uint16_t unit, ...) /**
* @brief Delete an element at the specified index and shift remaining elements.
*
* Frees the element's memory, shifts elements after the index one position left,
* and updates size. Releases all internal storage when the vector becomes empty.
* Otherwise shrinks capacity to twice the size when capacity exceeds four and
* half the capacity is at least four times the size.
*
* @param vector Pointer to the vector
* @param index Index of the element to delete
*
* @return ESP_OK on success
* @return ESP_ERR_INVALID_ARG if index is out of bounds
*/
static esp_err_t _delete(zh_vector_t *vector, uint16_t index);
/**
* @brief Calculate the new capacity for the vector when growing.
*
* Returns initial capacity of 4 for empty vectors, UINT16_MAX if doubling
* would overflow, or double the current capacity otherwise.
*
* @param current Current capacity value
*
* @return New capacity value (4, UINT16_MAX, or current * 2)
*/
static inline uint16_t _calc_new_capacity(uint16_t current);
esp_err_t zh_vector_init(zh_vector_t **vector, uint16_t unit)
{ {
ZH_LOGI("Vector initialization begin."); ZH_LOGI("Vector initialization begin.");
ZH_ERROR_CHECK(vector != NULL && unit != 0, ESP_ERR_INVALID_ARG, NULL, "Vector initialization failed. Invalid argument."); ZH_ERROR_CHECK(vector != NULL && unit != 0, ESP_ERR_INVALID_ARG, NULL, "Vector initialization failed. Invalid argument.");
ZH_ERROR_CHECK(vector->is_initialized == false, ESP_ERR_INVALID_STATE, NULL, "Vector initialization failed. Vector is already initialized."); ZH_ERROR_CHECK(*vector == NULL, ESP_ERR_INVALID_STATE, NULL, "Vector initialization failed. Vector is already initialized.");
vector->mutex = xSemaphoreCreateMutex(); *vector = heap_caps_calloc(1, sizeof(zh_vector_t), MALLOC_CAP_8BIT);
ZH_ERROR_CHECK(vector->mutex != NULL, ESP_ERR_NO_MEM, NULL, "Vector initialization failed. Failed to create mutex."); ZH_ERROR_CHECK(*vector != NULL, ESP_ERR_NO_MEM, NULL, "Vector initialization failed. Failed to allocate vector structure.");
vector->items = NULL; (*vector)->mutex = xSemaphoreCreateMutex();
vector->capacity = 0; ZH_ERROR_CHECK((*vector)->mutex != NULL, ESP_ERR_NO_MEM, heap_caps_free(*vector); *vector = NULL, "Vector initialization failed. Failed to create mutex.");
vector->size = 0; portMUX_INITIALIZE(&(*vector)->lock);
vector->unit = unit; (*vector)->items = NULL;
vector->is_initialized = true; (*vector)->capacity = 0;
(*vector)->size = 0;
(*vector)->unit = unit;
(*vector)->deleting = false;
(*vector)->refcount = 0;
ZH_LOGI("Vector initialization success."); ZH_LOGI("Vector initialization success.");
return ESP_OK; return ESP_OK;
} }
esp_err_t zh_vector_free(zh_vector_t *vector) esp_err_t zh_vector_free(zh_vector_t **vector)
{ {
ZH_LOGI("Vector deletion begin."); ZH_LOGI("Vector deletion begin.");
ZH_ERROR_CHECK(vector != NULL, ESP_ERR_INVALID_ARG, NULL, "Vector deletion failed. Invalid argument."); ZH_ERROR_CHECK(vector != NULL && *vector != NULL, ESP_ERR_INVALID_ARG, NULL, "Vector deletion failed. Invalid argument.");
ZH_ERROR_CHECK(vector->is_initialized == true, ESP_ERR_INVALID_STATE, NULL, "Vector deletion fail. Vector not initialized."); ZH_ERROR_CHECK(xSemaphoreTake((*vector)->mutex, portMAX_DELAY) == pdTRUE, ESP_ERR_INVALID_STATE, NULL, "Vector deletion failed. Failed to acquire mutex.");
ZH_ERROR_CHECK(xSemaphoreTake(vector->mutex, portMAX_DELAY) == pdTRUE, ESP_FAIL, NULL, "Vector deletion fail. Failed to acquire mutex."); taskENTER_CRITICAL(&(*vector)->lock);
for (uint16_t i = 0; i < vector->size; ++i) ZH_ERROR_CHECK((*vector)->deleting == false, ESP_ERR_INVALID_STATE, taskEXIT_CRITICAL(&(*vector)->lock); xSemaphoreGive((*vector)->mutex), "Vector deletion failed. The vector is being deleted.");
(*vector)->deleting = true;
taskEXIT_CRITICAL(&(*vector)->lock);
xSemaphoreGive((*vector)->mutex);
for (;;)
{ {
if (vector->items[i] != NULL) uint16_t refcount;
taskENTER_CRITICAL(&(*vector)->lock);
refcount = (*vector)->refcount;
taskEXIT_CRITICAL(&(*vector)->lock);
if (refcount == 0)
{ {
heap_caps_free(vector->items[i]); break;
vector->items[i] = NULL; }
vTaskDelay(1);
}
for (uint16_t i = 0; i < (*vector)->size; ++i)
{
if ((*vector)->items[i] != NULL)
{
heap_caps_free((*vector)->items[i]);
(*vector)->items[i] = NULL;
} }
} }
heap_caps_free(vector->items); heap_caps_free((*vector)->items);
vector->items = NULL; (*vector)->items = NULL;
vector->size = 0; (*vector)->size = 0;
vector->capacity = 0; (*vector)->capacity = 0;
vSemaphoreDelete(vector->mutex); vSemaphoreDelete((*vector)->mutex);
vector->mutex = NULL; (*vector)->mutex = NULL;
vector->is_initialized = false; heap_caps_free(*vector);
*vector = NULL;
ZH_LOGI("Vector deletion success."); ZH_LOGI("Vector deletion success.");
return ESP_OK; return ESP_OK;
} }
esp_err_t zh_vector_get_size(zh_vector_t *vector) esp_err_t zh_vector_get_size(zh_vector_t **vector, uint16_t *size)
{ {
ZH_LOGI("Getting vector size begin."); ZH_LOGI("Getting vector size begin.");
ZH_ERROR_CHECK(vector != NULL, ESP_FAIL, NULL, "Getting vector size fail. Invalid argument."); ZH_ERROR_CHECK(vector != NULL && *vector != NULL && size != NULL, ESP_ERR_INVALID_ARG, NULL, "Getting vector size failed. Invalid argument.");
ZH_ERROR_CHECK(vector->is_initialized == true, ESP_FAIL, NULL, "Getting vector size fail. Vector not initialized."); ZH_ERROR_CHECK(_zh_vector_take(*vector) == true, ESP_ERR_INVALID_STATE, NULL, "Getting vector size failed. The vector is being deleted.");
ZH_ERROR_CHECK(xSemaphoreTake(vector->mutex, portMAX_DELAY) == pdTRUE, ESP_FAIL, NULL, "Getting vector size fail. Failed to acquire mutex."); ZH_ERROR_CHECK(xSemaphoreTake((*vector)->mutex, portMAX_DELAY) == pdTRUE, ESP_ERR_INVALID_STATE, _zh_vector_give(*vector), "Getting vector size failed. Failed to acquire mutex.");
size_t size = vector->size; *size = (*vector)->size;
xSemaphoreGive(vector->mutex); xSemaphoreGive((*vector)->mutex);
_zh_vector_give(*vector);
ZH_LOGI("Getting vector size success."); ZH_LOGI("Getting vector size success.");
return (esp_err_t)size; return ESP_OK;
} }
esp_err_t zh_vector_push_front(zh_vector_t *vector, void *item) // -V2008 esp_err_t zh_vector_get_capacity(zh_vector_t **vector, uint16_t *capacity)
{
ZH_LOGI("Getting vector capacity begin.");
ZH_ERROR_CHECK(vector != NULL && *vector != NULL && capacity != NULL, ESP_ERR_INVALID_ARG, NULL, "Getting vector capacity failed. Invalid argument.");
ZH_ERROR_CHECK(_zh_vector_take(*vector) == true, ESP_ERR_INVALID_STATE, NULL, "Getting vector capacity failed. The vector is being deleted.");
ZH_ERROR_CHECK(xSemaphoreTake((*vector)->mutex, portMAX_DELAY) == pdTRUE, ESP_ERR_INVALID_STATE, _zh_vector_give(*vector), "Getting vector capacity failed. Failed to acquire mutex.");
*capacity = (*vector)->capacity;
xSemaphoreGive((*vector)->mutex);
_zh_vector_give(*vector);
ZH_LOGI("Getting vector capacity success.");
return ESP_OK;
}
esp_err_t zh_vector_push_front(zh_vector_t **vector, const void *item)
{ {
ZH_LOGI("Adding item to beginning of vector begin."); ZH_LOGI("Adding item to beginning of vector begin.");
ZH_ERROR_CHECK(vector != NULL && item != NULL, ESP_ERR_INVALID_ARG, NULL, "Adding item to beginning of vector fail. Invalid argument."); ZH_ERROR_CHECK(vector != NULL && *vector != NULL && item != NULL, ESP_ERR_INVALID_ARG, NULL, "Adding item to beginning of vector failed. Invalid argument.");
ZH_ERROR_CHECK(vector->is_initialized == true, ESP_ERR_INVALID_STATE, NULL, "Adding item to beginning of vector fail. Vector not initialized."); ZH_ERROR_CHECK(_zh_vector_take(*vector) == true, ESP_ERR_INVALID_STATE, NULL, "Adding item to beginning of vector failed. The vector is being deleted.");
ZH_ERROR_CHECK(xSemaphoreTake(vector->mutex, portMAX_DELAY) == pdTRUE, ESP_FAIL, NULL, "Adding item to beginning of vector fail. Failed to acquire mutex."); ZH_ERROR_CHECK(xSemaphoreTake((*vector)->mutex, portMAX_DELAY) == pdTRUE, ESP_ERR_INVALID_STATE, _zh_vector_give(*vector), "Adding item to beginning of vector failed. Failed to acquire mutex.");
if (vector->capacity == vector->size) ZH_ERROR_CHECK((*vector)->size < UINT16_MAX, ESP_ERR_NO_MEM, xSemaphoreGive((*vector)->mutex); _zh_vector_give(*vector), "Adding item to beginning of vector failed. Vector is full.");
if ((*vector)->capacity == (*vector)->size)
{ {
ZH_ERROR_CHECK(_resize(vector, vector->capacity + 1) == ESP_OK, ESP_ERR_NO_MEM, xSemaphoreGive(vector->mutex), "Adding item to beginning of vector fail. Memory allocation fail or no free memory in the heap."); uint16_t new_capacity = _calc_new_capacity((*vector)->capacity);
ZH_ERROR_CHECK(new_capacity > (*vector)->capacity, ESP_ERR_NO_MEM, xSemaphoreGive((*vector)->mutex); _zh_vector_give(*vector), "Adding item to beginning of vector failed. Cannot grow beyond current capacity.");
ZH_ERROR_CHECK(_resize(*vector, new_capacity) == ESP_OK, ESP_ERR_NO_MEM, xSemaphoreGive((*vector)->mutex); _zh_vector_give(*vector), "Adding item to beginning of vector failed. Memory reallocation failed.");
} }
for (uint16_t i = vector->size; i > 0; --i) void *new_item = heap_caps_calloc(1, (*vector)->unit, MALLOC_CAP_8BIT);
ZH_ERROR_CHECK(new_item != NULL, ESP_ERR_NO_MEM, xSemaphoreGive((*vector)->mutex); _zh_vector_give(*vector), "Adding item to beginning of vector failed. Element allocation failed.");
for (uint16_t i = (*vector)->size; i > 0; --i)
{ {
vector->items[i] = vector->items[i - 1]; (*vector)->items[i] = (*vector)->items[i - 1];
} }
vector->items[0] = heap_caps_calloc(1, vector->unit, MALLOC_CAP_8BIT); (*vector)->items[0] = new_item;
ZH_ERROR_CHECK(vector->items[0] != NULL, ESP_ERR_NO_MEM, xSemaphoreGive(vector->mutex), "Adding item to beginning of vector fail. Memory allocation fail or no free memory in the heap."); memcpy((*vector)->items[0], item, (*vector)->unit);
memcpy(vector->items[0], item, vector->unit); (*vector)->size++;
vector->size++; xSemaphoreGive((*vector)->mutex);
xSemaphoreGive(vector->mutex); _zh_vector_give(*vector);
ZH_LOGI("Adding item to beginning of vector success."); ZH_LOGI("Adding item to beginning of vector success.");
return ESP_OK; return ESP_OK;
} }
esp_err_t zh_vector_push_back(zh_vector_t *vector, void *item) // -V2008 esp_err_t zh_vector_push_back(zh_vector_t **vector, const void *item)
{ {
ZH_LOGI("Adding item to vector begin."); ZH_LOGI("Adding item to vector begin.");
ZH_ERROR_CHECK(vector != NULL && item != NULL, ESP_ERR_INVALID_ARG, NULL, "Adding item to vector fail. Invalid argument."); ZH_ERROR_CHECK(vector != NULL && *vector != NULL && item != NULL, ESP_ERR_INVALID_ARG, NULL, "Adding item to vector failed. Invalid argument.");
ZH_ERROR_CHECK(vector->is_initialized == true, ESP_ERR_INVALID_STATE, NULL, "Adding item to vector fail. Vector not initialized."); ZH_ERROR_CHECK(_zh_vector_take(*vector) == true, ESP_ERR_INVALID_STATE, NULL, "Adding item to vector failed. The vector is being deleted.");
ZH_ERROR_CHECK(xSemaphoreTake(vector->mutex, portMAX_DELAY) == pdTRUE, ESP_FAIL, NULL, "Adding item to vector fail. Failed to acquire mutex."); ZH_ERROR_CHECK(xSemaphoreTake((*vector)->mutex, portMAX_DELAY) == pdTRUE, ESP_ERR_INVALID_STATE, _zh_vector_give(*vector), "Adding item to vector failed. Failed to acquire mutex.");
if (vector->capacity == vector->size) ZH_ERROR_CHECK((*vector)->size < UINT16_MAX, ESP_ERR_NO_MEM, xSemaphoreGive((*vector)->mutex); _zh_vector_give(*vector), "Adding item to vector failed. Vector is full.");
if ((*vector)->capacity == (*vector)->size)
{ {
ZH_ERROR_CHECK(_resize(vector, vector->capacity + 1) == ESP_OK, ESP_ERR_NO_MEM, xSemaphoreGive(vector->mutex), "Adding item to vector fail. Memory allocation fail or no free memory in the heap."); uint16_t new_capacity = _calc_new_capacity((*vector)->capacity);
ZH_ERROR_CHECK(new_capacity > (*vector)->capacity, ESP_ERR_NO_MEM, xSemaphoreGive((*vector)->mutex); _zh_vector_give(*vector), "Adding item to vector failed. Cannot grow beyond current capacity.");
ZH_ERROR_CHECK(_resize(*vector, new_capacity) == ESP_OK, ESP_ERR_NO_MEM, xSemaphoreGive((*vector)->mutex); _zh_vector_give(*vector), "Adding item to vector failed. Memory reallocation failed.");
} }
uint16_t idx = vector->size; uint16_t idx = (*vector)->size;
vector->items[idx] = heap_caps_calloc(1, vector->unit, MALLOC_CAP_8BIT); (*vector)->items[idx] = heap_caps_calloc(1, (*vector)->unit, MALLOC_CAP_8BIT);
ZH_ERROR_CHECK(vector->items[idx] != NULL, ESP_ERR_NO_MEM, xSemaphoreGive(vector->mutex), "Adding item to vector fail. Memory allocation fail or no free memory in the heap."); ZH_ERROR_CHECK((*vector)->items[idx] != NULL, ESP_ERR_NO_MEM, xSemaphoreGive((*vector)->mutex); _zh_vector_give(*vector), "Adding item to vector failed. Element allocation failed.");
memcpy(vector->items[idx], item, vector->unit); memcpy((*vector)->items[idx], item, (*vector)->unit);
vector->size++; (*vector)->size++;
xSemaphoreGive(vector->mutex); xSemaphoreGive((*vector)->mutex);
_zh_vector_give(*vector);
ZH_LOGI("Adding item to vector success."); ZH_LOGI("Adding item to vector success.");
return ESP_OK; return ESP_OK;
} }
esp_err_t zh_vector_change_item(zh_vector_t *vector, uint16_t index, void *item) // -V2008 esp_err_t zh_vector_change_item(zh_vector_t **vector, uint16_t index, const void *item)
{ {
ZH_LOGI("Changing item in vector begin."); ZH_LOGI("Changing item in vector begin.");
ZH_ERROR_CHECK(vector != NULL && item != NULL, ESP_ERR_INVALID_ARG, NULL, "Changing item in vector fail. Invalid argument."); ZH_ERROR_CHECK(vector != NULL && *vector != NULL && item != NULL, ESP_ERR_INVALID_ARG, NULL, "Changing item in vector failed. Invalid argument.");
ZH_ERROR_CHECK(vector->is_initialized == true, ESP_ERR_INVALID_STATE, NULL, "Changing item in vector fail. Vector not initialized."); ZH_ERROR_CHECK(_zh_vector_take(*vector) == true, ESP_ERR_INVALID_STATE, NULL, "Changing item in vector failed. The vector is being deleted.");
ZH_ERROR_CHECK(xSemaphoreTake(vector->mutex, portMAX_DELAY) == pdTRUE, ESP_FAIL, NULL, "Changing item in vector fail. Failed to acquire mutex."); ZH_ERROR_CHECK(xSemaphoreTake((*vector)->mutex, portMAX_DELAY) == pdTRUE, ESP_ERR_INVALID_STATE, _zh_vector_give(*vector), "Changing item in vector failed. Failed to acquire mutex.");
ZH_ERROR_CHECK(index < vector->size, ESP_FAIL, NULL, "Changing item in vector fail. Index does not exist."); ZH_ERROR_CHECK(index < (*vector)->size, ESP_ERR_INVALID_ARG, xSemaphoreGive((*vector)->mutex); _zh_vector_give(*vector), "Changing item in vector failed. Index out of bounds.");
memcpy(vector->items[index], item, vector->unit); ZH_ERROR_CHECK((*vector)->items[index] != NULL, ESP_ERR_INVALID_STATE, xSemaphoreGive((*vector)->mutex); _zh_vector_give(*vector), "Changing item in vector failed. Item is NULL.");
xSemaphoreGive(vector->mutex); memcpy((*vector)->items[index], item, (*vector)->unit);
xSemaphoreGive((*vector)->mutex);
_zh_vector_give(*vector);
ZH_LOGI("Changing item in vector success."); ZH_LOGI("Changing item in vector success.");
return ESP_OK; return ESP_OK;
} }
void *zh_vector_get_item(zh_vector_t *vector, uint16_t index) // -V2008 esp_err_t zh_vector_get_item(zh_vector_t **vector, uint16_t index, void *item)
{ {
ZH_LOGI("Getting item from vector begin."); ZH_LOGI("Getting item from vector begin.");
if (vector == NULL) ZH_ERROR_CHECK(vector != NULL && *vector != NULL && item != NULL, ESP_ERR_INVALID_ARG, NULL, "Getting item from vector failed. Invalid argument.");
{ ZH_ERROR_CHECK(_zh_vector_take(*vector) == true, ESP_ERR_INVALID_STATE, NULL, "Getting item from vector failed. The vector is being deleted.");
ZH_LOGE("Getting item from vector fail. Invalid argument.", ESP_ERR_INVALID_ARG); ZH_ERROR_CHECK(xSemaphoreTake((*vector)->mutex, portMAX_DELAY) == pdTRUE, ESP_ERR_INVALID_STATE, _zh_vector_give(*vector), "Getting item from vector failed. Failed to acquire mutex.");
return NULL; ZH_ERROR_CHECK(index < (*vector)->size, ESP_ERR_INVALID_ARG, xSemaphoreGive((*vector)->mutex); _zh_vector_give(*vector), "Getting item from vector failed. Index out of bounds.");
} ZH_ERROR_CHECK((*vector)->items[index] != NULL, ESP_ERR_INVALID_STATE, xSemaphoreGive((*vector)->mutex); _zh_vector_give(*vector), "Getting item from vector failed. Item is NULL.");
if (vector->is_initialized == false) memcpy(item, (*vector)->items[index], (*vector)->unit);
{ xSemaphoreGive((*vector)->mutex);
ZH_LOGE("Getting item from vector fail. Vector not initialized.", ESP_ERR_INVALID_STATE); _zh_vector_give(*vector);
return NULL;
}
if (xSemaphoreTake(vector->mutex, portMAX_DELAY) != pdTRUE)
{
ZH_LOGE("Getting item from vector fail. Failed to acquire mutex.", ESP_FAIL);
return NULL;
}
void *item = NULL;
if (index >= vector->size)
{
xSemaphoreGive(vector->mutex);
ZH_LOGE("Getting item from vector fail. Index does not exist.", ESP_FAIL);
return NULL;
}
item = vector->items[index];
xSemaphoreGive(vector->mutex);
ZH_LOGI("Getting item from vector success."); ZH_LOGI("Getting item from vector success.");
return item; return ESP_OK;
} }
esp_err_t zh_vector_delete_item(zh_vector_t *vector, uint16_t index) // -V2008 esp_err_t zh_vector_delete_item(zh_vector_t **vector, uint16_t index)
{ {
ZH_LOGI("Deleting item in vector begin."); ZH_LOGI("Deleting item in vector begin.");
ZH_ERROR_CHECK(vector != NULL, ESP_ERR_INVALID_ARG, NULL, "Deleting item in vector fail. Invalid argument."); ZH_ERROR_CHECK(vector != NULL && *vector != NULL, ESP_ERR_INVALID_ARG, NULL, "Deleting item in vector failed. Invalid argument.");
ZH_ERROR_CHECK(vector->is_initialized == true, ESP_ERR_INVALID_STATE, NULL, "Deleting item in vector fail. Vector not initialized."); ZH_ERROR_CHECK(_zh_vector_take(*vector) == true, ESP_ERR_INVALID_STATE, NULL, "Deleting item in vector failed. The vector is being deleted.");
ZH_ERROR_CHECK(xSemaphoreTake(vector->mutex, portMAX_DELAY) == pdTRUE, ESP_FAIL, NULL, "Deleting item in vector fail. Failed to acquire mutex."); ZH_ERROR_CHECK(xSemaphoreTake((*vector)->mutex, portMAX_DELAY) == pdTRUE, ESP_ERR_INVALID_STATE, _zh_vector_give(*vector), "Deleting item in vector failed. Failed to acquire mutex.");
ZH_ERROR_CHECK(index < vector->size, ESP_FAIL, NULL, "Deleting item in vector fail. Index does not exist."); ZH_ERROR_CHECK(index < (*vector)->size, ESP_ERR_INVALID_ARG, xSemaphoreGive((*vector)->mutex); _zh_vector_give(*vector), "Deleting item in vector failed. Index out of bounds.");
void *freed_item = vector->items[index]; ZH_ERROR_CHECK(_delete(*vector, index) == ESP_OK, ESP_ERR_INVALID_STATE, xSemaphoreGive((*vector)->mutex); _zh_vector_give(*vector), "Deleting item in vector failed. Internal error.");
for (uint16_t i = index; i < (vector->size - 1); ++i) xSemaphoreGive((*vector)->mutex);
{ _zh_vector_give(*vector);
vector->items[i] = vector->items[i + 1];
}
heap_caps_free(freed_item);
vector->items[--vector->size] = NULL;
if (vector->capacity > vector->size)
{
ZH_ERROR_CHECK(_resize(vector, vector->size) == ESP_OK, ESP_ERR_NO_MEM, xSemaphoreGive(vector->mutex), "Deleting item in vector fail. Memory allocation fail or no free memory in the heap.");
}
xSemaphoreGive(vector->mutex);
ZH_LOGI("Deleting item in vector success."); ZH_LOGI("Deleting item in vector success.");
return ESP_OK; return ESP_OK;
} }
esp_err_t zh_vector_delete_back(zh_vector_t **vector)
{
ZH_LOGI("Deleting item in back begin.");
ZH_ERROR_CHECK(vector != NULL && *vector != NULL, ESP_ERR_INVALID_ARG, NULL, "Deleting item in back failed. Invalid argument.");
ZH_ERROR_CHECK(_zh_vector_take(*vector) == true, ESP_ERR_INVALID_STATE, NULL, "Deleting item in back failed. The vector is being deleted.");
ZH_ERROR_CHECK(xSemaphoreTake((*vector)->mutex, portMAX_DELAY) == pdTRUE, ESP_ERR_INVALID_STATE, _zh_vector_give(*vector), "Deleting item in back failed. Failed to acquire mutex.");
ZH_ERROR_CHECK((*vector)->size > 0, ESP_ERR_INVALID_ARG, xSemaphoreGive((*vector)->mutex); _zh_vector_give(*vector), "Deleting item in back failed. Vector is empty.");
ZH_ERROR_CHECK(_delete(*vector, (*vector)->size - 1) == ESP_OK, ESP_ERR_INVALID_STATE, xSemaphoreGive((*vector)->mutex); _zh_vector_give(*vector), "Deleting item in back failed. Internal error.");
xSemaphoreGive((*vector)->mutex);
_zh_vector_give(*vector);
ZH_LOGI("Deleting item in back success.");
return ESP_OK;
}
esp_err_t zh_vector_delete_front(zh_vector_t **vector)
{
ZH_LOGI("Deleting item in front begin.");
ZH_ERROR_CHECK(vector != NULL && *vector != NULL, ESP_ERR_INVALID_ARG, NULL, "Deleting item in front failed. Invalid argument.");
ZH_ERROR_CHECK(_zh_vector_take(*vector) == true, ESP_ERR_INVALID_STATE, NULL, "Deleting item in front failed. The vector is being deleted.");
ZH_ERROR_CHECK(xSemaphoreTake((*vector)->mutex, portMAX_DELAY) == pdTRUE, ESP_ERR_INVALID_STATE, _zh_vector_give(*vector), "Deleting item in front failed. Failed to acquire mutex.");
ZH_ERROR_CHECK((*vector)->size > 0, ESP_ERR_INVALID_ARG, xSemaphoreGive((*vector)->mutex); _zh_vector_give(*vector), "Deleting item in front failed. Vector is empty.");
ZH_ERROR_CHECK(_delete(*vector, 0) == ESP_OK, ESP_ERR_INVALID_STATE, xSemaphoreGive((*vector)->mutex); _zh_vector_give(*vector), "Deleting item in front failed. Internal error.");
xSemaphoreGive((*vector)->mutex);
_zh_vector_give(*vector);
ZH_LOGI("Deleting item in front success.");
return ESP_OK;
}
esp_err_t zh_vector_remove_duplicates(zh_vector_t **vector)
{
ZH_LOGI("Removing duplicates from vector begin.");
ZH_ERROR_CHECK(vector != NULL && *vector != NULL, ESP_ERR_INVALID_ARG, NULL, "Removing duplicates from vector failed. Invalid argument.");
ZH_ERROR_CHECK(_zh_vector_take(*vector) == true, ESP_ERR_INVALID_STATE, NULL, "Removing duplicates from vector failed. The vector is being deleted.");
ZH_ERROR_CHECK(xSemaphoreTake((*vector)->mutex, portMAX_DELAY) == pdTRUE, ESP_ERR_INVALID_STATE, _zh_vector_give(*vector), "Removing duplicates from vector failed. Failed to acquire mutex.");
ZH_ERROR_CHECK((*vector)->size > 0, ESP_ERR_INVALID_ARG, xSemaphoreGive((*vector)->mutex); _zh_vector_give(*vector), "Removing duplicates from vector failed. Vector is empty.");
for (uint16_t i = 0; i < (*vector)->size; ++i)
{
if ((*vector)->items[i] == NULL)
{
continue;
}
uint16_t j = i + 1;
while (j < (*vector)->size)
{
if ((*vector)->items[j] == NULL)
{
++j;
continue;
}
if (memcmp((*vector)->items[i], (*vector)->items[j], (*vector)->unit) == 0)
{
ZH_ERROR_CHECK(_delete(*vector, j) == ESP_OK, ESP_ERR_INVALID_STATE, xSemaphoreGive((*vector)->mutex); _zh_vector_give(*vector), "Removing duplicates from vector failed. Internal error.");
}
else
{
++j;
}
}
}
xSemaphoreGive((*vector)->mutex);
_zh_vector_give(*vector);
ZH_LOGI("Removing duplicates from vector success.");
return ESP_OK;
}
esp_err_t zh_vector_find_item(zh_vector_t **vector, const void *item, int32_t *index)
{
ZH_LOGI("Finding item in vector begin.");
ZH_ERROR_CHECK(vector != NULL && *vector != NULL && item != NULL && index != NULL, ESP_ERR_INVALID_ARG, NULL, "Finding item in vector failed. Invalid argument.");
ZH_ERROR_CHECK(_zh_vector_take(*vector) == true, ESP_ERR_INVALID_STATE, NULL, "Finding item in vector failed. The vector is being deleted.");
ZH_ERROR_CHECK(xSemaphoreTake((*vector)->mutex, portMAX_DELAY) == pdTRUE, ESP_ERR_INVALID_STATE, _zh_vector_give(*vector), "Finding item in vector failed. Failed to acquire mutex.");
*index = -1;
for (uint16_t i = 0; i < (*vector)->size; ++i)
{
if ((*vector)->items[i] == NULL)
{
continue;
}
if (memcmp((*vector)->items[i], item, (*vector)->unit) == 0)
{
*index = (int32_t)i;
xSemaphoreGive((*vector)->mutex);
_zh_vector_give(*vector);
ZH_LOGI("Finding item in vector success (found).");
return ESP_OK;
}
}
xSemaphoreGive((*vector)->mutex);
_zh_vector_give(*vector);
ZH_LOGI("Finding item in vector success (not found).");
return ESP_ERR_NOT_FOUND;
}
esp_err_t zh_vector_find_item_in_field(zh_vector_t **vector, const void *sample_struct, const void *item, uint16_t size, const void *value, uint16_t start, int32_t *index)
{
ZH_LOGI("Finding field in structure begin.");
ZH_ERROR_CHECK(vector != NULL && *vector != NULL && sample_struct != NULL && item != NULL && value != NULL && index != NULL, ESP_ERR_INVALID_ARG, NULL, "Finding field in structure failed. Invalid argument.");
ZH_ERROR_CHECK(size > 0, ESP_ERR_INVALID_ARG, *index = -1, "Finding field in structure failed. Invalid argument.");
ZH_ERROR_CHECK(_zh_vector_take(*vector) == true, ESP_ERR_INVALID_STATE, NULL, "Finding field in structure failed. The vector is being deleted.");
ZH_ERROR_CHECK(xSemaphoreTake((*vector)->mutex, portMAX_DELAY) == pdTRUE, ESP_ERR_INVALID_STATE, _zh_vector_give(*vector), "Finding field in structure failed. Mutex acquire failed.");
ZH_ERROR_CHECK(start < (*vector)->size, ESP_ERR_INVALID_ARG, xSemaphoreGive((*vector)->mutex); _zh_vector_give(*vector), "Finding field in structure failed. Start index out of bounds.");
ZH_ERROR_CHECK((uint32_t)item >= (uint32_t)sample_struct, ESP_ERR_INVALID_ARG, xSemaphoreGive((*vector)->mutex); _zh_vector_give(*vector), "Finding field in structure failed. Field pointer is before sample struct.");
uint32_t offset = (uint32_t)item - (uint32_t)sample_struct;
ZH_ERROR_CHECK(offset < (*vector)->unit, ESP_ERR_INVALID_ARG, xSemaphoreGive((*vector)->mutex); _zh_vector_give(*vector), "Finding field in structure failed. Field offset exceeds element size.");
ZH_ERROR_CHECK((offset + size) <= (*vector)->unit, ESP_ERR_INVALID_ARG, xSemaphoreGive((*vector)->mutex); _zh_vector_give(*vector), "Finding field in structure failed. Field exceeds element size.");
*index = -1;
for (uint16_t i = start; i < (*vector)->size; ++i)
{
if ((*vector)->items[i] == NULL)
{
continue;
}
if (memcmp((const uint8_t *)(*vector)->items[i] + offset, value, size) == 0)
{
*index = (int32_t)i;
xSemaphoreGive((*vector)->mutex);
_zh_vector_give(*vector);
ZH_LOGI("Finding field in structure success (found).");
return ESP_OK;
}
}
xSemaphoreGive((*vector)->mutex);
_zh_vector_give(*vector);
ZH_LOGI("Finding field in structure success (not found).");
return ESP_ERR_NOT_FOUND;
}
static bool _zh_vector_take(zh_vector_t *vector)
{
taskENTER_CRITICAL(&vector->lock);
if (vector->deleting == true)
{
taskEXIT_CRITICAL(&vector->lock);
return false;
}
++vector->refcount;
taskEXIT_CRITICAL(&vector->lock);
return true;
}
static void _zh_vector_give(zh_vector_t *vector)
{
taskENTER_CRITICAL(&vector->lock);
--vector->refcount;
taskEXIT_CRITICAL(&vector->lock);
}
static esp_err_t _resize(zh_vector_t *vector, uint16_t capacity) static esp_err_t _resize(zh_vector_t *vector, uint16_t capacity)
{ {
ZH_ERROR_CHECK(capacity >= vector->size, ESP_ERR_INVALID_ARG, NULL, "Invalid argument.");
if (capacity == 0) if (capacity == 0)
{ {
heap_caps_free(vector->items); heap_caps_free(vector->items);
vector->items = NULL; vector->items = NULL;
vector->size = 0;
vector->capacity = 0; vector->capacity = 0;
return ESP_OK; return ESP_OK;
} }
uint16_t old_capacity = vector->capacity;
void *new_items = heap_caps_realloc(vector->items, sizeof(void *) * capacity, MALLOC_CAP_8BIT); void *new_items = heap_caps_realloc(vector->items, sizeof(void *) * capacity, MALLOC_CAP_8BIT);
ZH_ERROR_CHECK(new_items != NULL, ESP_ERR_NO_MEM, NULL, "Memory allocation fail or no free memory in the heap."); ZH_ERROR_CHECK(new_items != NULL, ESP_ERR_NO_MEM, NULL, "Memory reallocation failed.");
uint16_t old_capacity = vector->capacity;
vector->items = new_items; vector->items = new_items;
if (capacity > old_capacity) if (capacity > old_capacity)
{ {
@@ -198,3 +458,57 @@ static esp_err_t _resize(zh_vector_t *vector, uint16_t capacity)
vector->capacity = capacity; vector->capacity = capacity;
return ESP_OK; return ESP_OK;
} }
static esp_err_t _delete(zh_vector_t *vector, uint16_t index)
{
ZH_ERROR_CHECK(index < vector->size, ESP_ERR_INVALID_ARG, NULL, "Invalid argument.");
void *freed_item = vector->items[index];
uint16_t last_idx = vector->size - 1;
if (index != last_idx)
{
for (uint16_t i = index; i < last_idx; ++i)
{
vector->items[i] = vector->items[i + 1];
}
}
vector->items[last_idx] = NULL;
heap_caps_free(freed_item);
freed_item = NULL;
--vector->size;
if (vector->size == 0)
{
if (vector->capacity > 0)
{
_resize(vector, 0);
}
}
else if (vector->capacity > 4 && vector->capacity / 2 >= vector->size * 2)
{
uint16_t target = (vector->size > UINT16_MAX / 2) ? vector->capacity : vector->size * 2;
if (target < 4)
{
target = 4;
}
if (target < vector->capacity)
{
_resize(vector, target);
}
}
return ESP_OK;
}
static inline uint16_t _calc_new_capacity(uint16_t current)
{
if (current == 0)
{
return 4;
}
else if (current > UINT16_MAX / 2)
{
return UINT16_MAX;
}
else
{
return current * 2;
}
}