Skip to content

Commit

Permalink
Refactor oslMoveImageTo function for clarity and robustness
Browse files Browse the repository at this point in the history
- Added early return if the image is already at the desired location to avoid unnecessary processing.
- Improved error handling by restoring the original data pointer if memory allocation fails.
- Enhanced code readability with clear comments and logical flow.
- Replaced numeric boolean values with `true` and `false` for better clarity.
  • Loading branch information
dogo committed Sep 2, 2024
1 parent 2c9f99b commit 2501260
Showing 1 changed file with 31 additions and 27 deletions.
58 changes: 31 additions & 27 deletions src/image/oslMoveImageTo.c
Original file line number Diff line number Diff line change
@@ -1,33 +1,37 @@
#include "oslib.h"

bool oslMoveImageTo(OSL_IMAGE *img, int newLocation) {
bool success = 0;
//On ne gère pas ça sur PC
bool oslMoveImageTo(OSL_IMAGE *img, int newLocation) {
// On PC, this function doesn't manage image relocation, so we return success.
#ifndef PSP
return 1;
return 1;
#endif

//Moves the image
if (img->location != newLocation) {
//We keep the old pointer in order to recopy the old data to the new image
OSL_IMAGE oldImage = *img;

//Allocate some new data for the image. Setting data to NULL prevents oslAllocImageData from freeing memory automatically (we need this memory later to copy the old image contents).
img->data = NULL;

oslAllocImageData(img, newLocation);
if (img->data) {
//Copy the old image to the new one
memcpy(img->data, oldImage.data, img->totalSize);

//We can now free the old image data
oslFreeImageData(&oldImage);

oslUncacheImageData(img);
success = 1;
}
}

return success;
}
// If the image is already in the desired location, no need to move it.
if (img->location == newLocation) {
return 1;
}

// Keep the old image data to copy to the new location.
OSL_IMAGE oldImage = *img;

// Prevent automatic freeing of memory during reallocation by setting data to NULL.
img->data = NULL;

// Allocate new data for the image at the new location.
if (!oslAllocImageData(img, newLocation)) {
// If allocation fails, restore the original data pointer and return failure.
img->data = oldImage.data;
return 0;
}

// Copy the old image data to the new memory location.
memcpy(img->data, oldImage.data, img->totalSize);

// Free the old image data since it has been copied successfully.
oslFreeImageData(&oldImage);

// Update image caching after moving.
oslUncacheImageData(img);

return 1;
}

0 comments on commit 2501260

Please sign in to comment.