Skip to content

Commit bc7368a

Browse files
committed
Add lfs_file_movehandle to allow moving file handles in the rare case it is needed. Add lfs_file_ishandleopen to allow checking if a file handle is open.
1 parent 8e251dd commit bc7368a

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

lfs.c

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6318,6 +6318,47 @@ lfs_soff_t lfs_file_size(lfs_t *lfs, lfs_file_t *file) {
63186318
return res;
63196319
}
63206320

6321+
int lfs_file_movehandle(lfs_t *lfs, lfs_file_t *old_file, lfs_file_t *new_file)
6322+
{
6323+
int err = LFS_LOCK(lfs->cfg);
6324+
if (err) {
6325+
return err;
6326+
}
6327+
LFS_TRACE("lfs_file_movehandle(%p, %p, %p)", (void*)lfs, (void*)old_file, (void*)new_file);
6328+
LFS_ASSERT(lfs_mlist_isopen(lfs->mlist, (struct lfs_mlist*)old_file));
6329+
LFS_ASSERT(!lfs_mlist_isopen(lfs->mlist, (struct lfs_mlist*)new_file));
6330+
6331+
*new_file = *old_file;
6332+
lfs_mlist_remove(lfs, (struct lfs_mlist*)old_file);
6333+
lfs_mlist_append(lfs, (struct lfs_mlist*)new_file);
6334+
6335+
err = LFS_ERR_OK;
6336+
6337+
LFS_TRACE("lfs_file_movehandle -> %d", err);
6338+
LFS_UNLOCK(lfs->cfg);
6339+
return err;
6340+
}
6341+
6342+
int lfs_file_ishandleopen(lfs_t *lfs, lfs_file_t *file)
6343+
{
6344+
int err = LFS_LOCK(lfs->cfg);
6345+
if (err) {
6346+
return err;
6347+
}
6348+
LFS_TRACE("lfs_file_ishandleopen(%p, %p)", (void*)lfs, (void*)file);
6349+
6350+
if(lfs_mlist_isopen(lfs->mlist, (struct lfs_mlist*)file)) {
6351+
err = LFS_ERR_OK;
6352+
}
6353+
else {
6354+
err = LFS_ERR_BADF;
6355+
}
6356+
6357+
LFS_TRACE("lfs_file_ishandleopen -> %d", err);
6358+
LFS_UNLOCK(lfs->cfg);
6359+
return err;
6360+
}
6361+
63216362
#ifndef LFS_READONLY
63226363
int lfs_mkdir(lfs_t *lfs, const char *path) {
63236364
int err = LFS_LOCK(lfs->cfg);

lfs.h

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -656,6 +656,20 @@ int lfs_file_rewind(lfs_t *lfs, lfs_file_t *file);
656656
// Returns the size of the file, or a negative error code on failure.
657657
lfs_soff_t lfs_file_size(lfs_t *lfs, lfs_file_t *file);
658658

659+
// Move a file handle
660+
//
661+
// Littlefs file handles are somewhat expensive to move.
662+
// Try to avoid needing to move them.
663+
// This allows moving a file handle from old_file to new_file when needed for abstraction.
664+
// After this call, old_file is invalid.
665+
//
666+
// Returns a negative error code on failure.
667+
int lfs_file_movehandle(lfs_t *lfs, lfs_file_t *old_file, lfs_file_t *new_file);
668+
669+
// Check if a given file handle is open
670+
//
671+
// Returns LFS_ERR_OK if the file handle is open, else LFS_ERR_BADF
672+
int lfs_file_ishandleopen(lfs_t *lfs, lfs_file_t *file);
659673

660674
/// Directory operations ///
661675

0 commit comments

Comments
 (0)