Skip to content

Commit

Permalink
Minor changes and tweaks in code
Browse files Browse the repository at this point in the history
- Add enums where used.
- Replace for loop with memcpy call.
- Add verbose comments to make it super easy to port to other platforms.
  • Loading branch information
josesimoes committed Mar 20, 2024
1 parent a5275b9 commit 394f788
Showing 1 changed file with 20 additions and 9 deletions.
29 changes: 20 additions & 9 deletions targets/ESP32/_common/targetHAL_StorageOperation.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,32 +32,37 @@ uint32_t HAL_StorageOperation(

size_t result;
StorageOperationErrorCode errorCode = StorageOperationErrorCode::NoError;

EnsureStorageInitialized();

// check if the name is not empty
if (nameLength == 0)
{
return StorageOperationErrorCode::WriteError;
}

// convert storageName to char*
char *strName = (char *)platform_malloc(nameLength + 1);

// sanity check for successfull malloc
if (strName == NULL)
{
return StorageOperationErrorCode::PlatformError;
}

for (uint32_t i = 0; i < nameLength; i++)
{
strName[i] = static_cast<char>(data[i]);
}
// go and copy the name
memcpy(strName, data, nameLength);

// Just making sure it's properly 0 terminated
strName[nameLength] = '\0';

// !! the returned char* needs to be freed !!
char *storageNameChar = ConvertToVfsPath(strName);

// Cleaning the temporary name buffer
platform_free(strName);

if (operation == (uint8_t)(StorageOperation_Monitor::StorageOperation_Write))
if (operation == StorageOperation_Monitor::StorageOperation_Write)
{
// Remove the file if already exists
remove(storageNameChar);
Expand All @@ -69,34 +74,40 @@ uint32_t HAL_StorageOperation(
result = fwrite((const void *)(data + nameLength), 1, (size_t)dataLength, file);
fclose(file);

// check if the data was written
if (result != (size_t)dataLength)
{
errorCode = StorageOperationErrorCode::WriteError;
}
}
else if (operation == (uint8_t)(StorageOperation_Monitor::StorageOperation_Append))
else if (operation == StorageOperation_Monitor::StorageOperation_Append)
{
// Open the file in read mode
FILE *file = fopen(storageNameChar, "a");
fseek(file, 0, SEEK_END);

// append more data
result = fwrite((const void *)(data + nameLength), 1, (size_t)dataLength, file);
fclose(file);

// check if the data was written
if (result != (size_t)dataLength)
{
errorCode = StorageOperationErrorCode::WriteError;
}
}
else if (operation == (uint8_t)(StorageOperation_Monitor::StorageOperation_Delete))
else if (operation == StorageOperation_Monitor::StorageOperation_Delete)
{
result = remove(storageNameChar);

// check if the file was deleted
if (result != 0)
{
errorCode = StorageOperationErrorCode::DeleteError;
}
}

// free buffer memory
if (storageNameChar != NULL)
{
platform_free(storageNameChar);
Expand Down

0 comments on commit 394f788

Please sign in to comment.