// Helper for parameters in key-value pair lists that should only appear
// once. Either replaces an existing entry or adds a new entry.
static void ReplaceOrInsertKeyValuePair(KeyValuePairs& kvp, const std::string& key, const std::string& value) {
    assert(kvp.count(key) <= 1);
    KeyValuePairs::iterator it = kvp.find(key);
    if (it != kvp.end())
        it->second = value;
    else
        kvp.insert(KeyValuePairs::value_type(key, value));
}
KeyValuePairs ParseKeyValuePairs(const std::string& encoded) {
    KeyValuePairs result;

    if (encoded.length() == 0) return result;

    // Split by &
    std::size_t last_amp = 0;
    // We can bail when the last one "found" was the end of the string
    while(true) {
        std::size_t next_amp = encoded.find('&', last_amp+1);
        std::string keyval =
            (next_amp == std::string::npos) ?
            encoded.substr(last_amp) :
            encoded.substr(last_amp, next_amp-last_amp);
        result.insert(ParseKeyValuePair(keyval));
        // Track spot after the & so the first iteration works without dealing
        // with -1 index
        last_amp = next_amp+1;

        // Exit condition
        if (next_amp == std::string::npos) break;
    }
    return result;
}