Skip to content

Commit 1596d19

Browse files
committed
Add ossl_str_new(), an exception-safe rb_str_new()
Add a new function ossl_str_new() as an exception-safe wrapper of rb_str_new(). This is useful for the openssl library because we can't always raise NoMemoryError immediately due to the independent memory management of OpenSSL.
1 parent 3dd7586 commit 1596d19

File tree

2 files changed

+26
-7
lines changed

2 files changed

+26
-7
lines changed

ext/openssl/ossl.c

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -92,22 +92,40 @@ OSSL_IMPL_SK2ARY(x509crl, X509_CRL)
9292
OSSL_IMPL_SK2ARY(x509name, X509_NAME)
9393

9494
static VALUE
95-
ossl_str_new(int size)
95+
ossl_str_new_i(VALUE size)
9696
{
97-
return rb_str_new(0, size);
97+
return rb_str_new(NULL, (long)size);
98+
}
99+
100+
VALUE
101+
ossl_str_new(const char *ptr, long len, int *pstate)
102+
{
103+
VALUE str;
104+
int state;
105+
106+
str = rb_protect(ossl_str_new_i, len, &state);
107+
if (pstate)
108+
*pstate = state;
109+
if (state) {
110+
if (!pstate)
111+
rb_set_errinfo(Qnil);
112+
return Qnil;
113+
}
114+
if (ptr)
115+
memcpy(RSTRING_PTR(str), ptr, len);
116+
return str;
98117
}
99118

100119
VALUE
101120
ossl_buf2str(char *buf, int len)
102121
{
103122
VALUE str;
104-
int status = 0;
123+
int state;
105124

106-
str = rb_protect((VALUE (*)(VALUE))ossl_str_new, len, &status);
107-
if(!NIL_P(str)) memcpy(RSTRING_PTR(str), buf, len);
125+
str = ossl_str_new(buf, len, &state);
108126
OPENSSL_free(buf);
109-
if(status) rb_jump_tag(status);
110-
127+
if (state)
128+
rb_jump_tag(state);
111129
return str;
112130
}
113131

ext/openssl/ossl.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@ VALUE ossl_x509_sk2ary(const STACK_OF(X509) *certs);
9292
VALUE ossl_x509crl_sk2ary(const STACK_OF(X509_CRL) *crl);
9393
VALUE ossl_x509name_sk2ary(const STACK_OF(X509_NAME) *names);
9494
VALUE ossl_buf2str(char *buf, int len);
95+
VALUE ossl_str_new(const char *, long, int *);
9596
#define ossl_str_adjust(str, p) \
9697
do{\
9798
long len = RSTRING_LEN(str);\

0 commit comments

Comments
 (0)