resizeable arrays: T[new]

Reiner Pope some at address.com
Wed Jun 6 23:50:45 PDT 2007


Sean Kelly wrote:
  > Okay, that makes sense.  So I'm not sure I entirely understand the
> problem with resizing even mutable array in place.  Could this just be 
> an instance where documentation is indeed sufficient?  I can't think of 
> a situation where I would actually pass a slice of a buffer to a routine 
> that may grow that buffer when writing to it--it just doesn't make any 
> sense from a use perspective.  Is this something that we really need to 
> add const features to check?

I don't know if this helps, but currently the following code behaves 
unexpectedly with version=bad

> import std.stdio;
> 
> void main()
> {
>     char[] data = "1 50.0 60".dup;
> 
>     writefln( data[0..1].withDecimals() );
>     writefln( data );                      // with version=bad prints "1.00.0 60" instead of "1 50.0 60"
>     writefln( data[2..6].withDecimals() );
>     writefln( data[7..$].withDecimals() );
> }
> 
> char[] withDecimals(char[] num)
> {
>     foreach (i, c; num)
>         if (c == '.')
>             return num;
> 
> version(bad)
> {
>     num ~= ".0";
>     return num;
> }
> else
> {
>     return (num ~ ".0");
> }
> 
> }      

I'm not sure what the suggested rewrite of this would be. To avoid 
unnecessary dup'ing, perhaps:

> 
> private char[new] withDecimals(char[new] num, bool needsDup)
> {
>     foreach (i, c; num)
>         if (c == '.')
>             return num;
> 
>     if (needsDup)
>         num = num.dup;
>     num ~= ".0";
>     return num;
> }
> 
> char[new] withDecimals(char[new] num)
> {
>     return withDecimals(num, false);
> }
> 
> char[] withDecimals(char[] num)
> {
>     return withDecimals(cast(char[new])num, true)
> }
>  

    -- Reiner



More information about the Digitalmars-d-announce mailing list