From: stephan b. <st...@s1...> - 2004-12-26 13:13:59
|
Okay, i needed some string util code for the App layer, and wanted to move some out of ps11n, so i finally went ahead and ported the string util code into Util/StringTool. It is namespace P::StringTool, encapsulating several commonly-useful string operations. Some of these will be especially useful for P, e.g. translateEntities(). i didn't call it Util::String, because that would mislead people to think it's only for the Unicode::String class. The name StringUtil has the same problem. Okay, maybe StringTool does as well :/. i'm open to suggestions for new names. Consider the problem of encoding URLs. e.g: "http://foo/?foo=bar bar bar" ==> "http://foo/?foo=bar%20bar%20bar" With translateEntities() encoding and decoding are trivial and generic: map<string,string> map; map[" "] = "%20"; map["..."] = "..."; // usw... encode: string u = "http://foo/?foo=bar bar bar"; StringTool::translateEntities( u, map ); // ^^^ modifies u in-place decode: StringTool::translateEntities( u, map, true ); // ^^^ 'true' == do reverse mapping All of s11n's serializers use this simple approach to do their, e.g. XML entity translation/escaping. By serving the translation maps through Phoenix, we ensure a) they are not populated until they're actually used and b) if they're called post-main() they get repopulated with the translations. Another useful func is expandDollarRefs(): map["HOME"] = getenv("HOME"); string foo = expandDollarRefs( "${HOME}/.myconfig", map ); or: foo = "${HOME}/.myconfig"; expandDollarRefsInline( foo, map ); // edits foo in-place Then, of course, there's the well-overused lexical casting: string s = StringTool::to(myobj); // tostring MyType m = StringTool::from("value"); // fromstring There's a small demo under test/StringToolTest.cpp: tringToolTest.cpp:18 : StringTool tests... StringToolTest.cpp:29 : string: [this $bar is a ${foo} input ${bar}. $UNMAPPED_VAR, \ \ \\ ${} $ \$ escaped \${foo}.] expanded: [this BARBAR is a FOOFOO input BARBAR. $UNMAPPED_VAR, \ \ \\ ${} $ $ escaped ${foo}.] StringToolTest.cpp:33 : escaped string: [this \$bar is a \${foo} input \${bar}. \$UNMAPPED_VAR, \ \ \\ \${} \$ \\$ escaped \\${foo}.] pre-escaped, expanded: [this $bar is a ${foo} input ${bar}. $UNMAPPED_VAR, \ \ \\ ${} $ \$ escaped \${foo}.] StringToolTest.cpp:46 : reference string=[this is a '<"test string">'. $GOODGRIEF!] StringToolTest.cpp:48 : 7 translated: [this is a '<"test string">'. excellent!] StringToolTest.cpp:50 : 7 reverse translated: [this is a '<"test string">'. $GOODGRIEF!] -- ----- st...@s1... http://s11n.net "...pleasure is a grace and is not obedient to the commands of the will." -- Alan W. Watts |