0

QStringクラスを理解するための演習として、単純なQtBencodeパーサーを作成しています

私の現在のアプローチでは、スキャナーのように動作するBencodeオブジェクトを作成し、文字列ポインター(pos)を段階的に進めることで解析します。その結果、次のようなコードになります( bEncodedBencode QString)。

void Bencode::parseInteger() {
    qDebug() << "Parsing an Integer";

    if(bEncoded.at(pos) != intChar) {
        qDebug() << "No leading i for integer";
        return;
    }
    pos++;
    QString buf;
    if(bEncoded.at(pos).isNumber() || bEncoded.at(pos) == negChar) {
        buf.append(bEncoded.at(pos));
        pos++;
    }
    while(bEncoded.at(pos).isNumber()) {
        buf.append(bEncoded.at(pos));
        pos++;
    }
    if(!bEncoded.at(pos).unicode() == 'e') {
        qDebug() << "No training e for integer";
        return;
    }
    pos++;
    qDebug("Integer: %i", buf.toInt());
}

これは簡潔なアプローチかどうか疑問に思います。私が虐待QString::at()しているようですQChar==。私がそれを見ると、正規表現はもっと簡潔になるかもしれないと思いますが、ここでもいくつかの意見を求めると思いました。

では、このアプローチをどのように改善できるでしょうか。

ここにあるすべてのコード:https ://github.com/jif/Bencode

4

1 に答える 1

0

ですから、メモリをあまり消費しないアプローチを見つけたと思います。QCharをあちこちに作成して比較する代わりに、QString :: mid()を使用してサブストリングを抽出できます。たとえば、整数パーサーは次のようになります。

int Bencode::parseInteger() {
    qDebug() << "Parsing an Integer";

    // Validate the integer
    if(currentChar() != intChar) {
        qDebug() << "No leading i for integer";
        return 0;
    }
    pos++;
    int len = bEncoded.indexOf(endChar,pos)-pos;
    if(len>0) {
        int intBuf = bEncoded.mid(pos,len).toInt();
        qDebug("Integer: %i", intBuf);
        pos = pos+len+1;
        return intBuf;
    } else {
        qDebug("Integer sytax error at %i",pos);
        return 0;
    }
}

私にはもっと簡潔に見えます:)

于 2013-03-24T19:34:23.293 に答える