Skip to content

Commit

Permalink
Merge pull request #356 from wonja/str_len_func
Browse files Browse the repository at this point in the history
adding string length built-in function
  • Loading branch information
Aaron Leung committed May 16, 2014
2 parents 983aa9e + 1e98e20 commit cd3ee1c
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
1 change: 1 addition & 0 deletions context.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -361,6 +361,7 @@ namespace Sass {
// String Functions
register_function(ctx, unquote_sig, sass_unquote, env);
register_function(ctx, quote_sig, sass_quote, env);
register_function(ctx, str_length_sig, str_length, env);
// Number Functions
register_function(ctx, percentage_sig, percentage, env);
register_function(ctx, round_sig, round, env);
Expand Down
36 changes: 36 additions & 0 deletions functions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -689,6 +689,42 @@ namespace Sass {
return result;
}


Signature str_length_sig = "str-length($string)";
BUILT_IN(str_length)
{
String_Constant* s = ARG("$string", String_Constant);
string str = s->value();
size_t len = 0;
size_t length_of_s = str.size();
size_t i = 0;

if (s->is_quoted()) {
++i;
--length_of_s;
}

while (i < length_of_s) {
unsigned char c = static_cast<unsigned char>(str[i]);
if (c < 128) {
// it's a single-byte character
++len;
++i;
}
// it's a multi bit sequence and presumably it's a leading bit
else {
++i; // go to the next byte
// see if it's still part of the sequence
while ((i < length_of_s) && ((static_cast<unsigned char>(str[i]) & 0b11000000) == 0b10000000)) {
++i;
}
// when it's not [aka a new leading bit], increment and move on
++len;
}
}
return new (ctx.mem) Number(path, position, len);
}

///////////////////
// NUMBER FUNCTIONS
///////////////////
Expand Down
2 changes: 2 additions & 0 deletions functions.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ namespace Sass {
extern Signature ie_hex_str_sig;
extern Signature unquote_sig;
extern Signature quote_sig;
extern Signature str_length_sig;
extern Signature percentage_sig;
extern Signature round_sig;
extern Signature ceil_sig;
Expand Down Expand Up @@ -115,6 +116,7 @@ namespace Sass {
BUILT_IN(ie_hex_str);
BUILT_IN(sass_unquote);
BUILT_IN(sass_quote);
BUILT_IN(str_length);
BUILT_IN(percentage);
BUILT_IN(round);
BUILT_IN(ceil);
Expand Down

0 comments on commit cd3ee1c

Please sign in to comment.