Skip to content
This repository has been archived by the owner on Oct 4, 2024. It is now read-only.

filesystem: improve read/write apis #12

Merged
merged 1 commit into from
Aug 7, 2024
Merged

Conversation

rr-
Copy link
Contributor

@rr- rr- commented Aug 7, 2024

Instead of a code like this:

int32_t version;
File_Read(&version, sizeof(int32_t), 1, fp);

this PR lets us write code like this:

const int32_t version = File_ReadS32(fp);

This also has the additional benefit of not causing problems if the storage size of the target variable is different than the read size:

int32_t foo = 0x12735471;
File_Read(&foo, sizeof(int16_t), 1, fp); // read two bytes that are both 0xFF
// foo now contains a garbage value of 0x1273FFFF.
// Because we only overrode two bytes, parts of the old value remain intact.
Full example using POSIX C

First off, a sample code, test.c:

#include <stdio.h>
#include <stdint.h>

int main(void)
{
    int32_t value = 0x12735471;
    printf("%x\n", value);
    FILE *fp = fopen("test.txt", "rb");
    fread(&value, sizeof(int16_t), 1, fp);
    printf("%x\n", value);
    fclose(fp);
    return 0;
}

Compiling and examining the results:

$ echo -ne "\xff\xff" > test.txt
$ gcc ./test.c -o ./test
$ chmod +x ./test
$ ./test
12735471
1273ffff

Thanks to having the type promotion work through an assignment, the value of foo in the new API will be correctly set to 0xFFFFFFFF (eg -1 as intended).

Full example using POSIX C

Updated test.c:

#include <stdio.h>
#include <stdint.h>

static int16_t read_s16(FILE *fp)
{
    int16_t result;
    fread(&result, sizeof(int16_t), 1, fp);
    return result;
}

int main(void)
{
    int32_t value = 0x12735471;
    printf("%x\n", value);
    FILE *fp = fopen("test.txt", "rb");
    value = read_s16(fp);
    printf("%x\n", value);
    fclose(fp);
    return 0;
}

Examining the results:

$ echo -ne "\xff\xff" > test.txt
$ gcc ./test.c -o ./test
$ chmod +x ./test
$ ./test
12735471
ffffffff

@rr- rr- requested review from a team, eikehein, lahm86 and walkawayy and removed request for a team August 7, 2024 10:38
Copy link
Contributor

@walkawayy walkawayy left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like the change to return the read variable.

@rr- rr- merged commit 54d1237 into main Aug 7, 2024
2 checks passed
@rr- rr- deleted the filesystem-io-better-apis branch August 7, 2024 19:10
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants