Skip to content

Commit

Permalink
simplify scrotCheckIfOverwriteFile()
Browse files Browse the repository at this point in the history
* the `nalloc += extLength;` was redundant because `slen` contains the
  extension length already.
* bring the declaration closer to usage.
* stop special casing the no extension case.
  • Loading branch information
N-R-K committed Sep 25, 2023
1 parent 98a3d25 commit 2c69b5d
Showing 1 changed file with 10 additions and 21 deletions.
31 changes: 10 additions & 21 deletions src/scrot.c
Original file line number Diff line number Diff line change
Expand Up @@ -573,33 +573,22 @@ static void scrotCheckIfOverwriteFile(char **filename)
return;

const size_t maxCounter = 999;
size_t counter = 0;
char *ext = NULL;
size_t extLength = 0;
char fmt[5]; // _000 + NUL byte
const size_t slen = strlen(*filename);
size_t nalloc = slen + 4 + 1; // _000 + NUL byte
char fmt[5];
char *newName = NULL;

extLength = scrotHaveFileExtension(*filename, &ext);
const size_t nalloc = slen + sizeof(fmt);

if (extLength)
nalloc += extLength; // .ext
char *ext;
size_t extLength = scrotHaveFileExtension(*filename, &ext);

newName = ecalloc(nalloc, sizeof(*newName));
memcpy(newName, *filename, slen);
char *newName = ecalloc(nalloc, sizeof(*newName));
memcpy(newName, *filename, slen - extLength);
char *ptr = newName + (slen - extLength);

size_t counter = 0;
do {
char *ptr = newName + slen;

snprintf(fmt, sizeof(fmt), "_%03zu", counter++);

if (extLength) {
ptr -= extLength;
memcpy(ptr, fmt, sizeof(fmt));
memcpy(ptr + sizeof(fmt) - 1, ext, extLength);
} else
memcpy(ptr, fmt, sizeof(fmt));
memcpy(ptr, fmt, sizeof(fmt));
memcpy(ptr + sizeof(fmt) - 1, ext, extLength);
} while ((counter < maxCounter) && !access(newName, F_OK));

scrotAssert(newName[nalloc - 1] == '\0');
Expand Down

0 comments on commit 2c69b5d

Please sign in to comment.