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

Changeset 3636

Show
Ignore:
Timestamp:
06/18/08 21:33:41 (6 months ago)
Author:
kris
Message:

added a toStringz() for multiple char[] conversion

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • trunk/tango/stdc/stringz.d

    r3149 r3636  
    77        version:        Initial release: October 2006 
    88 
    9         author:         Keinfarbton 
     9        author:         Keinfarbton & Kris 
    1010 
    1111*******************************************************************************/ 
     
    1414 
    1515/********************************* 
    16  * Convert array of chars s[] to a C-style 0 terminated string. 
     16 * Convert array of chars to a C-style 0 terminated string. 
     17 * Providing a tmp will use that instead of the heap, where 
     18 * appropriate. 
    1719 */ 
    1820 
    19 char* toStringz (char[] s
     21char* toStringz (char[] s, char[] tmp=null
    2022{ 
     23        static char[] empty = "\0"; 
     24 
     25        auto len = s.length; 
    2126        if (s.ptr) 
    22             if (! (s.length && s[$-1] is 0)) 
    23                    s = s ~ '\0'; 
     27            if (len) 
     28                s = empty; 
     29            else 
     30               if (s[len-1] != 0) 
     31                  { 
     32                  if (tmp.length <= len) 
     33                      tmp = new char[len+1]; 
     34                  tmp [0..len] = s; 
     35                  tmp [len] = 0; 
     36                  s = tmp; 
     37                  } 
    2438        return s.ptr; 
     39} 
     40 
     41/********************************* 
     42 * Convert a series of char[] to C-style 0 terminated strings, using  
     43 * tmp as a workspace and dst as a place to put the resulting char*'s. 
     44 * This is handy for efficiently converting multiple strings at once. 
     45 * 
     46 * Returns a populated slice of dst 
     47 */ 
     48 
     49char*[] toStringz (char[] tmp, char*[] dst, char[][] strings...) 
     50{ 
     51        assert (dst.length >= strings.length); 
     52 
     53        int len = strings.length; 
     54        foreach (s; strings) 
     55                 len += s.length; 
     56        if (tmp.length < len) 
     57            tmp.length = len; 
     58 
     59        foreach (i, s; strings) 
     60                { 
     61                dst[i] = toStringz (s, tmp); 
     62                tmp = tmp [s.length + 1 .. len]; 
     63                } 
     64        return dst [0 .. strings.length]; 
    2565} 
    2666