Better_Software_Header_MobileBetter_Software_Header_Web

Find what you need - explore our website and developer resources

QStringView Diaries: The Eagle Has Landed

QStringView merged for Qt 5.10


bool isValidIdentifier(const QChar *data, int len) {
    if (!data || len <= 0)
        return false;
    if (!data->isLetter())
        return false;
    --len;
    ++data;
    while (len) {
        if (!data->isLetterOrNumber())
            return false;
        ++data;
        --len;
    }
    return true;
}

bool isValidIdentifier(QStringView id) noexcept {
    if (id.isEmpty())
        return false;
    if (!id.front().isLetter())
        return false;
    for (QChar ch : id.mid(1)) {
        if (!ch.isLetterOrNumber())
            return false;
    }
    return true;
}

bool isValidIdentifier(QStringView id);
isValidIdentifier(u"QString");                // OK
isValidIdentifier(L"QString");                // OK (on Windows only)
isValidIdentifier(QStringLiteral("QString")); // OK
QString fun = "QString::left()";
isValidIdentifier(fun.leftRef(7));            // OK
isValidIdentifier(u"QString"s);               // OK
isValidIdentifier(L"QString"s);               // OK (on Windows only)

QString s = ...;
for (QStringView part : QStringTokenizer(s, u'\n'))
    use(part);

18 Comments

6 - Apr - 2017

Jon Hanish

6 - Apr - 2017

Marc Mutz

6 - Apr - 2017

Michał Małek

6 - Apr - 2017

Marc Mutz

10 - Apr - 2017

Flavio

10 - Apr - 2017

Marc Mutz

7 - Apr - 2017

Jon Hanish

7 - Apr - 2017

Marc Mutz

7 - Apr - 2017

bartek

7 - Apr - 2017

Marc Mutz

28 - Apr - 2017

Frerich Raabe

28 - Apr - 2017

Marc Mutz

auto id = u"Hello";
if (isValidIdentifier(cast...(id), 15)) // ERROR: precondition violation
                                        // [ptr, len) is not a valid range
auto sv = QStringView{u"Hello", 15}; // ERROR: precondition violation
                                     // [ptr, len) is not a valid range
auto id = u"Hello";
if (isValidIdentifier(QStringView(id, 15)) // ERROR: precondition violation
                                           // [ptr, len) is not a valid range
                                           // _while constructing QStringView_!

5 - May - 2017

Marc Mutz

8 - May - 2017

Frerich Raabe

QChar firstCharacter( const QString &s ) {
  return s[0]; // Oops - what if it's an empty string?
}
struct NonEmptyString {
  QString value;
  NonEmptyString( const QString &s ) {
    if ( s.isEmpty() ) {
      throw std::logic_error( "empty string passed" );
    }
  }
};

QChar firstCharacter( const NonEmptyString &s ) {
  return s.value[0]; // Fine - no NonEmptyString object ever exists having an empty value member
}

9 - May - 2017

Marc Mutz

11 - May - 2017

Frerich Raabe

  template <typename Iterator>
  struct Range {
    Iterator start;
    Iterator end;
  };

15 - May - 2017

Marc Mutz

11 - May - 2017

Frerich Raabe