V2 string

Regan Heath regan at netmail.co.nz
Fri Jul 6 01:56:49 PDT 2007


Proof of concept.

Only duplicate when the input is 'string' allowing for more efficient 
handling of char[] parameters and allowing callers to pass mutable 
char[] parameter, recieve the result as a mutable char[] and avoid 
future dup calls on the returned data.

Output:
sStringM: 0x  416080 becomes 0x  880FD0 DUP
sCharM  : 0x  880FE0 becomes 0x  880FE0 SAME
sString : 0x  416110 becomes 0x  416110 SAME
sChar   : 0x  880FC0 becomes 0x  880FC0 SAME


Code:
# /*
#  * Common Public License Version 1.0
#  * http://www.opensource.org/licenses/cpl1.0.php
#  */
# import std.stdio;
#
# void main()
# {
# 	string sStringM = "tEsT";
# 	char[] sCharM = sStringM.dup;
# 	string rStringM = .tolower(sStringM);
# 	char[] rCharM = .tolower(sCharM);
# 	
# 	writefln("sStringM: 0x%08x becomes 0x%08x %s", sStringM.ptr, 
rStringM.ptr, (sStringM.ptr!=rStringM.ptr)?"DUP":"SAME");
# 	writefln("sCharM  : 0x%08x becomes 0x%08x %s", sCharM.ptr, 
rCharM.ptr, (sCharM.ptr!=rCharM.ptr)?"DUP":"SAME");
#
# 	string sString = "test";
# 	char[] sChar = sString.dup;
# 	string rString = .tolower(sString);
# 	char[] rChar = .tolower(sChar);
#
# 	writefln("sString : 0x%08x becomes 0x%08x %s", sString.ptr, 
rString.ptr, (sString.ptr!=rString.ptr)?"DUP":"SAME");
# 	writefln("sChar   : 0x%08x becomes 0x%08x %s", sChar.ptr, rChar.ptr, 
(sChar.ptr!=rChar.ptr)?"DUP":"SAME");
# }
#
# T tolower(T)(T s)
# {
#     bool changed;
#     char[] r;
#
#     if (is(typeof(s) == char[]))
#     {
#     	changed = true;
#     	r = cast(char[])s;
#     }
#
#     for (size_t i = 0; i < s.length; i++)
#     {
# 	auto c = s[i];
# 	if ('A' <= c && c <= 'Z')
# 	{
# 	    if (!changed)
# 	    {
# 		r = s.dup;
# 		changed = true;
# 	    }
# 	    r[i] = cast(char) (c + (cast(char)'a' - 'A'));
# 	}
# 	else if (c >= 0x7F)
# 	{
# 	    foreach(size_t j, dchar dc; s[i .. length])
# 	    {
# 		if (std.uni.isUniUpper(dc))
# 		{
# 		    dc = std.uni.toUniLower(dc);
# 		    if (!changed)
# 		    {
# 			r = s[0 .. i + j].dup;
# 			changed = true;
# 		    }
# 		}
# 		if (changed)
# 		{
# 		    if (r.length != i + j)
# 			r = r[0 .. i + j];
# 		    std.utf.encode(r, dc);
# 		}
# 	    }
# 	    break;
# 	}
#     }
#     return changed ? r : s;
# }



More information about the Digitalmars-d mailing list