summaryrefslogtreecommitdiff
path: root/string.c
diff options
context:
space:
mode:
authornobu <nobu@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2011-03-02 14:20:06 +0000
committernobu <nobu@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2011-03-02 14:20:06 +0000
commitcddcffb8f9dd015650b2ac02235bfe39261989f9 (patch)
treed327758d47d6a93d6f9c20d07477be7b3b0a2c89 /string.c
parente1e8297a76cbe7918458cb37043ad498228c6139 (diff)
* string.c (str_byte_substr): return nil for negative length.
git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@31007 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
Diffstat (limited to 'string.c')
-rw-r--r--string.c56
1 files changed, 29 insertions, 27 deletions
diff --git a/string.c b/string.c
index bb13bd1d8d..770df7f651 100644
--- a/string.c
+++ b/string.c
@@ -3990,35 +3990,37 @@ rb_str_setbyte(VALUE str, VALUE index, VALUE value)
static VALUE
str_byte_substr(VALUE str, long beg, long len)
{
- char *p, *s = RSTRING_PTR(str), *e = s + RSTRING_LEN(str);
- VALUE str2;
- if (beg > RSTRING_LEN(str)) return Qnil;
- if (beg < 0) {
- beg += RSTRING_LEN(str);
- if (beg < 0) return Qnil;
- }
- if (beg + len > RSTRING_LEN(str))
- len = RSTRING_LEN(str) - beg;
- if (len <= 0) {
- len = 0;
- p = 0;
- }
- else
- p = s + beg;
+ char *p, *s = RSTRING_PTR(str);
+ long n = RSTRING_LEN(str);
+ VALUE str2;
- if (len > RSTRING_EMBED_LEN_MAX && beg + len == RSTRING_LEN(str)) {
- str2 = rb_str_new4(str);
- str2 = str_new3(rb_obj_class(str2), str2);
- RSTRING(str2)->as.heap.ptr += RSTRING(str2)->as.heap.len - len;
- RSTRING(str2)->as.heap.len = len;
- }
- else {
- str2 = rb_str_new5(str, p, len);
- rb_enc_cr_str_copy_for_substr(str2, str);
- OBJ_INFECT(str2, str);
- }
+ if (beg > n || len < 0) return Qnil;
+ if (beg < 0) {
+ beg += n;
+ if (beg < 0) return Qnil;
+ }
+ if (beg + len > n)
+ len = n - beg;
+ if (len <= 0) {
+ len = 0;
+ p = 0;
+ }
+ else
+ p = s + beg;
- return str2;
+ if (len > RSTRING_EMBED_LEN_MAX && beg + len == n) {
+ str2 = rb_str_new4(str);
+ str2 = str_new3(rb_obj_class(str2), str2);
+ RSTRING(str2)->as.heap.ptr += RSTRING(str2)->as.heap.len - len;
+ RSTRING(str2)->as.heap.len = len;
+ }
+ else {
+ str2 = rb_str_new5(str, p, len);
+ rb_enc_cr_str_copy_for_substr(str2, str);
+ OBJ_INFECT(str2, str);
+ }
+
+ return str2;
}
static VALUE