[vlc-commits] commit: vlc_loaddir: avoid realloc at every iteration ( Rémi Denis-Courmont )
git at videolan.org
git at videolan.org
Tue Aug 3 20:56:12 CEST 2010
vlc | branch: master | Rémi Denis-Courmont <remi at remlab.net> | Tue Aug 3 21:55:49 2010 +0300| [7214994261f855c83ee4d40d4b068418e04dcc62] | committer: Rémi Denis-Courmont
vlc_loaddir: avoid realloc at every iteration
> http://git.videolan.org/gitweb.cgi/vlc.git/?a=commit;h=7214994261f855c83ee4d40d4b068418e04dcc62
---
src/text/filesystem.c | 71 ++++++++++++++++++++++++++----------------------
1 files changed, 38 insertions(+), 33 deletions(-)
diff --git a/src/text/filesystem.c b/src/text/filesystem.c
index e7a65b8..65fafcb 100644
--- a/src/text/filesystem.c
+++ b/src/text/filesystem.c
@@ -353,54 +353,59 @@ int vlc_loaddir( DIR *dir, char ***namelist,
int (*select)( const char * ),
int (*compar)( const char **, const char ** ) )
{
- if( select == NULL )
+ assert (dir);
+
+ if (select == NULL)
select = dummy_select;
- if( dir == NULL )
- return -1;
- else
- {
- char **tab = NULL;
- char *entry;
- unsigned num = 0;
+ char **tab = NULL;
+ unsigned num = 0;
- rewinddir( dir );
+ rewinddir (dir);
- while( ( entry = vlc_readdir( dir ) ) != NULL )
+ for (unsigned size = 0;;)
+ {
+ errno = 0;
+ char *entry = vlc_readdir (dir);
+ if (entry == NULL)
{
- char **newtab;
+ if (errno)
+ goto error;
+ break;
+ }
- if( !select( entry ) )
- {
- free( entry );
- continue;
- }
+ if (!select (entry))
+ {
+ free (entry);
+ continue;
+ }
- newtab = realloc( tab, sizeof( char * ) * (num + 1) );
- if( newtab == NULL )
+ if (num >= size)
+ {
+ size = size ? (2 * size) : 16;
+ char **newtab = realloc (tab, sizeof (*tab) * (size));
+
+ if (unlikely(newtab == NULL))
{
- free( entry );
+ free (entry);
goto error;
}
tab = newtab;
- tab[num++] = entry;
}
- if( compar != NULL )
- qsort( tab, num, sizeof( tab[0] ),
- (int (*)( const void *, const void *))compar );
-
- *namelist = tab;
- return num;
+ tab[num++] = entry;
+ }
- error:{
- unsigned i;
+ if (compar != NULL)
+ qsort (tab, num, sizeof (*tab),
+ (int (*)( const void *, const void *))compar);
+ *namelist = tab;
+ return num;
- for( i = 0; i < num; i++ )
- free( tab[i] );
- free( tab );
- }
- }
+error:
+ for (unsigned i = 0; i < num; i++)
+ free (tab[i]);
+ free (tab);
return -1;
}
More information about the vlc-commits
mailing list