Comparison and Sorting

Comparison and Sorting

If the result of the compare is not visible to the user for example, if you're generating an internal hash table from the string consider using binary order. It's safe, fast, and stable. If the result of the compare is not visible to the user but binary order is unacceptable (the most common reason being case folding, which is outlined at http://www.unicode.org/unicode/reports/tr21), use the Invariant locale, LOCALE_INVARIANT, on Windows XP or the invariant culture in a managed code application.

int nResult = CompareString( LOCALE_INVARIANT, NORM_IGNORECASE NORM_IGNOREKANATYPE NORM_IGNOREWIDTH, lpStr1, -1, lpStr2, -1 );

If your code must run on platforms older than Windows XP, use the US English Locale. On Windows XP, CompareString results will then be identical to those with LOCALE_INVARIANT although Microsoft does not guarantee this to be true with future operating system releases.

int nResult = CompareString( MAKELCID(MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT), SORT_DEFAULT), NORM_IGNORECASE NORM_IGNOREKANATYPE NORM_IGNOREWIDTH, lpStr1, -1, lpStr2, -1 );

You should also assume a locale-sensitive compare is random. A frequent cause of errors, some of which pose security threats, is code that makes invalid assumptions about comparisons. In particular, for existing Windows locales:

  • A to Z might not always sort as in English.

  • When ignoring case, I might not always compare equal with i.

  • A might not always come after a.

  • Latin characters might not always precede other scripts.

Windows will support locales in the future that will include even more differences (or exceptions). If your code uses the user's locale to compare, assume the result will be random. If this is unacceptable, seriously consider using the Invariant locale.



Writing Secure Code
Writing Secure Code, Second Edition
ISBN: 0735617228
EAN: 2147483647
Year: 2001
Pages: 286

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net