Download Reference Manual
The Developer's Library for D
About Wiki Forums Source Search Contact

Ticket #765 (closed enhancement: fixed)

Opened 10 months ago

Last modified 5 months ago

FilePath: head/tail splitting

Reported by: DRK Assigned to: kris
Priority: minor Milestone: 0.99.6
Component: IO Version: 0.99.3 Triller
Keywords: Cc:

Description

It would be handy to be able to easily break a path into "head" and "tail" components. For example: "/a/b/c" -> "/a","b/c", "a/b/c" -> "a","b/c". This can be done by splitting the path on the first separator not in the 0th position.

This method is useful for any kind of iterative "walk" operation on raw path names. For instance, inserting a file into a hierarchy requires that all intermediate folders exist first, which can be efficiently done by repeatedly splitting the path into head & tail until there is only a head left.

If it is efficient to implement, the addition of char[] head() and char[] tail() members would be good. If this is impractical, then I would suggest a void headTail(out char[] head, out char[] tail) method.

A simple free-function implementation of the latter approach:

void headTail(ref FilePath fp, out char[] head, out char[] tail)
{
    return headTail(fp.toUtf8, head, tail);
}

void headTail(char[] path, out char[] head, out char[] tail)
{
    foreach( i,dchar c ; path[1..$] )
        if( c == '/' )
        {
            head = path[0..i+1];
            tail = path[i+2..$];
            return;
        }

    head = path;
    tail = null;
}

unittest
{
    char[] h,t;

    headTail("/a/b/c", h, t);
    assert( h == "/a" );
    assert( t == "b/c" );

    headTail("a/b/c", h, t);
    assert( h == "a" );
    assert( t == "b/c" );

    headTail("a/", h, t);
    assert( h == "a" );
    assert( t == "" );

    headTail("a", h, t);
    assert( h == "a" );
    assert( t == "" );
}

Change History

02/10/08 22:35:00 changed by kris

  • status changed from new to assigned.
  • milestone set to 0.99.6.

04/18/08 01:10:07 changed by kris

  • status changed from assigned to closed.
  • resolution set to fixed.

(In [3445]) fixes #765 :: FilePath?: head/tail splitting

Thanks to DRK for this