KLatin1Literal

Harri Porten porten at kde.org
Sat Apr 3 17:59:41 CEST 2004


Hi,

after some discussion in private and on this list I've changed the design
of the proposed Latin-1 helper class a bit. There are no more publically
accessible member functions and the class (rather a macro now) is
specialized on string literals. Hence the name change.

  if (s == KLatin1Literal("foo") {
  ...
  }

The code can probably easily be enhanced to completely avoid looping over
each character for short strings. I'll give it a test in HEAD.

Harri.
-------------- next part --------------
#include <qstring.h>
#include <stdio.h>
#include <assert.h>

class KLatin1LiteralInternal;
bool operator==(const QString &, const KLatin1LiteralInternal &);

class KLatin1LiteralInternal
{
    friend bool operator==(const QString &, const KLatin1LiteralInternal &);
public:
    KLatin1LiteralInternal(const char* s, size_t l)
        : str(s), len(s ? l : (size_t)-1) { }

private:
    const char* str;
    size_t len;
};

/**
 * A macro for explicit marking of string literals encoded in the ISO
 * 8859-1 character set. Allows for efficient, still (in terms of the
 * chosen encoding) safe comparison with QString instances. To be used
 * like this:
 *
 * \code
 *     QString s = .....
 *     if (s == KLatin1Literal("o")) { ..... }
 * \endcode
 */
#define KLatin1Literal(s) \
    KLatin1LiteralInternal((s), sizeof(s)/sizeof(char)-1)

inline bool operator==(const QString &s1, const KLatin1LiteralInternal &s2)
{
    const QChar* uc = s1.unicode();
    const char* c = s2.str;
    if (!c || !uc)
        return c == (char*)uc;
    size_t l = s2.len;
    if (s1.length() != l)
        return false;
    for (size_t i = 0; i < l; ++i, ++uc, ++c)
        if (uc->unicode() != (uchar)*c)
            return false;
    return true;
}

inline bool operator!=(const QString &s1, const KLatin1LiteralInternal &s2)
{
    return !(s1 == s2);
}

inline bool operator==(const KLatin1LiteralInternal &s1, const QString &s2)
{
    return s2 == s1;
}

inline bool operator!=(const KLatin1LiteralInternal &s1, const QString &s2)
{
    return !(s2 == s1);
}

int main()
{
    assert(QString::null == KLatin1Literal(0));
    assert(QString::null != KLatin1Literal(""));
    assert(QString::fromLatin1("") == KLatin1Literal(""));
    assert(QString::fromLatin1("") != KLatin1Literal(0));
    assert(QString::fromLatin1("x") != KLatin1Literal(""));
    assert(QString::fromLatin1("a") == KLatin1Literal("a"));
    assert(QString::fromLatin1("a") != KLatin1Literal("b"));
    assert(QString::fromLatin1("\xe4") == KLatin1Literal("\xe4"));
    assert(QString::fromUtf8("\xe2\x82\xac") != KLatin1Literal("?"));
    printf("OK\n");
}


More information about the Kde-optimize mailing list