Skip to content

Commit

Permalink
add string.at command (#59)
Browse files Browse the repository at this point in the history
  • Loading branch information
pyroscope committed May 31, 2018
1 parent 4c8018c commit b7b41ea
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
16 changes: 16 additions & 0 deletions patches/command_pyroscope.cc
Original file line number Diff line number Diff line change
Expand Up @@ -593,6 +593,21 @@ torrent::Object cmd_string_len(rpc::target_type target, const torrent::Object::l
}


torrent::Object cmd_string_at(rpc::target_type target, const torrent::Object::list_type& args) {
const std::string& text = string_get_first_arg("at", args);

torrent::Object::list_const_iterator itr = args.begin() + 1;
int64_t pos = 0;
std::string fallback;
if (itr != args.end()) pos = string_get_value_arg("at(pos)", itr);
if (itr != args.end()) fallback = (itr++)->as_string();
if (pos < 0) pos += text.length();
if (pos >= text.length()) return fallback;

return text.substr(pos, 1);
}


torrent::Object cmd_string_substr(rpc::target_type target, const torrent::Object::list_type& args) {
const std::string& text = string_get_first_arg("substr", args);

Expand Down Expand Up @@ -804,6 +819,7 @@ void initialize_command_pyroscope() {
#endif

CMD2_ANY_LIST("string.len", &cmd_string_len);
CMD2_ANY_LIST("string.at", &cmd_string_at);
CMD2_ANY_LIST("string.substr", &cmd_string_substr);
CMD2_ANY_LIST("string.contains", &cmd_string_contains);
CMD2_ANY_LIST("string.contains_i", &cmd_string_contains_i);
Expand Down
13 changes: 13 additions & 0 deletions tests/commands/string.at.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Tests for "string.at"
$ rtxmlrpc --repr string.at '' -- '' 42
''
$ rtxmlrpc --repr string.at '' -- '' 42 'Life, universe, everything'
'Life, universe, everything'
$ rtxmlrpc --repr string.at '' -- 'foobar' 5
'r'
$ rtxmlrpc --repr string.at '' -- 'foobar' 6
''
$ rtxmlrpc --repr string.at '' -- '➀ ➁ ➂ ➃ ➄ ➅ ➆ ➇ ➈' 2 # TODO: UTF8 support
'?'
$ rtxmlrpc --repr string.at '' --
ERROR … <Fault -503: 'string.at needs a string argument!'>
2 changes: 2 additions & 0 deletions tests/commands/string.substr.txt
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,5 @@ $ rtxmlrpc --repr string.substr '' -- '➀ ➁ ➂ ➃ ➄ ➅ ➆ ➇ ➈' 3 2
' ?'
$ rtxmlrpc --repr string.substr '' -- 'for123bar' 3 bad
ERROR …: <Fault -503: 'string.substr(count): junk at end of value: bad'>
$ rtxmlrpc --repr string.substr '' --
ERROR … <Fault -503: 'string.substr needs a string argument!'>

0 comments on commit b7b41ea

Please sign in to comment.