Assembly Language for Beginners

(Jeff_L) #1

3.15. STRINGS TRIMMING


break;
};
return s;
};


int main()
{
// test


// strdup() is used to copy text string into data segment,
// because it will crash on Linux otherwise,
// where text strings are allocated in constant data segment,
// and not modifiable.

printf ("[%s]\n", str_trim (strdup("")));
printf ("[%s]\n", str_trim (strdup("\n")));
printf ("[%s]\n", str_trim (strdup("\r")));
printf ("[%s]\n", str_trim (strdup("\n\r")));
printf ("[%s]\n", str_trim (strdup("\r\n")));
printf ("[%s]\n", str_trim (strdup("test1\r\n")));
printf ("[%s]\n", str_trim (strdup("test2\n\r")));
printf ("[%s]\n", str_trim (strdup("test3\n\r\n\r")));
printf ("[%s]\n", str_trim (strdup("test4\n")));
printf ("[%s]\n", str_trim (strdup("test5\r")));
printf ("[%s]\n", str_trim (strdup("test6\r\r\r")));
};


Theinputargumentisalwaysreturnedonexit, thisisconvenientwhenyouwanttochainstringprocessing
functions, like it has done here in themain()function.


The second part of for() (str_len>0 && (c=s[str_len-1])) is the so called “short-circuit” in C/C++ and
is very convenient [Dennis Yurichev,C/C++ programming language notes1.3.8].


The C/C++ compilers guarantee an evaluation sequence from left to right.


So if the first clause is false after evaluation, the second one is never to be evaluated.


3.15.1 x64: Optimizing MSVC 2013


Listing 3.62: Optimizing MSVC 2013 x64

s$ = 8
str_trim PROC


; RCX is the first function argument and it always holds pointer to the string
mov rdx, rcx
; this is strlen() function inlined right here:
; set RAX to 0xFFFFFFFFFFFFFFFF (-1)
or rax, -1
$LL14@str_trim:
inc rax
cmp BYTE PTR [rcx+rax], 0
jne SHORT $LL14@str_trim
; is the input string length zero? exit then:
test rax, rax
je SHORT $LN15@str_trim
; RAX holds string length
dec rcx
; RCX = s-1
mov r8d, 1
add rcx, rax
; RCX = s-1+strlen(s), i.e., this is the address of the last character in the string
sub r8, rdx
; R8 = 1-s
$LL6@str_trim:
; load the last character of the string:
; jump, if its code is 13 or 10:
movzx eax, BYTE PTR [rcx]
cmp al, 13

Free download pdf