1 /** 2 * Copyright: © 2012-2014 Anton Gushcha 3 * License: Subject to the terms of the MIT license, as written in the included LICENSE file. 4 * Authors: NCrashed <ncrashed@gmail.com> 5 */ 6 module ant.util; 7 8 /// fromStringz 9 /** 10 * Returns new string formed from C-style (null-terminated) string $(D msg). Usefull 11 * when interfacing with C libraries. For D-style to C-style convertion use std.string.toStringz 12 * 13 * Example: 14 * ---------- 15 * char[] cstring = "some string".dup ~ cast(char)0; 16 * 17 * assert(fromStringz(cstring.ptr) == "some string"); 18 * ---------- 19 */ 20 string fromStringz(const char* msg) nothrow 21 { 22 try 23 { 24 if(msg is null) return ""; 25 26 auto buff = new char[0]; 27 uint i = 0; 28 while(msg[i]!=cast(char)0) 29 buff ~= msg[i++]; 30 return buff.idup; 31 } catch(Exception e) 32 { 33 return ""; 34 } 35 } 36 37 unittest 38 { 39 char[] cstring = "some string".dup ~ cast(char)0; 40 41 assert(fromStringz(cstring.ptr) == "some string"); 42 }