Skip to content

Commit 3261d84

Browse files
committed
Clamp out-of-bounds slice indices
1 parent 4121892 commit 3261d84

File tree

1 file changed

+16
-12
lines changed

1 file changed

+16
-12
lines changed

include/minja/minja.hpp

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1226,7 +1226,7 @@ class SubscriptExpr : public Expression {
12261226
}
12271227
bool reverse = step == -1;
12281228

1229-
size_t len = target_value.size();
1229+
size_t len = target_value.size();
12301230
int64_t start = slice->start ? slice->start->evaluate(context).get<int64_t>() : (reverse ? len - 1 : 0);
12311231
int64_t end = slice->end ? slice->end->evaluate(context).get<int64_t>() : (reverse ? -1 : len);
12321232

@@ -1237,19 +1237,27 @@ class SubscriptExpr : public Expression {
12371237
end = (int64_t)len + end;
12381238
}
12391239

1240+
if (!reverse) {
1241+
start = std::max((int64_t)0, start);
1242+
start = std::min(start, (int64_t)len);
1243+
end = std::max((int64_t)0, end);
1244+
end = std::min(end, (int64_t)len);
1245+
} else {
1246+
start = std::max((int64_t)-1, start);
1247+
start = std::min(start, (int64_t)len - 1);
1248+
end = std::max((int64_t)-1, end);
1249+
end = std::min(end, (int64_t)len - 1);
1250+
}
1251+
12401252
if (target_value.is_string()) {
12411253
std::string s = target_value.get<std::string>();
12421254

12431255
std::string result_str;
12441256
if (reverse) {
12451257
for (int64_t i = start; i > end; --i) {
1246-
if (i >= 0 && i < (int64_t)len) {
1247-
result_str += s[i];
1248-
} else if (i < 0) {
1249-
break;
1250-
}
1258+
result_str += s[i];
12511259
}
1252-
} else {
1260+
} else if (start < end) {
12531261
result_str = s.substr(start, end - start);
12541262
}
12551263
return result_str;
@@ -1258,11 +1266,7 @@ class SubscriptExpr : public Expression {
12581266
auto result = Value::array();
12591267
if (reverse) {
12601268
for (int64_t i = start; i > end; --i) {
1261-
if (i >= 0 && i < (int64_t)len) {
1262-
result.push_back(target_value.at(i));
1263-
} else if (i < 0) {
1264-
break;
1265-
}
1269+
result.push_back(target_value.at(i));
12661270
}
12671271
} else {
12681272
for (auto i = start; i < end; ++i) {

0 commit comments

Comments
 (0)