2
\$\begingroup\$

The following code is from a utility I've written for myself.

It takes a file in this format:

 [SOME_CODE]
 Some following text
 [SOME_OTHER_CODE]
 Some following multi-line
 text

And then outputs a C header file containing some #defines with the strings encoded.

The bottom function, convert, is the one I'm scratching my head about. It works just fine, but I'm sure there's a better way of organising the loop. Performance isn't a great issue here, just maintainability. It doesn't have to be super-resilient to unexpected input either. It uses JUCE - hence the non-std string class and file operations.

bool isShortCode(const String & stringToCheck)
{
    return (stringToCheck.length() > 1) && (stringToCheck[0] == '[');
}

String getEncodedDefineAndComment(const String & shortCode, const String & originalText)
{
    String t;
    t += "\n";
    t += "// " + originalText.replace("\n", "\\n") + "\n";
    t += "#define JCF_ENCODED_" + shortCode + " " + getDefineForString(originalText) + "\n";
    return t;
}

void convert(File inFile, File outFile)
{
    auto inString = inFile.loadFileAsString();

    if (inString.isEmpty())
    {
        cout << "error reading input" << endl;
        return;
    }

    auto inLines = StringArray::fromLines(inString);
    String shortCode;
    String text;
    String outputText;

    auto p = inLines.begin();

    while (p != inLines.end())
    {
        String s = *p;

        if (isShortCode(s))
        {
            shortCode = s.removeCharacters("[] ");
            text = String::empty;
            p++;
        }
        else
        {
            if (shortCode.isEmpty())
            {
                cout << "error: input must start with a shortcode" << endl;
                return;
            }

            bool firstTime = true;

            while ((p != inLines.end()) && (! isShortCode(*p)))
            {
                // I only want a new line where there are multiple lines.  I don't want one for the last line.
                if (! firstTime)
                {
                    text += "\n";
                    firstTime = false;
                }

                text += *p;
                p++;
            }
            outputText += getEncodedDefineAndComment(shortCode, text);
        }
    }

    // Happy to assume no errors here.
    outFile.replaceWithText(outputText);
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.