const and phobos string functions
Kirk McDonald
kirklin.mcdonald at gmail.com
Wed Aug 1 12:48:07 PDT 2007
Regan Heath wrote:
> I wanted to post this real/concrete case of where 'const' and the
> current phobos implementation of certain string routines combine to
> cause a few irritations, inefficiencies and some IMO illogical behaviour.
>
> Note in the code below 'remove' is a template function which uses
> 'memmove' to remove an item from the array.
>
> (The code):
>
> char[][] tmp;
>
> tmp = cast(char[][])splitlines(cast(string)read(a[3..$]));
> foreach(ref line; tmp) line = cast(char[])strip(line);
> for(int i = 0; i < tmp.length; i++)
> {
> if (tmp[i].length == 0)
> tmp.remove(i);
> }
>
> (The problem):
>
> Notice all the cast()'s required above. I am of the belief that casting
> should only be done in exceptional circumstances, and this shouldn't be
> one of them.
>
> If you consider char[] as being a a string which you are the full owner
> of, you can change it at will, and 'string' as being a string which you
> are not the full owner of, as you can only read it then in many cases it
> doesn't make sense to pass a char[] to a function and get a 'string'
> back, unless the function has 'taken ownership' of the string data or is
> returning different string data which you are not the owner of.
>
> The obvious case where it make sense is a property setter which might
> copy the input and return a 'string' reference to the copy.
>
> In the cases above (splitlines, strip) it doesn't make sense for the
> function to 'take ownership' of the strings as they do not store them
> beyond the lifetime of the function call.
>
> Therefore if passed a char[] they should return char[][] and char[]
> respectively.
>
> Of course if passed 'string' they should return 'string[]' and 'string'
> respectively.
>
> (The solution):
>
> Given the requirements it seems templating is the obvious solution. I
> have described in earlier posts (though these relate to tolower
> specifically):
>
> http://www.digitalmars.com/webnews/newsgroups.php?art_group=digitalmars.D&article_id=55335
>
> http://www.digitalmars.com/webnews/newsgroups.php?art_group=digitalmars.D&article_id=55337
>
>
> All the phobos routines should likely be templated in the same fashion.
>
> Regan
A lot of those casts go away if tmp is a string[].
--
Kirk McDonald
http://kirkmcdonald.blogspot.com
Pyd: Connecting D and Python
http://pyd.dsource.org
More information about the Digitalmars-d
mailing list