Skip to content

Commit

Permalink
Lwt_unix.readdir_n: eliminate some allocations
Browse files Browse the repository at this point in the history
  • Loading branch information
aantron committed Nov 23, 2016
1 parent dbc42f2 commit 61ee392
Showing 1 changed file with 9 additions and 19 deletions.
28 changes: 9 additions & 19 deletions src/unix/lwt_unix_unix.c
Original file line number Diff line number Diff line change
Expand Up @@ -1547,37 +1547,25 @@ struct job_readdir_n {
DIR *dir;
long count;
int error_code;
struct dirent *entries[];
struct dirent entries[];
};

static void worker_readdir_n(struct job_readdir_n *job)
{
size_t size = dirent_size(job->dir);
long i;
for(i = 0; i < job->count; i++) {
struct dirent *ptr;
struct dirent *entry = (struct dirent *)lwt_unix_malloc(size);

int result = readdir_r(job->dir, entry, &ptr);
int result = readdir_r(job->dir, &job->entries[i], &ptr);

/* An error happened. */
if (result != 0) {
/* Free already read entries. */
free(entry);
long j;
for(j = 0; j < i; j++) free(job->entries[j]);
/* Return an error. */
job->error_code = result;
return;
}

/* End of directory reached */
if (ptr == NULL) {
free(entry);
if (ptr == NULL)
break;
}

job->entries[i] = entry;
}

job->count = i;
Expand All @@ -1596,8 +1584,7 @@ static value result_readdir_n(struct job_readdir_n *job)
result = caml_alloc(job->count, 0);
long i;
for(i = 0; i < job->count; i++) {
Store_field(result, i, caml_copy_string(job->entries[i]->d_name));
free(job->entries[i]);
Store_field(result, i, caml_copy_string(job->entries[i].d_name));
}
lwt_unix_free_job(&job->job);
CAMLreturn(result);
Expand All @@ -1607,9 +1594,12 @@ static value result_readdir_n(struct job_readdir_n *job)
CAMLprim value lwt_unix_readdir_n_job(value val_dir, value val_count)
{
long count = Long_val(val_count);
LWT_UNIX_INIT_JOB(job, readdir_n, sizeof(struct dirent*) * count);
job->dir = DIR_Val(val_dir);
DIR *dir = DIR_Val(val_dir);

LWT_UNIX_INIT_JOB(job, readdir_n, dirent_size(dir) * count);
job->dir = dir;
job->count = count;

return lwt_unix_alloc_job(&job->job);
}

Expand Down

0 comments on commit 61ee392

Please sign in to comment.