D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 3384 - toArray
Summary: toArray
Status: RESOLVED FIXED
Alias: None
Product: D
Classification: Unclassified
Component: phobos (show other issues)
Version: D2
Hardware: Other Windows
: P2 enhancement
Assignee: Andrei Alexandrescu
URL:
Keywords: patch
Depends on:
Blocks:
 
Reported: 2009-10-09 10:16 UTC by David Simcha
Modified: 2015-06-09 01:29 UTC (History)
1 user (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description David Simcha 2009-10-09 10:16:21 UTC
Phobos needs an easy, efficient way of converting an arbitrary finite range into an array, for example to allow for eager evaluation.  Below is a proposed solution.  It relies on the existence of newVoid().  (See Bugzilla 3383.)

/**Converts any range to an array on the GC heap by the most efficient means
 * available.  If it is already an array, duplicates the range.*/
Unqual!(ElementType!(T))[] toArray(T)(T range) if(isInputRange!(T)) {
    static if(isArray!(T)) {
        // Allow fast copying by assuming that the input is an array.
        return range.dup;
    } else static if(hasLength!(T)) {
        // Preallocate array, then copy.
        auto ret = newVoid!(Unqual!(ElementType!(T)))(range.length);
        static if(is(typeof(ret[] = range[]))) {
            ret[] = range[];
        } else {
            size_t pos = 0;
            foreach(elem; range) {
                ret[pos++] = elem;
            }
        }
        return ret;
    } else {
        // Don't have length, have to use appending.
        Unqual!(ElementType!(T))[] ret;
        auto app = appender(&ret);
        foreach(elem; range) {
            app.put(elem);
        }
        return ret;
    }
}
Comment 1 David Simcha 2009-11-19 19:43:42 UTC
I was looking through std.array for unrelated reasons and noticed that there is an array() function already in there.  I have no idea when that was added, but it solves this bug.
Comment 2 Andrei Alexandrescu 2009-11-19 20:07:28 UTC
Thanks!