Compare commits
11
Commits
main
...
b61ea6f80b
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b61ea6f80b | ||
|
|
847cccc34e | ||
|
|
c0267639e5 | ||
|
|
0b800218f2 | ||
|
|
684b38e52d | ||
|
|
da07ed2114 | ||
|
|
5fecd800e6 | ||
|
|
f83572e0e8 | ||
|
|
6263d23d65 | ||
|
|
e4a842508a | ||
|
|
c76486fa82 |
No files matched your search
@@ -15,7 +15,9 @@
|
|||||||
## Features
|
## Features
|
||||||
|
|
||||||
1. Support of any data types.
|
1. Support of any data types.
|
||||||
2. The maximum size of the veсtor is 65535 elements.
|
2. The maximum size of the vector is 65535 elements.
|
||||||
|
3. Thread-safe implementation using FreeRTOS mutex.
|
||||||
|
4. Automatic memory management with heap_caps functions.
|
||||||
|
|
||||||
## Using
|
## Using
|
||||||
|
|
||||||
|
|||||||
+388
-97
@@ -24,56 +24,58 @@ The component is designed specifically for ESP32 microcontrollers and uses ESP-I
|
|||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
1. **Type Agnostic**: Supports any data type (integers, floats, structs, custom types, etc.)
|
- **Type Agnostic**: Supports any data type (integers, floats, structs, custom types, etc.)
|
||||||
2. **Automatic Memory Management**: Automatic memory allocation and deallocation
|
- **Automatic Memory Management**: Automatic memory allocation and deallocation
|
||||||
3. **Dynamic Resizing**: Vector capacity grows and shrinks as needed
|
- **Dynamic Resizing**: Vector capacity grows and shrinks as needed
|
||||||
4. **Maximum Capacity**: Up to 65,535 elements (16-bit index limit)
|
- **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
|
- **ESP-IDF Optimized**: Uses heap_caps functions for memory allocation with memory caps
|
||||||
6. **Error Handling**: Comprehensive error checking with detailed logging
|
- **Error Handling**: Comprehensive error checking with detailed logging
|
||||||
7. **Thread-Safe**: Thread-safe (uses FreeRTOS mutex)
|
- **Thread-Safe**: Thread-safe (uses FreeRTOS mutex)
|
||||||
8. **Minimal Overhead**: Low memory and CPU overhead
|
- **Minimal Overhead**: Low memory and CPU overhead
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
1. Navigate to your project's components directory:
|
Navigate to your project's components directory:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd ../your_project/components
|
cd ../your_project/components
|
||||||
```
|
```
|
||||||
|
|
||||||
2. Clone the repository:
|
Clone the repository:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone https://github.com/aZholtikov/zh_vector
|
git clone https://github.com/aZholtikov/zh_vector
|
||||||
```
|
```
|
||||||
|
|
||||||
3. In your application, include the header:
|
In your application, include the header:
|
||||||
|
|
||||||
```c
|
```c
|
||||||
#include "zh_vector.h"
|
#include "zh_vector.h"
|
||||||
```
|
```
|
||||||
|
|
||||||
4. The component will be automatically built with your project.
|
The component will be automatically built with your project.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## API Reference
|
## API Reference
|
||||||
|
|
||||||
|
All functions in this library use double pointer (`zh_vector_t **`) for the vector parameter to allow for proper memory management and thread-safe operations.
|
||||||
|
|
||||||
### zh_vector_t Structure
|
### zh_vector_t Structure
|
||||||
|
|
||||||
```c
|
The structure is declared as `typedef struct _zh_vector_t zh_vector_t;` and encapsulates internal implementation details.
|
||||||
typedef struct
|
|
||||||
{
|
**Fields (internal):**
|
||||||
void **items; // Array of pointers of vector items
|
|
||||||
uint16_t capacity; // Maximum capacity of the vector
|
| Field | Type | Description |
|
||||||
uint16_t size; // Number of items in the vector
|
|-------|------|-------------|
|
||||||
uint16_t unit; // Vector item size (in bytes)
|
| `items` | `void **` | Array of element pointers. Items[0..size-1] are valid. Allocated via heap_caps_calloc, reallocated via heap_caps_realloc. |
|
||||||
bool is_initialized; // Vector initialization status flag
|
| `capacity` | `uint16_t` | Current allocated capacity (number of slots). Grows on insertion - may exceed size after deletions. |
|
||||||
SemaphoreHandle_t mutex; // FreeRTOS mutex for thread safety
|
| `size` | `uint16_t` | Current number of elements (0 ≤ size ≤ capacity). |
|
||||||
} zh_vector_t;
|
| `unit` | `uint16_t` | Size (in bytes) of a single element. Set once in zh_vector_init() and immutable. |
|
||||||
```
|
| `mutex` | `SemaphoreHandle_t` | FreeRTOS mutex. Created in zh_vector_init(), deleted in zh_vector_free. Automatically locked/unlocked in public functions. |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -83,39 +85,63 @@ Initializes the vector.
|
|||||||
|
|
||||||
**Parameters:**
|
**Parameters:**
|
||||||
|
|
||||||
- `vector` - Pointer to the vector structure
|
- `vector` - Pointer to pointer to vector structure (`zh_vector_t **`). If the vector pointer is NULL, memory will be allocated.
|
||||||
- `unit` - Size of each element in bytes
|
- `unit` - Size of each element in bytes
|
||||||
|
|
||||||
**Returns:**
|
**Returns:**
|
||||||
|
|
||||||
- `ESP_OK` - Success
|
- `ESP_OK` - Success
|
||||||
- `ESP_ERR_INVALID_ARG` - Invalid argument (NULL vector or zero unit size)
|
- `ESP_ERR_INVALID_ARG` - Invalid argument (NULL vector pointer or zero unit size)
|
||||||
- `ESP_ERR_INVALID_STATE` - Vector already initialized
|
- `ESP_ERR_INVALID_STATE` - Vector already initialized
|
||||||
|
- `ESP_ERR_NO_MEM` - Memory allocation failed
|
||||||
|
|
||||||
**Example:**
|
**Example:**
|
||||||
|
|
||||||
```c
|
```c
|
||||||
zh_vector_t vector = {0};
|
zh_vector_t *vector = NULL;
|
||||||
zh_vector_init(&vector, sizeof(int)); // For integers
|
esp_err_t ret = zh_vector_init(&vector, sizeof(int)); // For integers
|
||||||
|
if (ret != ESP_OK) {
|
||||||
|
// Handle error
|
||||||
|
}
|
||||||
|
// Don't forget to free: zh_vector_free(&vector);
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### zh_vector_free()
|
### zh_vector_free()
|
||||||
|
|
||||||
Deinitializes the vector and frees all allocated memory.
|
Deinitializes the vector and frees all allocated memory. Sets the vector pointer to NULL.
|
||||||
|
|
||||||
**Parameters:**
|
**Parameters:**
|
||||||
|
|
||||||
- `vector` - Pointer to the vector structure
|
- `vector` - Pointer to pointer to vector structure (`zh_vector_t **`). Must not be NULL.
|
||||||
|
|
||||||
**Returns:**
|
**Returns:**
|
||||||
|
|
||||||
- `ESP_OK` - Success
|
- `ESP_OK` - Success
|
||||||
- `ESP_ERR_INVALID_ARG` - Invalid argument (NULL vector)
|
- `ESP_ERR_INVALID_ARG` - Invalid argument (NULL vector pointer or NULL vector)
|
||||||
- `ESP_ERR_INVALID_STATE` - Vector not initialized
|
- `ESP_ERR_INVALID_STATE` - Failed to acquire mutex (rare system error)
|
||||||
|
|
||||||
**Note:** All dynamically allocated element memory is also freed.
|
**Note:** All dynamically allocated element memory is also freed. The vector pointer is set to NULL after deinitialization.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### zh_vector_get_capacity()
|
||||||
|
|
||||||
|
Gets the current allocated capacity of the vector (maximum number of elements without reallocation).
|
||||||
|
|
||||||
|
**Parameters:**
|
||||||
|
|
||||||
|
- `vector` - Pointer to pointer to vector structure (`zh_vector_t **`). Must not be NULL.
|
||||||
|
- `capacity` - Pointer to variable to store the capacity. Must not be NULL.
|
||||||
|
|
||||||
|
**Returns:**
|
||||||
|
|
||||||
|
- `ESP_OK` - Success
|
||||||
|
- `ESP_ERR_INVALID_ARG` - Invalid argument (NULL vector pointer or capacity pointer)
|
||||||
|
- `ESP_ERR_INVALID_STATE` - Failed to acquire mutex (rare system error)
|
||||||
|
|
||||||
|
**Note:** Capacity may be larger than the current size (e.g., after deletions), and is reduced lazily when size < capacity/2 (or when size becomes 0).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -125,12 +151,14 @@ Gets the current number of elements in the vector.
|
|||||||
|
|
||||||
**Parameters:**
|
**Parameters:**
|
||||||
|
|
||||||
- `vector` - Pointer to the vector structure
|
- `vector` - Pointer to pointer to vector structure (`zh_vector_t **`). Must not be NULL.
|
||||||
|
- `size` - Pointer to variable to store the size. Must not be NULL.
|
||||||
|
|
||||||
**Returns:**
|
**Returns:**
|
||||||
|
|
||||||
- `>= 0` - Number of elements (success)
|
- `ESP_OK` - Success
|
||||||
- `ESP_FAIL` - Error (NULL vector or not initialized)
|
- `ESP_ERR_INVALID_ARG` - Invalid argument (NULL vector pointer or size pointer)
|
||||||
|
- `ESP_ERR_INVALID_STATE` - Failed to acquire mutex (rare system error)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -140,15 +168,15 @@ Adds an element to the beginning of the vector.
|
|||||||
|
|
||||||
**Parameters:**
|
**Parameters:**
|
||||||
|
|
||||||
- `vector` - Pointer to the vector structure
|
- `vector` - Pointer to pointer to vector structure (`zh_vector_t **`). Must not be NULL.
|
||||||
- `item` - Pointer to the element to add
|
- `item` - Pointer to the element to add. Must not be NULL.
|
||||||
|
|
||||||
**Returns:**
|
**Returns:**
|
||||||
|
|
||||||
- `ESP_OK` - Success
|
- `ESP_OK` - Success
|
||||||
- `ESP_ERR_INVALID_ARG` - Invalid argument (NULL vector or item)
|
- `ESP_ERR_INVALID_ARG` - Invalid argument (NULL vector pointer or item pointer)
|
||||||
- `ESP_ERR_INVALID_STATE` - Vector not initialized
|
|
||||||
- `ESP_ERR_NO_MEM` - Memory allocation failed
|
- `ESP_ERR_NO_MEM` - Memory allocation failed
|
||||||
|
- `ESP_ERR_INVALID_STATE` - Failed to acquire mutex (rare system error)
|
||||||
|
|
||||||
**Note:** The function allocates memory for a copy of the item and copies the data. All existing elements are shifted right by one position.
|
**Note:** The function allocates memory for a copy of the item and copies the data. All existing elements are shifted right by one position.
|
||||||
|
|
||||||
@@ -160,15 +188,15 @@ Adds an element to the end of the vector.
|
|||||||
|
|
||||||
**Parameters:**
|
**Parameters:**
|
||||||
|
|
||||||
- `vector` - Pointer to the vector structure
|
- `vector` - Pointer to pointer to vector structure (`zh_vector_t **`). Must not be NULL.
|
||||||
- `item` - Pointer to the element to add
|
- `item` - Pointer to the element to add. Must not be NULL.
|
||||||
|
|
||||||
**Returns:**
|
**Returns:**
|
||||||
|
|
||||||
- `ESP_OK` - Success
|
- `ESP_OK` - Success
|
||||||
- `ESP_ERR_INVALID_ARG` - Invalid argument (NULL vector or item)
|
- `ESP_ERR_INVALID_ARG` - Invalid argument (NULL vector pointer or item pointer)
|
||||||
- `ESP_ERR_INVALID_STATE` - Vector not initialized
|
|
||||||
- `ESP_ERR_NO_MEM` - Memory allocation failed
|
- `ESP_ERR_NO_MEM` - Memory allocation failed
|
||||||
|
- `ESP_ERR_INVALID_STATE` - Failed to acquire mutex (rare system error)
|
||||||
|
|
||||||
**Note:** The function allocates memory for a copy of the item and copies the data.
|
**Note:** The function allocates memory for a copy of the item and copies the data.
|
||||||
|
|
||||||
@@ -180,34 +208,35 @@ Changes an element at a specific index.
|
|||||||
|
|
||||||
**Parameters:**
|
**Parameters:**
|
||||||
|
|
||||||
- `vector` - Pointer to the vector structure
|
- `vector` - Pointer to pointer to vector structure (`zh_vector_t **`). Must not be NULL.
|
||||||
- `index` - Index of the element to change (0-based)
|
- `index` - Index of the element to change (0-based). Must be < vector size.
|
||||||
- `item` - Pointer to the new element data
|
- `item` - Pointer to the new element data. Must not be NULL.
|
||||||
|
|
||||||
**Returns:**
|
**Returns:**
|
||||||
|
|
||||||
- `ESP_OK` - Success
|
- `ESP_OK` - Success
|
||||||
- `ESP_ERR_INVALID_ARG` - Invalid argument (NULL vector, item, or invalid index)
|
- `ESP_ERR_INVALID_ARG` - Invalid argument (NULL vector pointer, item pointer, or invalid index)
|
||||||
- `ESP_ERR_INVALID_STATE` - Vector not initialized
|
- `ESP_ERR_INVALID_STATE` - Failed to acquire mutex (rare system error)
|
||||||
- `ESP_FAIL` - Index out of bounds
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### zh_vector_get_item()
|
### zh_vector_get_item()
|
||||||
|
|
||||||
Gets an element at a specific index.
|
Retrieves an element at a specific index by copying it into the user-provided buffer.
|
||||||
|
|
||||||
**Parameters:**
|
**Parameters:**
|
||||||
|
|
||||||
- `vector` - Pointer to the vector structure
|
- `vector` - Pointer to pointer to vector structure (`zh_vector_t **`). Must not be NULL.
|
||||||
- `index` - Index of the element to get (0-based)
|
- `index` - Index of the element to get (0-based).
|
||||||
|
- `item` - Pointer to a buffer of at least `unit` bytes where the element will be copied. Must not be NULL.
|
||||||
|
|
||||||
**Returns:**
|
**Returns:**
|
||||||
|
|
||||||
- Pointer to the element (success)
|
- `ESP_OK` - Success
|
||||||
- `NULL` - Error (NULL vector, not initialized, or invalid index)
|
- `ESP_ERR_INVALID_ARG` - Invalid argument (NULL vector pointer, NULL item pointer, or invalid index)
|
||||||
|
- `ESP_ERR_INVALID_STATE` - Failed to acquire mutex (rare system error)
|
||||||
|
|
||||||
**Note:** Returns a pointer to the internal data. Do not free this pointer.
|
**Note:** This function copies the element data into the provided buffer. No pointers are returned.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -217,17 +246,81 @@ Deletes an element at a specific index and shifts all subsequent elements.
|
|||||||
|
|
||||||
**Parameters:**
|
**Parameters:**
|
||||||
|
|
||||||
- `vector` - Pointer to the vector structure
|
- `vector` - Pointer to pointer to vector structure (`zh_vector_t **`). Must not be NULL.
|
||||||
- `index` - Index of the element to delete (0-based)
|
- `index` - Index of the element to delete (0-based). Must be < vector size.
|
||||||
|
|
||||||
**Returns:**
|
**Returns:**
|
||||||
|
|
||||||
- `ESP_OK` - Success
|
- `ESP_OK` - Success
|
||||||
- `ESP_ERR_INVALID_ARG` - Invalid argument (NULL vector)
|
- `ESP_ERR_INVALID_ARG` - Invalid argument (NULL vector pointer or invalid index)
|
||||||
- `ESP_ERR_INVALID_STATE` - Vector not initialized
|
- `ESP_ERR_NO_MEM` - Memory allocation failed (during reallocation)
|
||||||
- `ESP_FAIL` - Index out of bounds
|
- `ESP_ERR_INVALID_STATE` - Failed to acquire mutex (rare system error)
|
||||||
|
|
||||||
**Note:** All elements after the deleted index are shifted left by one position.
|
**Note:** All elements after the deleted index are shifted left by one position. The deleted item's memory is freed.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### zh_vector_find_item()
|
||||||
|
|
||||||
|
Finds the first occurrence of an element in the vector.
|
||||||
|
|
||||||
|
**Parameters:**
|
||||||
|
|
||||||
|
- `vector` - Pointer to pointer to vector structure (`zh_vector_t **`). Must not be NULL.
|
||||||
|
- `item` - Pointer to the element to find. Must not be NULL.
|
||||||
|
- `index` - Pointer to variable to store the found index. Will be set to -1 if element is not found. Must not be NULL.
|
||||||
|
|
||||||
|
**Returns:**
|
||||||
|
|
||||||
|
- `ESP_OK` - Success (element found)
|
||||||
|
- `ESP_ERR_INVALID_ARG` - Invalid argument (NULL vector pointer, NULL item pointer, or NULL index pointer)
|
||||||
|
- `ESP_ERR_INVALID_STATE` - Failed to acquire mutex (rare system error)
|
||||||
|
- `ESP_ERR_NOT_FOUND` - Element not found (index set to -1)
|
||||||
|
|
||||||
|
**Note:** Uses memcmp to compare elements. Returns the index of the first occurrence. The index variable is set to -1 if the element is not found.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### zh_vector_find_item_in_field()
|
||||||
|
|
||||||
|
Finds the first occurrence of a value in a specific field within structures stored in the vector.
|
||||||
|
|
||||||
|
**Parameters:**
|
||||||
|
|
||||||
|
- `vector` - Pointer to pointer to vector structure (`zh_vector_t **`). Must not be NULL.
|
||||||
|
- `sample_struct` - Pointer to a sample structure of the same type as stored in the vector. Must not be NULL.
|
||||||
|
- `field` - Pointer to the field within the structure to search. Must be a valid member address within sample_struct.
|
||||||
|
- `size` - Size (in bytes) of the field to compare. Must be > 0.
|
||||||
|
- `item` - Pointer to the value to search for. Must not be NULL.
|
||||||
|
- `start` - Starting index for the search (0-based). Must be < vector size.
|
||||||
|
- `index` - Pointer to variable to store the found index. Will be set to -1 if value is not found. Must not be NULL.
|
||||||
|
|
||||||
|
**Returns:**
|
||||||
|
|
||||||
|
- `ESP_OK` - Success (value found)
|
||||||
|
- `ESP_ERR_INVALID_ARG` - Invalid argument (NULL pointer, zero size, or invalid start index)
|
||||||
|
- `ESP_ERR_INVALID_STATE` - Failed to acquire mutex (rare system error)
|
||||||
|
- `ESP_ERR_NOT_FOUND` - Value not found (index set to -1)
|
||||||
|
|
||||||
|
**Note:** This function calculates the offset of the field within the structure using sample_struct and item pointers, then searches for the specified value in that field across all vector elements starting from the given index. Uses memcmp for comparison. Useful for searching in vectors of structures without copying the entire structure.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### zh_vector_remove_duplicates()
|
||||||
|
|
||||||
|
Removes duplicate elements from the vector, keeping only the first occurrence of each element.
|
||||||
|
|
||||||
|
**Parameters:**
|
||||||
|
|
||||||
|
- `vector` - Pointer to pointer to vector structure (`zh_vector_t **`). Must not be NULL.
|
||||||
|
|
||||||
|
**Returns:**
|
||||||
|
|
||||||
|
- `ESP_OK` - Success
|
||||||
|
- `ESP_ERR_INVALID_ARG` - Invalid argument (NULL vector pointer or NULL vector)
|
||||||
|
- `ESP_ERR_INVALID_STATE` - Failed to acquire mutex (rare system error)
|
||||||
|
|
||||||
|
**Note:** Uses memcmp to compare elements. Only the first occurrence of each unique element is preserved. The function preserves the order of first occurrences.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -238,36 +331,50 @@ Deletes an element at a specific index and shifts all subsequent elements.
|
|||||||
```c
|
```c
|
||||||
#include "zh_vector.h"
|
#include "zh_vector.h"
|
||||||
|
|
||||||
zh_vector_t int_vector = {0};
|
|
||||||
|
|
||||||
void app_main(void)
|
void app_main(void)
|
||||||
{
|
{
|
||||||
esp_log_level_set("zh_vector", ESP_LOG_ERROR);
|
esp_log_level_set("zh_vector", ESP_LOG_ERROR);
|
||||||
|
zh_vector_t *vector = NULL;
|
||||||
// Initialize vector for integers
|
// Initialize vector for integers
|
||||||
zh_vector_init(&int_vector, sizeof(int));
|
esp_err_t ret = zh_vector_init(&vector, sizeof(int));
|
||||||
|
if (ret != ESP_OK) {
|
||||||
|
printf("Vector initialization error\n");
|
||||||
|
return;
|
||||||
|
}
|
||||||
// Add elements
|
// Add elements
|
||||||
int val1 = 10;
|
int val1 = 10;
|
||||||
int val2 = 20;
|
int val2 = 20;
|
||||||
int val3 = 30;
|
int val3 = 30;
|
||||||
zh_vector_push_front(&int_vector, &val1);
|
zh_vector_push_front(&vector, &val1);
|
||||||
zh_vector_push_back(&int_vector, &val2);
|
zh_vector_push_back(&vector, &val2);
|
||||||
zh_vector_push_back(&int_vector, &val3);
|
zh_vector_push_back(&vector, &val3);
|
||||||
printf("Vector size: %d\n", zh_vector_get_size(&int_vector));
|
size_t size;
|
||||||
|
ret = zh_vector_get_size(&vector, &size);
|
||||||
|
if (ret == ESP_OK) {
|
||||||
|
printf("Vector size: %zu\n", size);
|
||||||
|
}
|
||||||
// Access elements
|
// Access elements
|
||||||
for (int i = 0; i < zh_vector_get_size(&int_vector); i++) {
|
for (int i = 0; i < size; i++) {
|
||||||
int *item = (int *)zh_vector_get_item(&int_vector, i);
|
int item_value;
|
||||||
printf("Element %d: %d\n", i, *item);
|
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));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
// Change element
|
// Change element
|
||||||
int new_val = 100;
|
int new_val = 100;
|
||||||
zh_vector_change_item(&int_vector, 1, &new_val);
|
zh_vector_change_item(&vector, 1, &new_val);
|
||||||
// Delete element
|
// Delete element
|
||||||
zh_vector_delete_item(&int_vector, 0);
|
zh_vector_delete_item(&vector, 0);
|
||||||
// Cleanup
|
// Cleanup
|
||||||
zh_vector_free(&int_vector);
|
zh_vector_free(&vector);
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
### Struct Example
|
### Struct Example
|
||||||
|
|
||||||
```c
|
```c
|
||||||
@@ -279,52 +386,236 @@ typedef struct {
|
|||||||
float value;
|
float value;
|
||||||
} my_struct_t;
|
} my_struct_t;
|
||||||
|
|
||||||
zh_vector_t struct_vector = {0};
|
|
||||||
|
|
||||||
void app_main(void)
|
void app_main(void)
|
||||||
{
|
{
|
||||||
esp_log_level_set("zh_vector", ESP_LOG_ERROR);
|
esp_log_level_set("zh_vector", ESP_LOG_ERROR);
|
||||||
|
zh_vector_t *vector = NULL;
|
||||||
// Initialize vector for structs
|
// Initialize vector for structs
|
||||||
zh_vector_init(&struct_vector, sizeof(my_struct_t));
|
esp_err_t ret = zh_vector_init(&vector, sizeof(my_struct_t));
|
||||||
|
if (ret != ESP_OK) {
|
||||||
|
printf("Vector initialization error\n");
|
||||||
|
return;
|
||||||
|
}
|
||||||
// Add struct elements
|
// Add struct elements
|
||||||
my_struct_t item1 = {1, "Item 1", 1.5f};
|
my_struct_t item1 = {1, "Item 1", 1.5f};
|
||||||
my_struct_t item2 = {2, "Item 2", 2.5f};
|
my_struct_t item2 = {2, "Item 2", 2.5f};
|
||||||
zh_vector_push_front(&struct_vector, &item1);
|
zh_vector_push_front(&vector, &item1);
|
||||||
zh_vector_push_back(&struct_vector, &item2);
|
zh_vector_push_back(&vector, &item2);
|
||||||
// Access and modify
|
// Access and modify
|
||||||
my_struct_t *ptr = (my_struct_t *)zh_vector_get_item(&struct_vector, 0);
|
my_struct_t item_value;
|
||||||
ptr->value = 10.5f;
|
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);
|
||||||
|
}
|
||||||
// Cleanup
|
// Cleanup
|
||||||
zh_vector_free(&struct_vector);
|
zh_vector_free(&vector);
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
### String Example (Char Arrays)
|
### String Example (Char Arrays)
|
||||||
|
|
||||||
```c
|
```c
|
||||||
#include "zh_vector.h"
|
#include "zh_vector.h"
|
||||||
#include "string.h"
|
|
||||||
|
|
||||||
zh_vector_t string_vector = {0};
|
|
||||||
|
|
||||||
void app_main(void)
|
void app_main(void)
|
||||||
{
|
{
|
||||||
esp_log_level_set("zh_vector", ESP_LOG_ERROR);
|
esp_log_level_set("zh_vector", ESP_LOG_ERROR);
|
||||||
// Initialize vector for strings (100 char max)
|
zh_vector_t *vector = NULL;
|
||||||
char buffer[100] = {0};
|
char buffer[100] = {0};
|
||||||
zh_vector_init(&string_vector, sizeof(buffer));
|
// Initialize vector for strings (100 char max)
|
||||||
|
esp_err_t ret = zh_vector_init(&vector, sizeof(buffer));
|
||||||
|
if (ret != ESP_OK) {
|
||||||
|
printf("Vector initialization error\n");
|
||||||
|
return;
|
||||||
|
}
|
||||||
// Add strings
|
// Add strings
|
||||||
strcpy(buffer, "Hello");
|
strcpy(buffer, "Hello");
|
||||||
zh_vector_push_front(&string_vector, &buffer);
|
zh_vector_push_front(&vector, &buffer);
|
||||||
strcpy(buffer, "World");
|
strcpy(buffer, "World");
|
||||||
zh_vector_push_back(&string_vector, &buffer);
|
zh_vector_push_back(&vector, &buffer);
|
||||||
// Print all strings
|
size_t size;
|
||||||
for (int i = 0; i < zh_vector_get_size(&string_vector); i++) {
|
ret = zh_vector_get_size(&vector, &size);
|
||||||
char *str = (char *)zh_vector_get_item(&string_vector, i);
|
if (ret == ESP_OK) {
|
||||||
printf("String %d: %s\n", i, str);
|
// Print all strings
|
||||||
|
for (int i = 0; i < size; i++) {
|
||||||
|
char str_value[100];
|
||||||
|
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));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Remove duplicates (if any)
|
||||||
|
zh_vector_remove_duplicates(&vector);
|
||||||
|
// Cleanup
|
||||||
|
zh_vector_free(&vector);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Remove Duplicates Example
|
||||||
|
|
||||||
|
```c
|
||||||
|
#include "zh_vector.h"
|
||||||
|
|
||||||
|
void app_main(void)
|
||||||
|
{
|
||||||
|
esp_log_level_set("zh_vector", ESP_LOG_ERROR);
|
||||||
|
zh_vector_t *vector = NULL;
|
||||||
|
// Initialize vector for integers
|
||||||
|
esp_err_t ret = zh_vector_init(&vector, sizeof(int));
|
||||||
|
if (ret != ESP_OK) {
|
||||||
|
printf("Vector initialization error\n");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Add elements with duplicates
|
||||||
|
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;
|
||||||
|
ret = zh_vector_get_size(&vector, &size);
|
||||||
|
if (ret == ESP_OK) {
|
||||||
|
printf("Vector size before removing duplicates: %zu\n", size);
|
||||||
|
}
|
||||||
|
// Remove duplicates
|
||||||
|
zh_vector_remove_duplicates(&vector);
|
||||||
|
ret = zh_vector_get_size(&vector, &size);
|
||||||
|
if (ret == ESP_OK) {
|
||||||
|
printf("Vector size after removing duplicates: %zu\n", size);
|
||||||
|
}
|
||||||
|
// Access remaining elements
|
||||||
|
for (int i = 0; i < size; i++) {
|
||||||
|
int item_value;
|
||||||
|
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));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
// Cleanup
|
// Cleanup
|
||||||
zh_vector_free(&string_vector);
|
zh_vector_free(&vector);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Find Item Example
|
||||||
|
|
||||||
|
```c
|
||||||
|
#include "zh_vector.h"
|
||||||
|
|
||||||
|
void app_main(void)
|
||||||
|
{
|
||||||
|
esp_log_level_set("zh_vector", ESP_LOG_ERROR);
|
||||||
|
zh_vector_t *vector = NULL;
|
||||||
|
// Initialize vector for integers
|
||||||
|
esp_err_t ret = zh_vector_init(&vector, sizeof(int));
|
||||||
|
if (ret != ESP_OK) {
|
||||||
|
printf("Vector initialization error\n");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Add elements
|
||||||
|
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);
|
||||||
|
// Find element
|
||||||
|
int search_item = 20;
|
||||||
|
int16_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, found_index);
|
||||||
|
} else {
|
||||||
|
printf("Element %d not found (index=%d)\n", search_item, found_index);
|
||||||
|
}
|
||||||
|
// Find non-existing element
|
||||||
|
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, found_index);
|
||||||
|
} else {
|
||||||
|
printf("Element %d not found (index=%d)\n", search_item, found_index);
|
||||||
|
}
|
||||||
|
// Cleanup
|
||||||
|
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;
|
||||||
|
|
||||||
|
void app_main(void)
|
||||||
|
{
|
||||||
|
esp_log_level_set("zh_vector", ESP_LOG_ERROR);
|
||||||
|
zh_vector_t *vector = NULL;
|
||||||
|
// Initialize vector for structs
|
||||||
|
esp_err_t ret = zh_vector_init(&vector, sizeof(my_struct_t));
|
||||||
|
if (ret != ESP_OK) {
|
||||||
|
printf("Vector initialization error\n");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Add struct elements
|
||||||
|
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);
|
||||||
|
// Find struct by field value (searching by id field)
|
||||||
|
int search_id = 2;
|
||||||
|
int16_t found_index = -1;
|
||||||
|
// Calculate offset of 'id' field within the structure
|
||||||
|
my_struct_t sample;
|
||||||
|
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, found_index);
|
||||||
|
// Get the found struct
|
||||||
|
my_struct_t found_item;
|
||||||
|
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, found_index);
|
||||||
|
}
|
||||||
|
// Find non-existing id
|
||||||
|
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, found_index);
|
||||||
|
} else {
|
||||||
|
printf("Struct with id=%d not found (index=%d)\n", search_id, found_index);
|
||||||
|
}
|
||||||
|
// Cleanup
|
||||||
|
zh_vector_free(&vector);
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -351,9 +642,9 @@ void app_main(void)
|
|||||||
|------------|-------------|
|
|------------|-------------|
|
||||||
| `ESP_OK` | Operation successful |
|
| `ESP_OK` | Operation successful |
|
||||||
| `ESP_ERR_INVALID_ARG` | Invalid argument (NULL pointer or zero size) |
|
| `ESP_ERR_INVALID_ARG` | Invalid argument (NULL pointer or zero size) |
|
||||||
| `ESP_ERR_INVALID_STATE` | Vector not initialized or already initialized |
|
| `ESP_ERR_INVALID_STATE` | Failed to acquire mutex (rare system error) |
|
||||||
| `ESP_ERR_NO_MEM` | Memory allocation failed (out of memory) |
|
| `ESP_ERR_NO_MEM` | Memory allocation failed (out of memory) |
|
||||||
| `ESP_FAIL` | General failure (e.g., index out of bounds) |
|
| `ESP_ERR_NOT_FOUND` | Element not found (for zh_vector_find_item) |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -405,4 +696,4 @@ limitations under the License.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
*Generated for zh_vector v1.3.0*
|
*Generated for zh_vector v2.4.0*
|
||||||
+389
-98
@@ -24,56 +24,58 @@
|
|||||||
|
|
||||||
## Возможности
|
## Возможности
|
||||||
|
|
||||||
1. **Независимость от типа данных**: Поддерживает любой тип данных (целые числа, числа с плавающей точкой, структуры, пользовательские типы и т.д.)
|
- **Независимость от типа данных**: Поддерживает любой тип данных (целые числа, числа с плавающей точкой, структуры, пользовательские типы и т.д.)
|
||||||
2. **Автоматическое управление памятью**: Автоматическое выделение и освобождение памяти
|
- **Автоматическое управление памятью**: Автоматическое выделение и освобождение памяти
|
||||||
3. **Динамическое изменение размера**: Емкость вектора увеличивается и уменьшается по мере необходимости
|
- **Динамическое изменение размера**: Емкость вектора увеличивается и уменьшается по мере необходимости
|
||||||
4. **Максимальная емкость**: До 65 535 элементов (ограничение 16-битного индекса)
|
- **Максимальная емкость**: До 65 535 элементов (ограничение 16-битного индекса)
|
||||||
5. **Оптимизировано под ESP-IDF**: Использует функции heap_caps для выделения памяти с параметрами памяти
|
- **Оптимизировано под ESP-IDF**: Использует функции heap_caps для выделения памяти с параметрами памяти
|
||||||
6. **Обработка ошибок**: Комплексная проверка ошибок с детальным логированием
|
- **Обработка ошибок**: Комплексная проверка ошибок с детальным логированием
|
||||||
7. **Потокобезопасность**: Является потокобезопасным (использует FreeRTOS mutex)
|
- **Потокобезопасность**: Является потокобезопасным (использует FreeRTOS mutex)
|
||||||
8. **Минимальные накладные расходы**: Низкие накладные расходы на память и процессор
|
- **Минимальные накладные расходы**: Низкие накладные расходы на память и процессор
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Установка
|
## Установка
|
||||||
|
|
||||||
1. Перейдите в каталог компонентов вашего проекта:
|
Перейдите в каталог компонентов вашего проекта:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd ../ваш_проект/components
|
cd ../ваш_проект/components
|
||||||
```
|
```
|
||||||
|
|
||||||
2. Клонируйте репозиторий:
|
Клонируйте репозиторий:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone https://github.com/aZholtikov/zh_vector
|
git clone https://github.com/aZholtikov/zh_vector
|
||||||
```
|
```
|
||||||
|
|
||||||
3. В вашем приложении подключите заголовочный файл:
|
В вашем приложении подключите заголовочный файл:
|
||||||
|
|
||||||
```c
|
```c
|
||||||
#include "zh_vector.h"
|
#include "zh_vector.h"
|
||||||
```
|
```
|
||||||
|
|
||||||
4. Компонент будет автоматически собран вместе с вашим проектом.
|
Компонент будет автоматически собран вместе с вашим проектом.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Справочник API
|
## Справочник API
|
||||||
|
|
||||||
|
Все функции в этой библиотеке используют double pointer (`zh_vector_t **`) для параметра вектора, чтобы обеспечить правильное управление памятью и потокобезопасные операции.
|
||||||
|
|
||||||
### Структура zh_vector_t
|
### Структура zh_vector_t
|
||||||
|
|
||||||
```c
|
Структура объявляется как `typedef struct _zh_vector_t zh_vector_t;` и инкапсулирует внутренние детали реализации.
|
||||||
typedef struct
|
|
||||||
{
|
**Поля (внутренние):**
|
||||||
void **items; // Массив указателей на элементы вектора
|
|
||||||
uint16_t capacity; // Максимальная емкость вектора
|
| Поле | Тип | Описание |
|
||||||
uint16_t size; // Количество элементов в векторе
|
|------|-----|----------|
|
||||||
uint16_t unit; // Размер элемента вектора (в байтах)
|
| `items` | `void **` | Массив указателей на элементы вектора. Items[0..size-1] являются валидными. Выделяется через heap_caps_calloc, перераспределяется через heap_caps_realloc. |
|
||||||
bool is_initialized; // Флаг состояния инициализации вектора
|
| `capacity` | `uint16_t` | Текущая выделенная емкость (количество слотов). Увеличивается при вставке — может превышать size после удалений. |
|
||||||
SemaphoreHandle_t mutex; // FreeRTOS mutex для потокобезопасности
|
| `size` | `uint16_t` | Текущее количество элементов (0 ≤ size ≤ capacity). |
|
||||||
} zh_vector_t;
|
| `unit` | `uint16_t` | Размер (в байтах) одного элемента. Устанавливается при инициализации и не должен меняться. |
|
||||||
```
|
| `mutex` | `SemaphoreHandle_t` | FreeRTOS mutex. Создается в zh_vector_init, удаляется в zh_vector_free. Автоматически блокируется/разблокируется в публичных функциях. |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -83,39 +85,63 @@ typedef struct
|
|||||||
|
|
||||||
**Параметры:**
|
**Параметры:**
|
||||||
|
|
||||||
- `vector` - Указатель на структуру вектора
|
- `vector` - Указатель на указатель на структуру вектора (`zh_vector_t **`). Если указатель на вектор равен NULL, будет выделена память.
|
||||||
- `unit` - Размер каждого элемента в байтах
|
- `unit` - Размер каждого элемента в байтах
|
||||||
|
|
||||||
**Возвращает:**
|
**Возвращает:**
|
||||||
|
|
||||||
- `ESP_OK` - Успех
|
- `ESP_OK` - Успех
|
||||||
- `ESP_ERR_INVALID_ARG` - Неверный аргумент (NULL вектор или нулевой размер unit)
|
- `ESP_ERR_INVALID_ARG` - Неверный аргумент (NULL указатель на вектор или нулевой размер unit)
|
||||||
- `ESP_ERR_INVALID_STATE` - Вектор уже инициализирован
|
- `ESP_ERR_INVALID_STATE` - Вектор уже инициализирован
|
||||||
|
- `ESP_ERR_NO_MEM` - Ошибка выделения памяти
|
||||||
|
|
||||||
**Пример:**
|
**Пример:**
|
||||||
|
|
||||||
```c
|
```c
|
||||||
zh_vector_t vector = {0};
|
zh_vector_t *vector = NULL;
|
||||||
zh_vector_init(&vector, sizeof(int)); // Для целых чисел
|
esp_err_t ret = zh_vector_init(&vector, sizeof(int)); // Для целых чисел
|
||||||
|
if (ret != ESP_OK) {
|
||||||
|
// Обработка ошибки
|
||||||
|
}
|
||||||
|
// Не забудьте освободить: zh_vector_free(&vector);
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### zh_vector_free()
|
### zh_vector_free()
|
||||||
|
|
||||||
Деинициализирует вектор и освобождает всю выделенную память.
|
Деинициализирует вектор и освобождает всю выделенную память. Устанавливает указатель на вектор в NULL.
|
||||||
|
|
||||||
**Параметры:**
|
**Параметры:**
|
||||||
|
|
||||||
- `vector` - Указатель на структуру вектора
|
- `vector` - Указатель на указатель на структуру вектора (`zh_vector_t **`). Не должен быть NULL.
|
||||||
|
|
||||||
**Возвращает:**
|
**Возвращает:**
|
||||||
|
|
||||||
- `ESP_OK` - Успех
|
- `ESP_OK` - Успех
|
||||||
- `ESP_ERR_INVALID_ARG` - Неверный аргумент (NULL вектор)
|
- `ESP_ERR_INVALID_ARG` - Неверный аргумент (NULL указатель на указатель на вектор или NULL указатель на вектор)
|
||||||
- `ESP_ERR_INVALID_STATE` - Вектор не инициализирован
|
- `ESP_ERR_INVALID_STATE` - Не удалось захватить mutex (редкий системный сбой)
|
||||||
|
|
||||||
**Примечание:** Вся динамически выделенная память элементов также освобождается.
|
**Примечание:** Вся динамически выделенная память элементов также освобождается. Указатель на вектор устанавливается в NULL после деинициализации.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### zh_vector_get_capacity()
|
||||||
|
|
||||||
|
Получает текущую выделенную емкость вектора (максимальное количество элементов без перераспределения).
|
||||||
|
|
||||||
|
**Параметры:**
|
||||||
|
|
||||||
|
- `vector` - Указатель на указатель на структуру вектора (`zh_vector_t **`). Не должен быть NULL.
|
||||||
|
- `capacity` - Указатель на переменную для сохранения емкости. Не должен быть NULL.
|
||||||
|
|
||||||
|
**Возвращает:**
|
||||||
|
|
||||||
|
- `ESP_OK` - Успех
|
||||||
|
- `ESP_ERR_INVALID_ARG` - Неверный аргумент (NULL указатель на указатель на вектор или capacity)
|
||||||
|
- `ESP_ERR_INVALID_STATE` - Не удалось захватить mutex (редкий системный сбой)
|
||||||
|
|
||||||
|
**Примечание:** Емкость может быть больше текущего размера (например, после удалений), и уменьшается лениво при size < capacity/2 (или когда size становится 0).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -125,12 +151,14 @@ zh_vector_init(&vector, sizeof(int)); // Для целых чисел
|
|||||||
|
|
||||||
**Параметры:**
|
**Параметры:**
|
||||||
|
|
||||||
- `vector` - Указатель на структуру вектора
|
- `vector` - Указатель на указатель на структуру вектора (`zh_vector_t **`). Не должен быть NULL.
|
||||||
|
- `size` - Указатель на переменную для сохранения размера. Не должен быть NULL.
|
||||||
|
|
||||||
**Возвращает:**
|
**Возвращает:**
|
||||||
|
|
||||||
- `>= 0` - Количество элементов (успех)
|
- `ESP_OK` - Успех
|
||||||
- `ESP_FAIL` - Ошибка (NULL вектор или не инициализирован)
|
- `ESP_ERR_INVALID_ARG` - Неверный аргумент (NULL указатель на указатель на вектор или size)
|
||||||
|
- `ESP_ERR_INVALID_STATE` - Не удалось захватить mutex (редкий системный сбой)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -140,15 +168,15 @@ zh_vector_init(&vector, sizeof(int)); // Для целых чисел
|
|||||||
|
|
||||||
**Параметры:**
|
**Параметры:**
|
||||||
|
|
||||||
- `vector` - Указатель на структуру вектора
|
- `vector` - Указатель на указатель на структуру вектора (`zh_vector_t **`). Не должен быть NULL.
|
||||||
- `item` - Указатель на элемент для добавления
|
- `item` - Указатель на элемент для добавления. Не должен быть NULL.
|
||||||
|
|
||||||
**Возвращает:**
|
**Возвращает:**
|
||||||
|
|
||||||
- `ESP_OK` - Успех
|
- `ESP_OK` - Успех
|
||||||
- `ESP_ERR_INVALID_ARG` - Неверный аргумент (NULL вектор или item)
|
- `ESP_ERR_INVALID_ARG` - Неверный аргумент (NULL указатель на указатель на вектор или item)
|
||||||
- `ESP_ERR_INVALID_STATE` - Вектор не инициализирован
|
|
||||||
- `ESP_ERR_NO_MEM` - Ошибка выделения памяти
|
- `ESP_ERR_NO_MEM` - Ошибка выделения памяти
|
||||||
|
- `ESP_ERR_INVALID_STATE` - Не удалось захватить mutex (редкий системный сбой)
|
||||||
|
|
||||||
**Примечание:** Функция выделяет память для копии элемента и копирует данные. Все существующие элементы сдвигаются на одну позицию вправо.
|
**Примечание:** Функция выделяет память для копии элемента и копирует данные. Все существующие элементы сдвигаются на одну позицию вправо.
|
||||||
|
|
||||||
@@ -160,15 +188,15 @@ zh_vector_init(&vector, sizeof(int)); // Для целых чисел
|
|||||||
|
|
||||||
**Параметры:**
|
**Параметры:**
|
||||||
|
|
||||||
- `vector` - Указатель на структуру вектора
|
- `vector` - Указатель на указатель на структуру вектора (`zh_vector_t **`). Не должен быть NULL.
|
||||||
- `item` - Указатель на элемент для добавления
|
- `item` - Указатель на элемент для добавления. Не должен быть NULL.
|
||||||
|
|
||||||
**Возвращает:**
|
**Возвращает:**
|
||||||
|
|
||||||
- `ESP_OK` - Успех
|
- `ESP_OK` - Успех
|
||||||
- `ESP_ERR_INVALID_ARG` - Неверный аргумент (NULL вектор или item)
|
- `ESP_ERR_INVALID_ARG` - Неверный аргумент (NULL указатель на указатель на вектор или item)
|
||||||
- `ESP_ERR_INVALID_STATE` - Вектор не инициализирован
|
|
||||||
- `ESP_ERR_NO_MEM` - Ошибка выделения памяти
|
- `ESP_ERR_NO_MEM` - Ошибка выделения памяти
|
||||||
|
- `ESP_ERR_INVALID_STATE` - Не удалось захватить mutex (редкий системный сбой)
|
||||||
|
|
||||||
**Примечание:** Функция выделяет память для копии элемента и копирует данные.
|
**Примечание:** Функция выделяет память для копии элемента и копирует данные.
|
||||||
|
|
||||||
@@ -180,34 +208,35 @@ zh_vector_init(&vector, sizeof(int)); // Для целых чисел
|
|||||||
|
|
||||||
**Параметры:**
|
**Параметры:**
|
||||||
|
|
||||||
- `vector` - Указатель на структуру вектора
|
- `vector` - Указатель на указатель на структуру вектора (`zh_vector_t **`). Не должен быть NULL.
|
||||||
- `index` - Индекс элемента для изменения (начиная с 0)
|
- `index` - Индекс элемента для изменения (начиная с 0). Должен быть < размера вектора.
|
||||||
- `item` - Указатель на новые данные элемента
|
- `item` - Указатель на новые данные элемента. Не должен быть NULL.
|
||||||
|
|
||||||
**Возвращает:**
|
**Возвращает:**
|
||||||
|
|
||||||
- `ESP_OK` - Успех
|
- `ESP_OK` - Успех
|
||||||
- `ESP_ERR_INVALID_ARG` - Неверный аргумент (NULL вектор, item или неверный индекс)
|
- `ESP_ERR_INVALID_ARG` - Неверный аргумент (NULL указатель на указатель на вектор, item или неверный индекс)
|
||||||
- `ESP_ERR_INVALID_STATE` - Вектор не инициализирован
|
- `ESP_ERR_INVALID_STATE` - Не удалось захватить mutex (редкий системный сбой)
|
||||||
- `ESP_FAIL` - Индекс вне границ
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### zh_vector_get_item()
|
### zh_vector_get_item()
|
||||||
|
|
||||||
Получает элемент по определенному индексу.
|
Получает элемент по определенному индексу, копируя его в предоставленный буфер пользователя.
|
||||||
|
|
||||||
**Параметры:**
|
**Параметры:**
|
||||||
|
|
||||||
- `vector` - Указатель на структуру вектора
|
- `vector` - Указатель на указатель на структуру вектора (`zh_vector_t **`). Не должен быть NULL.
|
||||||
- `index` - Индекс элемента для получения (начиная с 0)
|
- `index` - Индекс элемента для получения (начиная с 0).
|
||||||
|
- `item` - Указатель на буфер размером не менее `unit` байт, куда будет скопирован элемент. Не должен быть NULL.
|
||||||
|
|
||||||
**Возвращает:**
|
**Возвращает:**
|
||||||
|
|
||||||
- Указатель на элемент (успех)
|
- `ESP_OK` - Успех
|
||||||
- `NULL` - Ошибка (NULL вектор, не инициализирован или неверный индекс)
|
- `ESP_ERR_INVALID_ARG` - Неверный аргумент (NULL указатель на указатель на вектор, NULL указатель item или неверный индекс)
|
||||||
|
- `ESP_ERR_INVALID_STATE` - Не удалось захватить mutex (редкий системный сбой)
|
||||||
|
|
||||||
**Примечание:** Возвращает указатель на внутренние данные. Не освобождайте этот указатель.
|
**Примечание:** Эта функция копирует данные элемента в предоставленный буфер. Указатели не возвращаются.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -217,17 +246,81 @@ zh_vector_init(&vector, sizeof(int)); // Для целых чисел
|
|||||||
|
|
||||||
**Параметры:**
|
**Параметры:**
|
||||||
|
|
||||||
- `vector` - Указатель на структуру вектора
|
- `vector` - Указатель на указатель на структуру вектора (`zh_vector_t **`). Не должен быть NULL.
|
||||||
- `index` - Индекс элемента для удаления (начиная с 0)
|
- `index` - Индекс элемента для удаления (начиная с 0). Должен быть < размера вектора.
|
||||||
|
|
||||||
**Возвращает:**
|
**Возвращает:**
|
||||||
|
|
||||||
- `ESP_OK` - Успех
|
- `ESP_OK` - Успех
|
||||||
- `ESP_ERR_INVALID_ARG` - Неверный аргумент (NULL вектор)
|
- `ESP_ERR_INVALID_ARG` - Неверный аргумент (NULL указатель на указатель на вектор или неверный индекс)
|
||||||
- `ESP_ERR_INVALID_STATE` - Вектор не инициализирован
|
- `ESP_ERR_NO_MEM` - Ошибка выделения памяти (при перераспределении)
|
||||||
- `ESP_FAIL` - Индекс вне границ
|
- `ESP_ERR_INVALID_STATE` - Не удалось захватить mutex (редкий системный сбой)
|
||||||
|
|
||||||
**Примечание:** Все элементы после удаляемого индекса сдвигаются влево на одну позицию.
|
**Примечание:** Все элементы после удаляемого индекса сдвигаются влево на одну позицию. Память удаленного элемента освобождается.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### zh_vector_find_item()
|
||||||
|
|
||||||
|
Находит первое вхождение элемента в векторе.
|
||||||
|
|
||||||
|
**Параметры:**
|
||||||
|
|
||||||
|
- `vector` - Указатель на указатель на структуру вектора (`zh_vector_t **`). Не должен быть NULL.
|
||||||
|
- `item` - Указатель на элемент для поиска. Не должен быть NULL.
|
||||||
|
- `index` - Указатель на переменную для сохранения найденного индекса. Будет установлен в -1, если элемент не найден. Не должен быть NULL.
|
||||||
|
|
||||||
|
**Возвращает:**
|
||||||
|
|
||||||
|
- `ESP_OK` - Успех (элемент найден)
|
||||||
|
- `ESP_ERR_INVALID_ARG` - Неверный аргумент (NULL указатель на вектор, NULL указатель item или NULL указатель index)
|
||||||
|
- `ESP_ERR_INVALID_STATE` - Не удалось захватить mutex (редкий системный сбой)
|
||||||
|
- `ESP_ERR_NOT_FOUND` - Элемент не найден (index установлен в -1)
|
||||||
|
|
||||||
|
**Примечание:** Использует memcmp для сравнения элементов. Возвращает индекс первого вхождения. Переменная index устанавливается в -1, если элемент не найден.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### zh_vector_find_item_in_field()
|
||||||
|
|
||||||
|
Находит первое вхождение значения в определенном поле внутри структур, хранящихся в векторе.
|
||||||
|
|
||||||
|
**Параметры:**
|
||||||
|
|
||||||
|
- `vector` - Указатель на указатель на структуру вектора (`zh_vector_t **`). Не должен быть NULL.
|
||||||
|
- `sample_struct` - Указатель на образец структуры того же типа, что и хранится в векторе. Не должен быть NULL.
|
||||||
|
- `field` - Указатель на поле внутри структуры для поиска. Должен быть действительным адресом члена внутри sample_struct.
|
||||||
|
- `size` - Размер (в байтах) поля для сравнения. Должен быть > 0.
|
||||||
|
- `item` - Указатель на значение для поиска. Не должен быть NULL.
|
||||||
|
- `start` - Начальный индекс для поиска (начиная с 0). Должен быть < размера вектора.
|
||||||
|
- `index` - Указатель на переменную для сохранения найденного индекса. Будет установлен в -1, если значение не найдено. Не должен быть NULL.
|
||||||
|
|
||||||
|
**Возвращает:**
|
||||||
|
|
||||||
|
- `ESP_OK` - Успех (значение найдено)
|
||||||
|
- `ESP_ERR_INVALID_ARG` - Неверный аргумент (NULL указатель, нулевой размер или неверный начальный индекс)
|
||||||
|
- `ESP_ERR_INVALID_STATE` - Не удалось захватить mutex (редкий системный сбой)
|
||||||
|
- `ESP_ERR_NOT_FOUND` - Значение не найдено (index установлен в -1)
|
||||||
|
|
||||||
|
**Примечание:** Эта функция вычисляет смещение поля внутри структуры, используя sample_struct и item указатели, затем ищет указанное значение в этом поле во всех элементах вектора, начиная с заданного индекса. Использует memcmp для сравнения. Полезно для поиска в векторах структур без копирования всей структуры.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### zh_vector_remove_duplicates()
|
||||||
|
|
||||||
|
Удаляет дублирующиеся элементы из вектора, оставляя только первое вхождение каждого элемента.
|
||||||
|
|
||||||
|
**Параметры:**
|
||||||
|
|
||||||
|
- `vector` - Указатель на указатель на структуру вектора (`zh_vector_t **`). Не должен быть NULL.
|
||||||
|
|
||||||
|
**Возвращает:**
|
||||||
|
|
||||||
|
- `ESP_OK` - Успех
|
||||||
|
- `ESP_ERR_INVALID_ARG` - Неверный аргумент (NULL указатель на указатель на вектор или NULL указатель на вектор)
|
||||||
|
- `ESP_ERR_INVALID_STATE` - Не удалось захватить mutex (редкий системный сбой)
|
||||||
|
|
||||||
|
**Примечание:** Использует memcmp для сравнения элементов. Сохраняется только первое вхождение каждого уникального элемента. Функция сохраняет порядок первых вхождений.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -238,36 +331,50 @@ zh_vector_init(&vector, sizeof(int)); // Для целых чисел
|
|||||||
```c
|
```c
|
||||||
#include "zh_vector.h"
|
#include "zh_vector.h"
|
||||||
|
|
||||||
zh_vector_t int_vector = {0};
|
|
||||||
|
|
||||||
void app_main(void)
|
void app_main(void)
|
||||||
{
|
{
|
||||||
esp_log_level_set("zh_vector", ESP_LOG_ERROR);
|
esp_log_level_set("zh_vector", ESP_LOG_ERROR);
|
||||||
|
zh_vector_t *vector = NULL;
|
||||||
// Инициализация вектора для целых чисел
|
// Инициализация вектора для целых чисел
|
||||||
zh_vector_init(&int_vector, sizeof(int));
|
esp_err_t ret = zh_vector_init(&vector, sizeof(int));
|
||||||
|
if (ret != ESP_OK) {
|
||||||
|
printf("Ошибка инициализации вектора\n");
|
||||||
|
return;
|
||||||
|
}
|
||||||
// Добавление элементов
|
// Добавление элементов
|
||||||
int val1 = 10;
|
int val1 = 10;
|
||||||
int val2 = 20;
|
int val2 = 20;
|
||||||
int val3 = 30;
|
int val3 = 30;
|
||||||
zh_vector_push_front(&int_vector, &val1);
|
zh_vector_push_front(&vector, &val1);
|
||||||
zh_vector_push_back(&int_vector, &val2);
|
zh_vector_push_back(&vector, &val2);
|
||||||
zh_vector_push_back(&int_vector, &val3);
|
zh_vector_push_back(&vector, &val3);
|
||||||
printf("Размер вектора: %d\n", zh_vector_get_size(&int_vector));
|
size_t size;
|
||||||
|
ret = zh_vector_get_size(&vector, &size);
|
||||||
|
if (ret == ESP_OK) {
|
||||||
|
printf("Размер вектора: %zu\n", size);
|
||||||
|
}
|
||||||
// Доступ к элементам
|
// Доступ к элементам
|
||||||
for (int i = 0; i < zh_vector_get_size(&int_vector); i++) {
|
for (int i = 0; i < size; i++) {
|
||||||
int *item = (int *)zh_vector_get_item(&int_vector, i);
|
int item_value;
|
||||||
printf("Элемент %d: %d\n", i, *item);
|
esp_err_t err = zh_vector_get_item(&vector, (uint16_t)i, &item_value);
|
||||||
|
if (err == ESP_OK) {
|
||||||
|
printf("Элемент %d: %d\n", i, item_value);
|
||||||
|
} else {
|
||||||
|
printf("Ошибка получения элемента %d: %s\n", i, esp_err_to_name(err));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
// Изменение элемента
|
// Изменение элемента
|
||||||
int new_val = 100;
|
int new_val = 100;
|
||||||
zh_vector_change_item(&int_vector, 1, &new_val);
|
zh_vector_change_item(&vector, 1, &new_val);
|
||||||
// Удаление элемента
|
// Удаление элемента
|
||||||
zh_vector_delete_item(&int_vector, 0);
|
zh_vector_delete_item(&vector, 0);
|
||||||
// Очистка
|
// Очистка
|
||||||
zh_vector_free(&int_vector);
|
zh_vector_free(&vector);
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
### Пример со структурой
|
### Пример со структурой
|
||||||
|
|
||||||
```c
|
```c
|
||||||
@@ -279,52 +386,236 @@ typedef struct {
|
|||||||
float value;
|
float value;
|
||||||
} my_struct_t;
|
} my_struct_t;
|
||||||
|
|
||||||
zh_vector_t struct_vector = {0};
|
|
||||||
|
|
||||||
void app_main(void)
|
void app_main(void)
|
||||||
{
|
{
|
||||||
esp_log_level_set("zh_vector", ESP_LOG_ERROR);
|
esp_log_level_set("zh_vector", ESP_LOG_ERROR);
|
||||||
|
zh_vector_t *vector = NULL;
|
||||||
// Инициализация вектора для структур
|
// Инициализация вектора для структур
|
||||||
zh_vector_init(&struct_vector, sizeof(my_struct_t));
|
esp_err_t ret = zh_vector_init(&vector, sizeof(my_struct_t));
|
||||||
|
if (ret != ESP_OK) {
|
||||||
|
printf("Ошибка инициализации вектора\n");
|
||||||
|
return;
|
||||||
|
}
|
||||||
// Добавление элементов-структур
|
// Добавление элементов-структур
|
||||||
my_struct_t item1 = {1, "Item 1", 1.5f};
|
my_struct_t item1 = {1, "Item 1", 1.5f};
|
||||||
my_struct_t item2 = {2, "Item 2", 2.5f};
|
my_struct_t item2 = {2, "Item 2", 2.5f};
|
||||||
zh_vector_push_front(&struct_vector, &item1);
|
zh_vector_push_front(&vector, &item1);
|
||||||
zh_vector_push_back(&struct_vector, &item2);
|
zh_vector_push_back(&vector, &item2);
|
||||||
// Доступ и модификация
|
// Доступ и модификация
|
||||||
my_struct_t *ptr = (my_struct_t *)zh_vector_get_item(&struct_vector, 0);
|
my_struct_t item_value;
|
||||||
ptr->value = 10.5f;
|
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(&struct_vector);
|
zh_vector_free(&vector);
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
### Пример со строками (массивы символов)
|
### Пример со строками (массивы символов)
|
||||||
|
|
||||||
```c
|
```c
|
||||||
#include "zh_vector.h"
|
#include "zh_vector.h"
|
||||||
#include "string.h"
|
|
||||||
|
|
||||||
zh_vector_t string_vector = {0};
|
|
||||||
|
|
||||||
void app_main(void)
|
void app_main(void)
|
||||||
{
|
{
|
||||||
esp_log_level_set("zh_vector", ESP_LOG_ERROR);
|
esp_log_level_set("zh_vector", ESP_LOG_ERROR);
|
||||||
// Инициализация вектора для строк (макс. 100 символов)
|
zh_vector_t *vector = NULL;
|
||||||
char buffer[100] = {0};
|
char buffer[100] = {0};
|
||||||
zh_vector_init(&string_vector, sizeof(buffer));
|
// Инициализация вектора для строк (макс. 100 символов)
|
||||||
// Добавление строк
|
esp_err_t ret = zh_vector_init(&vector, sizeof(buffer));
|
||||||
|
if (ret != ESP_OK) {
|
||||||
|
printf("Ошибка инициализации вектора\n");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Добавление стро��
|
||||||
strcpy(buffer, "Привет");
|
strcpy(buffer, "Привет");
|
||||||
zh_vector_push_front(&string_vector, &buffer);
|
zh_vector_push_front(&vector, &buffer);
|
||||||
strcpy(buffer, "Мир");
|
strcpy(buffer, "Мир");
|
||||||
zh_vector_push_back(&string_vector, &buffer);
|
zh_vector_push_back(&vector, &buffer);
|
||||||
// Печать всех строк
|
size_t size;
|
||||||
for (int i = 0; i < zh_vector_get_size(&string_vector); i++) {
|
ret = zh_vector_get_size(&vector, &size);
|
||||||
char *str = (char *)zh_vector_get_item(&string_vector, i);
|
if (ret == ESP_OK) {
|
||||||
printf("Строка %d: %s\n", i, str);
|
// Печать всех строк
|
||||||
|
for (int i = 0; i < size; i++) {
|
||||||
|
char str_value[100];
|
||||||
|
esp_err_t err = zh_vector_get_item(&vector, (uint16_t)i, str_value);
|
||||||
|
if (err == ESP_OK) {
|
||||||
|
printf("Строка %d: %s\n", i, str_value);
|
||||||
|
} else {
|
||||||
|
printf("Ошибка получения строки %d: %s\n", i, esp_err_to_name(err));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Удаление дубликатов (если есть)
|
||||||
|
zh_vector_remove_duplicates(&vector);
|
||||||
|
// Очистка
|
||||||
|
zh_vector_free(&vector);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Пример удаления дубликатов
|
||||||
|
|
||||||
|
```c
|
||||||
|
#include "zh_vector.h"
|
||||||
|
|
||||||
|
void app_main(void)
|
||||||
|
{
|
||||||
|
esp_log_level_set("zh_vector", ESP_LOG_ERROR);
|
||||||
|
zh_vector_t *vector = NULL;
|
||||||
|
// Инициализация вектора для целых чисел
|
||||||
|
esp_err_t ret = zh_vector_init(&vector, sizeof(int));
|
||||||
|
if (ret != ESP_OK) {
|
||||||
|
printf("Ошибка инициализации вектора\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;
|
||||||
|
ret = zh_vector_get_size(&vector, &size);
|
||||||
|
if (ret == ESP_OK) {
|
||||||
|
printf("Размер вектора перед удалением дубликатов: %zu\n", size);
|
||||||
|
}
|
||||||
|
// Удаление дубликатов
|
||||||
|
zh_vector_remove_duplicates(&vector);
|
||||||
|
ret = zh_vector_get_size(&vector, &size);
|
||||||
|
if (ret == ESP_OK) {
|
||||||
|
printf("Размер вектора после удаления дубликатов: %zu\n", size);
|
||||||
|
}
|
||||||
|
// Доступ к оставшимся элементам
|
||||||
|
for (int i = 0; i < size; i++) {
|
||||||
|
int item_value;
|
||||||
|
esp_err_t err = zh_vector_get_item(&vector, (uint16_t)i, &item_value);
|
||||||
|
if (err == ESP_OK) {
|
||||||
|
printf("Элемент %d: %d\n", i, item_value);
|
||||||
|
} else {
|
||||||
|
printf("Ошибка получения элемента %d: %s\n", i, esp_err_to_name(err));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
// Очистка
|
// Очистка
|
||||||
zh_vector_free(&string_vector);
|
zh_vector_free(&vector);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Пример поиска элемента
|
||||||
|
|
||||||
|
```c
|
||||||
|
#include "zh_vector.h"
|
||||||
|
|
||||||
|
void app_main(void)
|
||||||
|
{
|
||||||
|
esp_log_level_set("zh_vector", ESP_LOG_ERROR);
|
||||||
|
zh_vector_t *vector = NULL;
|
||||||
|
// Инициализация вектора для целых чисел
|
||||||
|
esp_err_t ret = zh_vector_init(&vector, sizeof(int));
|
||||||
|
if (ret != ESP_OK) {
|
||||||
|
printf("Ошибка инициализации вектора\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;
|
||||||
|
int16_t found_index = -1;
|
||||||
|
ret = zh_vector_find_item(&vector, &search_item, &found_index);
|
||||||
|
if (ret == ESP_OK) {
|
||||||
|
printf("Элемент %d найден по индексу %d\n", search_item, found_index);
|
||||||
|
} else {
|
||||||
|
printf("Элемент %d не найден (index=%d)\n", search_item, found_index);
|
||||||
|
}
|
||||||
|
// Поиск несуществующего элемента
|
||||||
|
search_item = 100;
|
||||||
|
found_index = -1;
|
||||||
|
ret = zh_vector_find_item(&vector, &search_item, &found_index);
|
||||||
|
if (ret == ESP_OK) {
|
||||||
|
printf("Элемент %d найден по индексу %d\n", search_item, found_index);
|
||||||
|
} else {
|
||||||
|
printf("Элемент %d не найден (index=%d)\n", search_item, found_index);
|
||||||
|
}
|
||||||
|
// Очистка
|
||||||
|
zh_vector_free(&vector);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Пример поиска элемента по полю
|
||||||
|
|
||||||
|
```c
|
||||||
|
#include "zh_vector.h"
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
int id;
|
||||||
|
char name[32];
|
||||||
|
float value;
|
||||||
|
} my_struct_t;
|
||||||
|
|
||||||
|
void app_main(void)
|
||||||
|
{
|
||||||
|
esp_log_level_set("zh_vector", ESP_LOG_ERROR);
|
||||||
|
zh_vector_t *vector = NULL;
|
||||||
|
// Инициализация вектора для структур
|
||||||
|
esp_err_t ret = zh_vector_init(&vector, sizeof(my_struct_t));
|
||||||
|
if (ret != ESP_OK) {
|
||||||
|
printf("Ошибка инициализации вектора\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);
|
||||||
|
// Поиск структуры по значению поля (поиск по полю id)
|
||||||
|
int search_id = 2;
|
||||||
|
int16_t found_index = -1;
|
||||||
|
// Вычисление смещения поля 'id' внутри структуры
|
||||||
|
my_struct_t sample;
|
||||||
|
ret = zh_vector_find_item_in_field(&vector, &sample, &sample.id, sizeof(sample.id), &search_id, 0, &found_index);
|
||||||
|
if (ret == ESP_OK) {
|
||||||
|
printf("Структура с id=%d найдена по индексу %d\n", search_id, found_index);
|
||||||
|
// Получение найденной структуры
|
||||||
|
my_struct_t found_item;
|
||||||
|
ret = zh_vector_get_item(&vector, (uint16_t)found_index, &found_item);
|
||||||
|
if (ret == ESP_OK) {
|
||||||
|
printf("Найденный элемент: id=%d, name=%s, value=%.1f\n", found_item.id, found_item.name, found_item.value);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
printf("Структура с id=%d не найдена (index=%d)\n", search_id, found_index);
|
||||||
|
}
|
||||||
|
// Поиск несуществующего id
|
||||||
|
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("Структура с id=%d найдена по индексу %d\n", search_id, found_index);
|
||||||
|
} else {
|
||||||
|
printf("Структура с id=%d не найдена (index=%d)\n", search_id, found_index);
|
||||||
|
}
|
||||||
|
// Очистка
|
||||||
|
zh_vector_free(&vector);
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -351,9 +642,9 @@ void app_main(void)
|
|||||||
|------------|----------|
|
|------------|----------|
|
||||||
| `ESP_OK` | Операция выполнена успешно |
|
| `ESP_OK` | Операция выполнена успешно |
|
||||||
| `ESP_ERR_INVALID_ARG` | Неверный аргумент (NULL указатель или нулевой размер) |
|
| `ESP_ERR_INVALID_ARG` | Неверный аргумент (NULL указатель или нулевой размер) |
|
||||||
| `ESP_ERR_INVALID_STATE` | Вектор не инициализирован или уже инициализирован |
|
| `ESP_ERR_INVALID_STATE` | Не удалось захватить mutex (редкий системный сбой) |
|
||||||
| `ESP_ERR_NO_MEM` | Ошибка выделения памяти (не хватает памяти) |
|
| `ESP_ERR_NO_MEM` | Ошибка выделения памяти (не хватает памяти) |
|
||||||
| `ESP_FAIL` | Общий сбой (например, индекс вне границ) |
|
| `ESP_ERR_NOT_FOUND` | Элемент не найден (для zh_vector_find_item) |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -405,4 +696,4 @@ void app_main(void)
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
*Сгенерировано для zh_vector v1.3.0*
|
*Сгенерировано для zh_vector v2.4.0*
|
||||||
+1
-1
@@ -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.4.0"
|
||||||
license: "Apache-2.0"
|
license: "Apache-2.0"
|
||||||
maintainers:
|
maintainers:
|
||||||
- "Alexey Zholtikov <alexey.zholtikov@yandex.ru>"
|
- "Alexey Zholtikov <alexey.zholtikov@yandex.ru>"
|
||||||
|
|||||||
+207
-50
@@ -1,10 +1,19 @@
|
|||||||
/**
|
/**
|
||||||
* @file zh_vector.h
|
* @file zh_vector.h
|
||||||
|
*
|
||||||
|
* @brief Thread-safe dynamic array (vector) implementation for ESP-IDF.
|
||||||
|
*
|
||||||
|
* This vector stores elements by pointer (i.e., it holds `void*` to heap-allocated copies of items).
|
||||||
|
* The vector is protected by a FreeRTOS mutex, making it safe for use in multi-threaded environments.
|
||||||
|
*
|
||||||
|
* @note The vector allocates memory for each item on push operations.
|
||||||
|
* @note The vector does **not** own the lifetime of the data pointed to by the user — it copies the data.
|
||||||
|
* @warning The `item` parameter of zh_vector_get_item must point to a buffer of at least `unit` bytes.
|
||||||
|
* The function copies the element *by value* — no pointers are returned.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include "string.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 +26,244 @@ extern "C"
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @brief Main structure of vector data.
|
* @brief Opaque vector type.
|
||||||
*/
|
*/
|
||||||
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 Initializes a vector.
|
||||||
*
|
*
|
||||||
* @param[in] vector Pointer to main structure of vector data.
|
* Allocates memory for the vector structure, internal item pointer array and a FreeRTOS mutex.
|
||||||
* @param[in] unit Size of vector item.
|
|
||||||
*
|
*
|
||||||
* @return ESP_OK if success or an error code otherwise.
|
* @note Safe to call with `*vector == NULL` or with `*vector` pointing to uninitialized memory.
|
||||||
|
* @warning Do **not** call this function twice on the same variable without an intervening `zh_vector_free()` — it will return `ESP_ERR_INVALID_STATE`.
|
||||||
|
* To reuse a vector, call `zh_vector_free(&v);` then `zh_vector_init(&v, ...);`.
|
||||||
|
*
|
||||||
|
* @param[out] vector Double pointer to vector structure (`zh_vector_t **`). On success, `*vector` points to newly allocated structure.
|
||||||
|
* @param[in] unit Size (in bytes) of each item. Must be > 0.
|
||||||
|
*
|
||||||
|
* @return ESP_OK on success.
|
||||||
|
* @return ESP_ERR_NO_MEM if memory allocation fails (vector struct or mutex).
|
||||||
|
* @return ESP_ERR_INVALID_ARG if `vector == NULL` or `unit == 0`.
|
||||||
|
* @return ESP_ERR_INVALID_STATE if `*vector != NULL` (already initialized).
|
||||||
*/
|
*/
|
||||||
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 Deinitializes and frees the entire vector.
|
||||||
*
|
*
|
||||||
* @param[in] vector Pointer to main structure of vector data.
|
* Frees all item copies, the internal pointer array, and the mutex. Sets `*vector` to `NULL` before returning.
|
||||||
*
|
*
|
||||||
* @return ESP_OK if success or an error code otherwise.
|
* @warning This function is NOT thread-safe. It must not be called concurrently with any other vector operation
|
||||||
|
* from different tasks or interrupts. The caller is responsible for ensuring that all other accesses to
|
||||||
|
* the vector have completed before invoking `zh_vector_free`. In a multi‑tasking environment, use an external
|
||||||
|
* mutex to protect the vector's lifecycle if concurrent calls are possible.
|
||||||
|
*
|
||||||
|
* @warning After this call, all previously obtained item pointers become invalid.
|
||||||
|
* @note Safe to call with `vector == NULL` or `*vector == NULL` (returns `ESP_OK`).
|
||||||
|
*
|
||||||
|
* @param[in,out] vector Double pointer to vector structure (`zh_vector_t **`). Must not be `NULL`. Set to `NULL` on exit.
|
||||||
|
*
|
||||||
|
* @return ESP_OK on success.
|
||||||
|
* @return ESP_ERR_INVALID_ARG if `vector == NULL` or `*vector == NULL` (not initialized).
|
||||||
|
* @return ESP_ERR_INVALID_STATE if the internal mutex cannot be acquired (rare, indicates a system error).
|
||||||
*/
|
*/
|
||||||
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 Gets the current number of items in the vector.
|
||||||
*
|
*
|
||||||
* @param[in] vector Pointer to main structure of vector data.
|
* @note Thread-safe: internally locks/unlocks the mutex.
|
||||||
*
|
*
|
||||||
* @return Vector size if success or ESP_FAIL otherwise.
|
* @param[in] vector Double pointer to vector structure (`zh_vector_t **`). Must not be `NULL`.
|
||||||
|
* @param[out] size Pointer to store the number of items. Must not be `NULL`.
|
||||||
|
*
|
||||||
|
* @return ESP_OK on success.
|
||||||
|
* @return ESP_ERR_INVALID_ARG if `vector == NULL` or `size == NULL` or `*vector == NULL` (not initialized).
|
||||||
|
* @return ESP_ERR_INVALID_STATE if the internal mutex cannot be acquired (rare, indicates a system error).
|
||||||
*/
|
*/
|
||||||
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 Gets the current allocated capacity (maximum number of elements without reallocation).
|
||||||
*
|
*
|
||||||
* @param[in] vector Pointer to main structure of vector data.
|
* @note Thread-safe: internally locks/unlocks the mutex.
|
||||||
* @param[in] item Pointer to item for add.
|
* @note Capacity may be larger than the current size (e.g., after deletions), and is reduced
|
||||||
|
* lazily via _resize() only when size < capacity/2 (or when size becomes 0).
|
||||||
|
* @note When the vector is empty (size == 0), capacity is guaranteed to be 0.
|
||||||
*
|
*
|
||||||
* @return ESP_OK if success or an error code otherwise.
|
* @param[in] vector Double pointer to vector structure (`zh_vector_t **`). Must not be `NULL`.
|
||||||
|
* @param[out] capacity Pointer to store the allocated capacity. Must not be `NULL`.
|
||||||
|
*
|
||||||
|
* @return ESP_OK on success.
|
||||||
|
* @return ESP_ERR_INVALID_ARG if `vector == NULL`, `capacity == NULL`, or `*vector == NULL` (not initialized).
|
||||||
|
* @return ESP_ERR_INVALID_STATE if the internal mutex cannot be acquired (rare, indicates a system error).
|
||||||
*/
|
*/
|
||||||
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 Adds a copy of the item to the beginning of the vector.
|
||||||
*
|
*
|
||||||
* @param[in] vector Pointer to main structure of vector data.
|
* A copy of `item` is allocated on the heap and stored in the vector.
|
||||||
* @param[in] item Pointer to item for add.
|
* The vector owns the lifetime of this copy (freed on `zh_vector_free()` or `zh_vector_delete_item()`).
|
||||||
|
* All existing items are shifted one position to the right.
|
||||||
|
* This may involve reallocation of the internal pointer array via `heap_caps_realloc`.
|
||||||
*
|
*
|
||||||
* @return ESP_OK if success or an error code otherwise.
|
* @note Memory for the item and potential reallocation is done via `heap_caps_calloc`/`heap_caps_realloc` (`MALLOC_CAP_8BIT`).
|
||||||
|
*
|
||||||
|
* @param[in,out] vector Double pointer to vector structure (`zh_vector_t **`). Must not be `NULL`.
|
||||||
|
* @param[in] item Pointer to the data to copy into the new item. Must not be `NULL`.
|
||||||
|
*
|
||||||
|
* @return ESP_OK on success.
|
||||||
|
* @return ESP_ERR_INVALID_ARG if `vector == NULL` or `item == NULL` or `*vector == NULL` (not initialized).
|
||||||
|
* @return ESP_ERR_NO_MEM if memory allocation fails.
|
||||||
|
* @return ESP_ERR_INVALID_STATE if the internal mutex cannot be acquired (rare, indicates a system error).
|
||||||
*/
|
*/
|
||||||
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 Adds a copy of the item to the end of the vector.
|
||||||
*
|
*
|
||||||
* @param[in] vector Pointer to main structure of vector data.
|
* A copy of `item` is allocated on the heap and stored in the vector.
|
||||||
* @param[in] index Index of item for change.
|
* The vector owns the lifetime of this copy (freed on `zh_vector_free()` or `zh_vector_delete_item()`).
|
||||||
* @param[in] item Pointer to new data of item.
|
* This may involve reallocation of the internal pointer array via `heap_caps_realloc`.
|
||||||
*
|
*
|
||||||
* @return ESP_OK if success or an error code otherwise.
|
* @note Memory for the item and potential reallocation is done via `heap_caps_calloc`/`heap_caps_realloc` (`MALLOC_CAP_8BIT`).
|
||||||
|
*
|
||||||
|
* @param[in,out] vector Double pointer to vector structure (`zh_vector_t **`). Must not be `NULL`.
|
||||||
|
* @param[in] item Pointer to the data to copy into the new item. Must not be `NULL`.
|
||||||
|
*
|
||||||
|
* @return ESP_OK on success.
|
||||||
|
* @return ESP_ERR_INVALID_ARG if `vector == NULL` or `item == NULL` or `*vector == NULL` (not initialized).
|
||||||
|
* @return ESP_ERR_NO_MEM if memory allocation fails.
|
||||||
|
* @return ESP_ERR_INVALID_STATE if the internal mutex cannot be acquired (rare, indicates a system error).
|
||||||
*/
|
*/
|
||||||
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 Replaces the item at the specified index with a copy of the provided data.
|
||||||
*
|
*
|
||||||
* @param[in] vector Pointer to main structure of vector data.
|
* @warning Modifies the existing item *in-place* — no new memory allocation occurs.
|
||||||
* @param[in] index Index of item for get.
|
* Only the data is overwritten (via `memcpy`). The item size must match the vector’s `unit`.
|
||||||
*
|
*
|
||||||
* @return Pointer to item or NULL otherwise.
|
* @param[in,out] vector Double pointer to vector structure (`zh_vector_t **`). Must not be `NULL`.
|
||||||
|
* @param[in] index Index of the item to replace (must be < `(*vector)->size`).
|
||||||
|
* @param[in] item Pointer to new data to copy into the item. Must not be `NULL`.
|
||||||
|
*
|
||||||
|
* @return ESP_OK on success.
|
||||||
|
* @return ESP_ERR_INVALID_ARG if `vector == NULL`, `item == NULL`, `index >= (*vector)->size` or `*vector == NULL` (not initialized).
|
||||||
|
* @return ESP_ERR_INVALID_STATE if the internal mutex cannot be acquired (rare, indicates a system error).
|
||||||
*/
|
*/
|
||||||
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 Retrieves the item at the specified index by copying it into the user-provided buffer.
|
||||||
*
|
*
|
||||||
* @param[in] vector Pointer to main structure of vector data.
|
* @note Thread-safe: internally locks/unlocks the mutex.
|
||||||
* @param[in] index Index of item for delete.
|
* @note This function **copies** the element — no pointers are returned or stored.
|
||||||
*
|
*
|
||||||
* @return ESP_OK if success or an error code otherwise.
|
* @param[in] vector Double pointer to vector structure (`zh_vector_t **`). Must not be `NULL`.
|
||||||
|
* @param[in] index Index of the item to retrieve (0-based).
|
||||||
|
* @param[out] item Pointer to a buffer of at least `unit` bytes, where the item will be copied.
|
||||||
|
*
|
||||||
|
* @return ESP_OK on success.
|
||||||
|
* @return ESP_ERR_INVALID_ARG if `vector == NULL`, `item == NULL`, `index >= (*vector)->size` or `*vector == NULL` (not initialized).
|
||||||
|
* @return ESP_ERR_INVALID_STATE if the internal mutex cannot be acquired (rare, indicates a system error).
|
||||||
*/
|
*/
|
||||||
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 Deletes the item at the specified index and shifts subsequent items one position left.
|
||||||
|
*
|
||||||
|
* The deleted item’s memory is freed.
|
||||||
|
* If the size drops below half of the capacity (and size > 0), the capacity is reduced via `_resize(size)`.
|
||||||
|
* If the size reaches 0, capacity is set to 0 and the pointer array is freed.
|
||||||
|
*
|
||||||
|
* @note Thread-safe: internally locks/unlocks the mutex.
|
||||||
|
*
|
||||||
|
* @param[in,out] vector Double pointer to vector structure (`zh_vector_t **`). Must not be `NULL`.
|
||||||
|
* @param[in] index Index of the item to delete (must be < `(*vector)->size`).
|
||||||
|
*
|
||||||
|
* @return ESP_OK on success.
|
||||||
|
* @return ESP_ERR_INVALID_ARG if `vector == NULL`, `index >= (*vector)->size` or `*vector == NULL` (not initialized).
|
||||||
|
* @return ESP_ERR_NO_MEM if memory allocation fails.
|
||||||
|
* @return ESP_ERR_INVALID_STATE if the internal mutex cannot be acquired (rare, indicates a system error).
|
||||||
|
*/
|
||||||
|
esp_err_t zh_vector_delete_item(zh_vector_t **vector, uint16_t index);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Removes duplicate items from the vector, keeping only the first occurrence of each value.
|
||||||
|
*
|
||||||
|
* The function compares items byte-by-byte using `memcmp(..., unit)`. All elements that are equal
|
||||||
|
* to a previously seen element are deleted. The relative order of the remaining elements is preserved.
|
||||||
|
*
|
||||||
|
* @note This operation is O(n^2) in the worst case and may be slow for large vectors.
|
||||||
|
* @note Memory of duplicate elements is freed, and the vector capacity may be reduced if the size drops
|
||||||
|
* below half of the capacity (same as in zh_vector_delete_item).
|
||||||
|
* @note Thread-safe: internally locks/unlocks the mutex.
|
||||||
|
*
|
||||||
|
* @param[in,out] vector Double pointer to vector structure (`zh_vector_t **`). Must not be `NULL`.
|
||||||
|
*
|
||||||
|
* @return ESP_OK on success.
|
||||||
|
* @return ESP_ERR_INVALID_ARG if `vector == NULL` or `*vector == NULL` (not initialized).
|
||||||
|
* @return ESP_ERR_INVALID_STATE if the internal mutex cannot be acquired (rare, indicates a system error).
|
||||||
|
* @return ESP_ERR_NO_MEM if memory allocation fails during capacity reduction.
|
||||||
|
*/
|
||||||
|
esp_err_t zh_vector_remove_duplicates(zh_vector_t **vector);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Searches for an item equal to the given data in the vector.
|
||||||
|
*
|
||||||
|
* Compares the provided item with each element in the vector using `memcmp`.
|
||||||
|
* If a match is found, its index (0‑based) is written to `*index` and `ESP_OK` is returned.
|
||||||
|
* If no match is found, `*index` is set to `-1` and `ESP_ERR_NOT_FOUND` is returned.
|
||||||
|
*
|
||||||
|
* @note Thread-safe: internally locks/unlocks the mutex.
|
||||||
|
* @note The search is linear O(n).
|
||||||
|
*
|
||||||
|
* @param[in] vector Double pointer to vector structure (`zh_vector_t **`). Must not be `NULL`.
|
||||||
|
* @param[in] item Pointer to the data to search for. Must not be `NULL`.
|
||||||
|
* @param[out] index Pointer to store the found index (0‑based) or `-1` if not found. Must not be `NULL`.
|
||||||
|
*
|
||||||
|
* @return ESP_OK if the item is found.
|
||||||
|
* @return ESP_ERR_NOT_FOUND if the item is not present in the vector.
|
||||||
|
* @return ESP_ERR_INVALID_ARG if any pointer argument is `NULL` or `*vector == NULL` (not initialized).
|
||||||
|
* @return ESP_ERR_INVALID_STATE if the internal mutex cannot be acquired (rare, system error).
|
||||||
|
*/
|
||||||
|
esp_err_t zh_vector_find_item(zh_vector_t **vector, const void *item, int16_t *index);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Searches for an item in a vector of structures by comparing a specific field.
|
||||||
|
*
|
||||||
|
* This function is intended for vectors that store structures (not primitive types).
|
||||||
|
* It takes a sample structure and a pointer to one of its fields, computes the field offset,
|
||||||
|
* and then scans the vector starting from the given index. For each element, it compares
|
||||||
|
* the bytes of the field with the provided value using `memcmp`. If a match is found,
|
||||||
|
* its index (0‑based) is written to `*index` and `ESP_OK` is returned. If no match is found,
|
||||||
|
* `*index` is set to `-1` and `ESP_ERR_NOT_FOUND` is returned.
|
||||||
|
*
|
||||||
|
* @note The vector must contain elements of a structure type. The `sample_struct` and `field`
|
||||||
|
* pointers must belong to the same structure definition as the elements stored in the vector.
|
||||||
|
* The function computes the field offset as `(uint8_t*)field - (uint8_t*)sample_struct`.
|
||||||
|
* @note The `size` parameter must be the exact size in bytes of the field (e.g., `sizeof(sample.id)`). If `size` is 0, the function returns an error.
|
||||||
|
* @note This function is thread-safe: internally locks/unlocks the mutex for the entire search.
|
||||||
|
* @note The search is linear O(n) and starts from the given `start` index to the end.
|
||||||
|
* @note To find all occurrences, call this function repeatedly with an updated `start` index (found index + 1) until `ESP_ERR_NOT_FOUND` is returned.
|
||||||
|
*
|
||||||
|
* @param[in] vector Double pointer to the vector structure (must be initialized).
|
||||||
|
* @param[in] sample_struct Pointer to a sample structure of the same type as stored in the vector. Used only to compute the field offset. The contents are not used.
|
||||||
|
* @param[in] field Pointer to the specific field inside the `sample_struct`.
|
||||||
|
* @param[in] size Size in bytes of the field. Must be > 0.
|
||||||
|
* @param[in] item Pointer to the value to search for in the field.
|
||||||
|
* @param[in] start Index (0‑based) from which to start searching. Must be < vector size.
|
||||||
|
* @param[out] index Pointer to store the found index (0‑based) or `-1` if not found.
|
||||||
|
*
|
||||||
|
* @return ESP_OK if a matching element is found (index is set).
|
||||||
|
* @return ESP_ERR_NOT_FOUND if no element with a matching field value is found.
|
||||||
|
* @return ESP_ERR_INVALID_ARG if any pointer argument is NULL, `*vector` is NULL (not initialized), `size == 0`, `start >= vector size`, or the field extends beyond the element size.
|
||||||
|
* @return ESP_ERR_INVALID_STATE if the internal mutex cannot be acquired.
|
||||||
|
*/
|
||||||
|
esp_err_t zh_vector_find_item_in_field(zh_vector_t **vector, const void *sample_struct, const void *field, size_t size, const void *item, uint16_t start, int16_t *index);
|
||||||
|
|
||||||
#ifdef __cplusplus
|
#ifdef __cplusplus
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -1 +1 @@
|
|||||||
1.3.0
|
2.4.0
|
||||||
+273
-110
@@ -13,183 +13,303 @@ static const char *TAG = "zh_vector";
|
|||||||
return err; \
|
return err; \
|
||||||
}
|
}
|
||||||
|
|
||||||
static esp_err_t _resize(zh_vector_t *vector, uint16_t capacity);
|
#define ZH_ERROR_CHECK_VOID(cond, cleanup, msg, ...) \
|
||||||
|
if (!(cond)) \
|
||||||
|
{ \
|
||||||
|
ZH_LOGE(msg, ESP_FAIL, ##__VA_ARGS__); \
|
||||||
|
cleanup; \
|
||||||
|
return; \
|
||||||
|
}
|
||||||
|
|
||||||
esp_err_t zh_vector_init(zh_vector_t *vector, uint16_t unit, ...)
|
/**
|
||||||
|
* @brief Internal representation of a thread-safe, dynamically resizing vector of *copied* elements.
|
||||||
|
*
|
||||||
|
* Stores pointers to heap-allocated *copies* of elements (not raw pointers).
|
||||||
|
* Elements (stored in items[i]) are allocated via heap_caps_calloc(1, unit, ...) and freed via heap_caps_free.
|
||||||
|
* Supports push front/back, change, delete and size queries.
|
||||||
|
* Thread safety via FreeRTOS mutex.
|
||||||
|
*
|
||||||
|
* @note Opaque type: only zh_vector_t (typedef struct _zh_vector_t* zh_vector_t) is exposed.
|
||||||
|
* @note Elements are deep-copied — ownership of input item is NOT transferred.
|
||||||
|
* @note All public functions lock the mutex internally — no external locking required.
|
||||||
|
* Internal functions _resize() and _calc_new_capacity() are not thread-safe and must be called
|
||||||
|
* only while the vector's mutex is held.
|
||||||
|
* @note Internal function _resize() guarantees invariant: 0 ≤ size ≤ capacity.
|
||||||
|
* In particular, _resize(..., 0) always sets size = 0, capacity = 0, and frees all element buffers.
|
||||||
|
* @note The capacity may exceed size after deletions (memory is not shrunk immediately),
|
||||||
|
* and is reduced only via _resize() on explicit request (e.g., during delete).
|
||||||
|
*
|
||||||
|
* @warning Do not access fields directly — always use public API.
|
||||||
|
* @warning unit must match the actual element size — mismatch causes heap corruption.
|
||||||
|
* @note capacity and size are limited to uint16_t (max 65535 elements), to save memory on embedded devices.
|
||||||
|
* @note items is allocated via heap_caps_realloc as `void*`, but logically treated as `void**`.
|
||||||
|
* Each valid items[i] (0 ≤ i < size) points to a heap buffer of exactly `unit` bytes (allocated via heap_caps_calloc(1, unit, ...)).
|
||||||
|
* Only the first `unit` bytes are used for the copied item.
|
||||||
|
* @warning Actual memory usage depends on allocator overhead and alignment.
|
||||||
|
* Rough estimate: `sizeof(zh_vector_t) + capacity * sizeof(void*) + size * (unit + item_overhead)`.
|
||||||
|
* Typical heap overhead per item: ~16 bytes (metadata + alignment).
|
||||||
|
* @note Capacity reduction is triggered when `size < capacity / 2` (integer division). For example:
|
||||||
|
* - capacity=4, size=1 → capacity=1 (4/2=2 > 1)
|
||||||
|
* - capacity=2, size=1 → capacity stays 2 (2/2=1 not > 1)
|
||||||
|
* - capacity=1, size=0 → capacity=0 (handled separately: size==0 && capacity>0)
|
||||||
|
* @note When size reaches 0, capacity is always set to 0, even without explicit resize request.
|
||||||
|
*/
|
||||||
|
struct _zh_vector_t
|
||||||
|
{
|
||||||
|
void **items; /*!< Array of element pointers. items[0..size-1] are valid and non-NULL. Initially NULL; allocated via heap_caps_realloc (as `void*`, cast to `void**`). When capacity > old_capacity, new slots (items[old_capacity..capacity-1]) are zeroed (NULL). */
|
||||||
|
uint16_t capacity; /*!< Current allocated capacity (number of slots). Grows on insertion, shrinks on delete (see _resize). Limited to uint16_t (max 65535). */
|
||||||
|
uint16_t size; /*!< Current number of valid elements (0 ≤ size ≤ capacity). Always kept in sync: _resize(..., 0) sets size = 0; after push operations size++; after delete size--. */
|
||||||
|
uint16_t unit; /*!< Size (in bytes) of a single element. Set once in zh_vector_init() and immutable. Must match the actual element size — mismatch causes heap corruption. */
|
||||||
|
SemaphoreHandle_t mutex; /*!< FreeRTOS mutex. Created in zh_vector_init() and deleted in zh_vector_free(). All public functions acquire it before accessing/modifying the vector state. The mutex itself does not affect logical state (`size`, `capacity`). */
|
||||||
|
};
|
||||||
|
|
||||||
|
static esp_err_t _resize(zh_vector_t *vector, uint16_t capacity);
|
||||||
|
static esp_err_t _delete(zh_vector_t *vector, uint16_t index);
|
||||||
|
static inline uint16_t _calc_new_capacity(uint16_t current);
|
||||||
|
|
||||||
|
esp_err_t zh_vector_init(zh_vector_t **vector, uint16_t unit) // -V2008
|
||||||
{
|
{
|
||||||
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;
|
(*vector)->items = NULL;
|
||||||
vector->unit = unit;
|
(*vector)->capacity = 0;
|
||||||
vector->is_initialized = true;
|
(*vector)->size = 0;
|
||||||
|
(*vector)->unit = unit;
|
||||||
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.");
|
for (uint16_t i = 0; i < (*vector)->size; ++i)
|
||||||
for (uint16_t i = 0; i < vector->size; ++i)
|
|
||||||
{
|
{
|
||||||
if (vector->items[i] != NULL)
|
if ((*vector)->items[i] != NULL)
|
||||||
{
|
{
|
||||||
heap_caps_free(vector->items[i]);
|
heap_caps_free((*vector)->items[i]);
|
||||||
vector->items[i] = NULL;
|
(*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(xSemaphoreTake((*vector)->mutex, portMAX_DELAY) == pdTRUE, ESP_ERR_INVALID_STATE, NULL, "Getting vector size failed. Failed to acquire mutex.");
|
||||||
ZH_ERROR_CHECK(xSemaphoreTake(vector->mutex, portMAX_DELAY) == pdTRUE, ESP_FAIL, NULL, "Getting vector size fail. Failed to acquire mutex.");
|
*size = (*vector)->size;
|
||||||
size_t size = vector->size;
|
xSemaphoreGive((*vector)->mutex);
|
||||||
xSemaphoreGive(vector->mutex);
|
|
||||||
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(xSemaphoreTake((*vector)->mutex, portMAX_DELAY) == pdTRUE, ESP_ERR_INVALID_STATE, NULL, "Getting vector capacity failed. Failed to acquire mutex.");
|
||||||
|
*capacity = (*vector)->capacity;
|
||||||
|
xSemaphoreGive((*vector)->mutex);
|
||||||
|
ZH_LOGI("Getting vector capacity success.");
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t zh_vector_push_front(zh_vector_t **vector, const void *item) // -V2008
|
||||||
{
|
{
|
||||||
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(xSemaphoreTake((*vector)->mutex, portMAX_DELAY) == pdTRUE, ESP_ERR_INVALID_STATE, NULL, "Adding item to beginning of vector failed. Failed to acquire mutex.");
|
||||||
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((*vector)->size < UINT16_MAX, ESP_ERR_NO_MEM, xSemaphoreGive((*vector)->mutex), "Adding item to beginning of vector failed. Vector is full.");
|
||||||
if (vector->capacity == vector->size)
|
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(_resize(*vector, new_capacity) == ESP_OK, ESP_ERR_NO_MEM, xSemaphoreGive((*vector)->mutex), "Adding item to beginning of vector failed. Memory reallocation failed.");
|
||||||
}
|
}
|
||||||
for (uint16_t i = vector->size; i > 0; --i)
|
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] = heap_caps_calloc(1, (*vector)->unit, MALLOC_CAP_8BIT);
|
||||||
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.");
|
ZH_ERROR_CHECK((*vector)->items[0] != NULL, ESP_ERR_NO_MEM, xSemaphoreGive((*vector)->mutex), "Adding item to beginning of vector failed. Element allocation failed.");
|
||||||
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_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) // -V2008
|
||||||
{
|
{
|
||||||
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(xSemaphoreTake((*vector)->mutex, portMAX_DELAY) == pdTRUE, ESP_ERR_INVALID_STATE, NULL, "Adding item to vector failed. Failed to acquire mutex.");
|
||||||
ZH_ERROR_CHECK(xSemaphoreTake(vector->mutex, portMAX_DELAY) == pdTRUE, ESP_FAIL, NULL, "Adding item to vector fail. Failed to acquire mutex.");
|
ZH_ERROR_CHECK((*vector)->size < UINT16_MAX, ESP_ERR_NO_MEM, xSemaphoreGive((*vector)->mutex), "Adding item to vector failed. Vector is full.");
|
||||||
if (vector->capacity == vector->size)
|
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(_resize(*vector, new_capacity) == ESP_OK, ESP_ERR_NO_MEM, xSemaphoreGive((*vector)->mutex), "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), "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_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) // -V2008
|
||||||
{
|
{
|
||||||
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(xSemaphoreTake((*vector)->mutex, portMAX_DELAY) == pdTRUE, ESP_ERR_INVALID_STATE, NULL, "Changing item in vector failed. Failed to acquire mutex.");
|
||||||
ZH_ERROR_CHECK(xSemaphoreTake(vector->mutex, portMAX_DELAY) == pdTRUE, ESP_FAIL, NULL, "Changing item in vector fail. Failed to acquire mutex.");
|
ZH_ERROR_CHECK(index < (*vector)->size, ESP_ERR_INVALID_ARG, xSemaphoreGive((*vector)->mutex), "Changing item in vector failed. Index out of bounds.");
|
||||||
ZH_ERROR_CHECK(index < vector->size, ESP_FAIL, NULL, "Changing item in vector fail. Index does not exist.");
|
ZH_ERROR_CHECK((*vector)->items[index] != NULL, ESP_ERR_INVALID_STATE, xSemaphoreGive((*vector)->mutex), "Changing item in vector failed. Item is NULL.");
|
||||||
memcpy(vector->items[index], item, vector->unit);
|
memcpy((*vector)->items[index], item, (*vector)->unit);
|
||||||
xSemaphoreGive(vector->mutex);
|
xSemaphoreGive((*vector)->mutex);
|
||||||
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) // -V2008
|
||||||
{
|
{
|
||||||
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(xSemaphoreTake((*vector)->mutex, portMAX_DELAY) == pdTRUE, ESP_ERR_INVALID_STATE, NULL, "Getting item from vector failed. Failed to acquire mutex.");
|
||||||
ZH_LOGE("Getting item from vector fail. Invalid argument.", ESP_ERR_INVALID_ARG);
|
ZH_ERROR_CHECK(index < (*vector)->size, ESP_ERR_INVALID_ARG, xSemaphoreGive((*vector)->mutex), "Getting item from vector failed. Index out of bounds.");
|
||||||
return NULL;
|
ZH_ERROR_CHECK((*vector)->items[index] != NULL, ESP_ERR_INVALID_STATE, xSemaphoreGive((*vector)->mutex), "Getting item from vector failed. Item is NULL.");
|
||||||
}
|
memcpy(item, (*vector)->items[index], (*vector)->unit);
|
||||||
if (vector->is_initialized == false)
|
xSemaphoreGive((*vector)->mutex);
|
||||||
{
|
|
||||||
ZH_LOGE("Getting item from vector fail. Vector not initialized.", ESP_ERR_INVALID_STATE);
|
|
||||||
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) // -V2008
|
||||||
{
|
{
|
||||||
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(xSemaphoreTake((*vector)->mutex, portMAX_DELAY) == pdTRUE, ESP_ERR_INVALID_STATE, NULL, "Deleting item in vector failed. Failed to acquire mutex.");
|
||||||
ZH_ERROR_CHECK(xSemaphoreTake(vector->mutex, portMAX_DELAY) == pdTRUE, ESP_FAIL, NULL, "Deleting item in vector fail. Failed to acquire mutex.");
|
ZH_ERROR_CHECK(index < (*vector)->size, ESP_ERR_INVALID_ARG, xSemaphoreGive((*vector)->mutex), "Deleting item in vector failed. Index out of bounds.");
|
||||||
ZH_ERROR_CHECK(index < vector->size, ESP_FAIL, NULL, "Deleting item in vector fail. Index does not exist.");
|
ZH_ERROR_CHECK(_delete(*vector, index) == ESP_OK, ESP_ERR_INVALID_STATE, xSemaphoreGive((*vector)->mutex), "Deleting item in vector failed. Internal error.");
|
||||||
void *freed_item = vector->items[index];
|
xSemaphoreGive((*vector)->mutex);
|
||||||
for (uint16_t i = index; i < (vector->size - 1); ++i)
|
|
||||||
{
|
|
||||||
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_remove_duplicates(zh_vector_t **vector) // -V2008
|
||||||
|
{
|
||||||
|
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(xSemaphoreTake((*vector)->mutex, portMAX_DELAY) == pdTRUE, ESP_ERR_INVALID_STATE, NULL, "Removing duplicates from vector failed. Failed to acquire mutex.");
|
||||||
|
if ((*vector)->size >= 2)
|
||||||
|
{
|
||||||
|
for (uint16_t i = 0; i < (*vector)->size - 1; ++i)
|
||||||
|
{
|
||||||
|
uint16_t j = i + 1;
|
||||||
|
while (j < (*vector)->size)
|
||||||
|
{
|
||||||
|
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), "Removing duplicates from vector failed. Internal error.");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
++j;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
xSemaphoreGive((*vector)->mutex);
|
||||||
|
ZH_LOGI("Removing duplicates from vector success.");
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t zh_vector_find_item(zh_vector_t **vector, const void *item, int16_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(xSemaphoreTake((*vector)->mutex, portMAX_DELAY) == pdTRUE, ESP_ERR_INVALID_STATE, NULL, "Finding item in vector failed. Failed to acquire mutex.");
|
||||||
|
*index = -1;
|
||||||
|
for (uint16_t i = 0; i < (*vector)->size; ++i)
|
||||||
|
{
|
||||||
|
if (memcmp((*vector)->items[i], item, (*vector)->unit) == 0)
|
||||||
|
{
|
||||||
|
*index = (int16_t)i;
|
||||||
|
xSemaphoreGive((*vector)->mutex);
|
||||||
|
ZH_LOGI("Finding item in vector success (found).");
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
xSemaphoreGive((*vector)->mutex);
|
||||||
|
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, size_t size, const void *value, uint16_t start, int16_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 && size > 0, ESP_ERR_INVALID_ARG, NULL, "Finding field in structure failed. Invalid argument.");
|
||||||
|
ZH_ERROR_CHECK(xSemaphoreTake((*vector)->mutex, portMAX_DELAY) == pdTRUE, ESP_ERR_INVALID_STATE, NULL, "Finding field in structure failed. Mutex acquire failed.");
|
||||||
|
ZH_ERROR_CHECK(start < (*vector)->size, ESP_ERR_INVALID_ARG, xSemaphoreGive((*vector)->mutex), "Finding field in structure failed. Start index out of bounds.");
|
||||||
|
size_t offset = (const uint8_t *)item - (const uint8_t *)sample_struct;
|
||||||
|
ZH_ERROR_CHECK((offset + size) <= (*vector)->unit, ESP_ERR_INVALID_ARG, xSemaphoreGive((*vector)->mutex), "Finding field in structure failed. Field exceeds element size.");
|
||||||
|
*index = -1;
|
||||||
|
for (uint16_t i = start; i < (*vector)->size; ++i)
|
||||||
|
{
|
||||||
|
const uint8_t *elem = (const uint8_t *)(*vector)->items[i];
|
||||||
|
if (memcmp(elem + offset, value, size) == 0)
|
||||||
|
{
|
||||||
|
*index = (int16_t)i;
|
||||||
|
xSemaphoreGive((*vector)->mutex);
|
||||||
|
ZH_LOGI("Finding field in structure success (found).");
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
xSemaphoreGive((*vector)->mutex);
|
||||||
|
ZH_LOGI("Finding field in structure success (not found).");
|
||||||
|
return ESP_ERR_NOT_FOUND;
|
||||||
|
}
|
||||||
|
|
||||||
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)
|
||||||
{
|
{
|
||||||
|
if (vector->items != NULL)
|
||||||
|
{
|
||||||
|
for (uint16_t i = 0; i < vector->size; ++i)
|
||||||
|
{
|
||||||
|
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->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 +318,46 @@ 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 && vector->capacity / 2 > vector->size)
|
||||||
|
{
|
||||||
|
return _resize(vector, vector->size);
|
||||||
|
}
|
||||||
|
else if (vector->size == 0 && vector->capacity > 0)
|
||||||
|
{
|
||||||
|
_resize(vector, 0);
|
||||||
|
}
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user