1 /**
2 *   Defines utility functions for strings
3 */
4 module dash.utility..string;
5 
6 import std.array, std.traits;
7 
8 // std.string.fromStringz was introduced in https://github.com/D-Programming-Language/phobos/pull/1607
9 static if( __VERSION__ < 2066 )
10 {
11     /**
12      * Returns new string formed from C-style (null-terminated) string $(D msg). Usefull
13      * when interfacing with C libraries. For D-style to C-style convertion use std.string.toStringz.
14      *
15      * Params:
16      *  msg =                 The C string to convert.
17      *
18      * Authors: NCrashed
19      */
20     string fromStringz( const char* msg ) pure nothrow
21     {
22         scope(failure) return "";
23         if( msg is null ) return "";
24 
25         auto buff = appender!(char[]);
26         uint i = 0;
27         while( msg[i] != cast(char)0 )
28         {
29             buff.put(msg[i++]);
30         }
31 
32         return buff.data.idup;
33     }
34     /// Example
35     unittest
36     {
37         char[] cstring = "some string".dup ~ cast(char)0;
38 
39         assert(cstring.ptr.fromStringz == "some string");
40         assert(null.fromStringz == "");
41     }
42 }
43 
44 /**
45  * Replaces each key in replaceMap with it's value.
46  *
47  * Params:
48  *  base =              The string to replace on.
49  *  replaceMap =        The map to use to replace things.
50  *
51  * Returns: The updated string.
52  */
53 T replaceMap( T, TKey, TValue )( T base, TKey[TValue] replaceMap )
54     if( isSomeString!T && isSomeString!TKey && isSomeString!TValue )
55 {
56     scope(failure) return "";
57     if( base is null ) return "";
58 
59     auto result = base;
60 
61     foreach( key, value; replaceMap )
62     {
63         result = result.replace( key, value );
64     }
65 
66     return result;
67 }
68 /// Example
69 unittest
70 {
71     assert( "$val1 $val2 val3".replaceMap( [ "$val1": "test1", "$val2": "test2", "$val3": "test3" ] ) == "test1 test2 val3" );
72 }