Skip to content

Commit

Permalink
Add += operator for string.
Browse files Browse the repository at this point in the history
This allows appending to a `string` without having to allocate a new
string. This might perform better most of the time.

Closes #1500.
  • Loading branch information
bbannier committed Jan 4, 2024
1 parent 8d081af commit 77e9cb2
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 0 deletions.
4 changes: 4 additions & 0 deletions doc/autogen/types/string.rst
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@
Returns the concatenation of two strings.

.. spicy:operator:: string::SumAssign string t:string <sp> op:+= <sp> t:string
Appends the second string to the first.

.. spicy:operator:: string::Unequal bool t:string <sp> op:!= <sp> t:string
Compares two strings lexicographically.
Expand Down
2 changes: 2 additions & 0 deletions hilti/toolchain/include/ast/operators/string.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ STANDARD_OPERATOR_1(string, Size, type::UnsignedInteger(64), type::String(),
"Returns the number of characters the string contains.");
STANDARD_OPERATOR_2(string, Sum, type::String(), type::String(), type::String(),
"Returns the concatenation of two strings.");
STANDARD_OPERATOR_2(string, SumAssign, type::String(), type::String(), type::String(),
"Appends the second string to the first.");

BEGIN_METHOD(string, Encode)
const auto& signature() const {
Expand Down
1 change: 1 addition & 0 deletions hilti/toolchain/src/compiler/codegen/operators.cc
Original file line number Diff line number Diff line change
Expand Up @@ -727,6 +727,7 @@ struct Visitor : hilti::visitor::PreOrder<cxx::Expression, Visitor> {
// String

result_t operator()(const operator_::string::Sum& n) { return binary(n, "+"); }
result_t operator()(const operator_::string::SumAssign& n) { return binary(n, "+="); }
result_t operator()(const operator_::string::Size& n) { return fmt("%s.size()", op0(n)); }
result_t operator()(const operator_::string::Equal& n) { return binary(n, "=="); }
result_t operator()(const operator_::string::Unequal& n) { return binary(n, "!="); }
Expand Down
21 changes: 21 additions & 0 deletions tests/hilti/types/string/operators.hlt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# @TEST-EXEC: ${HILTIC} -dj %INPUT

module Foo {

global x1 = "abc";
x1 = x1 + "123";
assert x1 == "abc123";

global x2 = "abc";
x2 += "123";
assert x2 == "abc123";

assert |"abc"| == 3;

assert "abc" == "abc";
assert !( "abc" == "123" );

assert !( "abc" != "abc" );
assert "abc" != "123";

}

0 comments on commit 77e9cb2

Please sign in to comment.