1 module des.util.stdext..string;
2 
3 public import std..string;
4 import std.array;
5 import std.algorithm;
6 
7 import des.util.data.type : ArrayData, AlienArray;
8 
9 @trusted pure
10 {
11     ///
12     string toSnakeCase( in string str, bool ignore_first=true ) @property
13     {
14         string[] buf;
15         buf ~= "";
16         foreach( i, ch; str )
17         {
18             if( [ch].toUpper == [ch] ) buf ~= "";
19             buf[$-1] ~= [ch].toLower;
20         }
21         if( buf[0].length == 0 && ignore_first )
22             buf = buf[1..$];
23         return buf.join("_");
24     }
25 
26     ///
27     string toCamelCaseBySep( in string str, string sep="_", bool first_capitalize=true )
28     {
29         auto arr = array( filter!"a.length > 0"( str.split(sep) ) );
30         string[] ret;
31         foreach( i, v; arr )
32         {
33             auto bb = v.capitalize;
34             if( i == 0 && !first_capitalize )
35                 bb = v.toLower;
36             ret ~= bb;
37         }
38         return ret.join("");
39     }
40 
41     ///
42     string toCamelCase( in string str, bool first_capitalize=true ) @property
43     { return toCamelCaseBySep( str, "_", first_capitalize ); }
44 
45     /// copy chars to string
46     string toDString( const(char*) c_str ) nothrow
47     {
48         if( c_str is null ) return "";
49         char *ch = cast(char*)c_str;
50         size_t n;
51         while( *ch++ != '\0' ) n++;
52         return AlienArray!char( ArrayData( n, cast(void*)c_str ) ).arr.idup;
53     }
54 
55     /// ditto
56     string toDStringFix(size_t S)( const(char[S]) c_buf ) nothrow
57     {
58         size_t n;
59         foreach( c; c_buf )
60         {
61             if( c == '\0' ) break;
62             n++;
63         }
64         return AlienArray!char( ArrayData( n, cast(void*)c_buf.ptr ) ).arr.idup;
65     }
66 }
67 
68 ///
69 unittest
70 {
71     assert( "someVar".toSnakeCase == "some_var" );
72     assert( "SomeVar".toSnakeCase == "some_var" );
73     assert( "SomeVar".toSnakeCase(false) == "_some_var" );
74     assert( "ARB".toSnakeCase == "a_r_b" );
75     assert( "ARB".toSnakeCase(false) == "_a_r_b" );
76 }
77 
78 ///
79 unittest
80 {
81     assert( "some_class".toCamelCase == "SomeClass" );
82     assert( "_some_class".toCamelCase == "SomeClass" );
83     assert( "some_func".toCamelCase(false) == "someFunc" );
84     assert( "_some_func".toCamelCase(false) == "someFunc" );
85     assert( "a_r_b".toCamelCase == "ARB" );
86     assert( toCamelCase( "program_build" ) == "ProgramBuild" );
87     assert( toCamelCaseBySep( "single-precision-constant", "-", false ) == "singlePrecisionConstant" );
88 }