1 module osc.oscstring; 2 3 import std.range; 4 import std.conv; 5 import std.algorithm; 6 7 8 private T addNullSuffix( T:string )( T str ) 9 { 10 return str ~ ('\0' 11 .repeat( 4 - str.length % 4 ) 12 .map!( c => cast(immutable(char)) c ) 13 .array); 14 } 15 16 private T addNullSuffix( T:ubyte[] )( T str ) 17 { 18 return cast(T) addNullSuffix( cast(string) str ); 19 } 20 21 22 23 /// Converts a string to an OSC string. 24 /// 25 ubyte[] toOSC( string str ) 26 { 27 return str 28 .addNullSuffix 29 .map!( c => c.to!char.to!ubyte ) 30 .array; 31 } 32 33 /// Converts an OSC string to a string. 34 /// 35 string fromOSC( ubyte[] str ) 36 { 37 return str 38 .stripRight( 0 ) 39 .map!( c => c.to!char) 40 .to!string; 41 } 42 43 44 45 unittest 46 { 47 assert("osc".addNullSuffix == "osc\0"); 48 assert("data".addNullSuffix == "data\0\0\0\0"); 49 assert(",iisff".addNullSuffix == ",iisff\0\0"); 50 assert(",i".addNullSuffix == ",i\0\0"); 51 } 52 53 unittest 54 { 55 assert( "osc".toOSC == 56 ['o', 's', 'c', 0] ); 57 assert( "data".toOSC == 58 ['d', 'a', 't', 'a', 0, 0, 0, 0] ); 59 assert( ",iisff".toOSC == 60 [',', 'i', 'i', 's', 'f', 'f', 0, 0] ); 61 assert( ",i".toOSC == 62 [',', 'i', 0, 0] ); 63 }