Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reduce ensure nesting #86

Merged
merged 1 commit into from
Oct 24, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 13 additions & 21 deletions ext/zlib/zlib.c
Original file line number Diff line number Diff line change
Expand Up @@ -1100,6 +1100,12 @@ zstream_run_try(VALUE value_arg)
int err;
VALUE old_input = Qnil;

/* Cannot start zstream while it is in progress. */
if (z->flags & ZSTREAM_IN_PROGRESS) {
rb_raise(cInProgressError, "zlib stream is in progress");
}
z->flags |= ZSTREAM_IN_PROGRESS;

if (NIL_P(z->input) && len == 0) {
z->stream.next_in = (Bytef*)"";
z->stream.avail_in = 0;
Expand Down Expand Up @@ -1167,35 +1173,18 @@ zstream_run_try(VALUE value_arg)
rb_str_resize(old_input, 0);
}

if (args->jump_state)
rb_jump_tag(args->jump_state);

return Qnil;
}

static VALUE
zstream_run_ensure(VALUE value_arg)
{
struct zstream_run_args *args = (struct zstream_run_args *)value_arg;
struct zstream *z = args->z;

/* Remove ZSTREAM_IN_PROGRESS flag to signal that this zstream is not in use. */
args->z->flags &= ~ZSTREAM_IN_PROGRESS;

return Qnil;
}

static VALUE
zstream_run_synchronized(VALUE value_arg)
{
struct zstream_run_args *args = (struct zstream_run_args *)value_arg;

/* Cannot start zstream while it is in progress. */
if (args->z->flags & ZSTREAM_IN_PROGRESS) {
rb_raise(cInProgressError, "zlib stream is in progress");
}
args->z->flags |= ZSTREAM_IN_PROGRESS;

rb_ensure(zstream_run_try, value_arg, zstream_run_ensure, value_arg);
z->flags &= ~ZSTREAM_IN_PROGRESS;
rb_mutex_unlock(z->mutex);

return Qnil;
}
Expand All @@ -1212,7 +1201,10 @@ zstream_run(struct zstream *z, Bytef *src, long len, int flush)
.jump_state = 0,
.stream_output = !ZSTREAM_IS_GZFILE(z) && rb_block_given_p(),
};
rb_mutex_synchronize(z->mutex, zstream_run_synchronized, (VALUE)&args);
rb_mutex_lock(z->mutex);
rb_ensure(zstream_run_try, (VALUE)&args, zstream_run_ensure, (VALUE)&args);
if (args.jump_state)
rb_jump_tag(args.jump_state);
}

static VALUE
Expand Down