libimobiledevice / libplist

A library to handle Apple Property List format in binary or XML
https://libimobiledevice.org
GNU Lesser General Public License v2.1
532 stars 304 forks source link

It is recommended to add a function void dict_sort(plist_t pl) #209

Closed xdeng closed 1 year ago

xdeng commented 2 years ago
typedef struct _psi{
    string key;
    plist_t item;
}psi;

bool compare_psi(const psi &first, const psi &second)
{
    return first.key < second.key;
}

void dict_sort(plist_t pl)
{
    if(plist_get_node_type(pl) != PLIST_DICT)
        return;

    list<psi> ls;
    plist_dict_iter iter = NULL;
    plist_dict_new_iter(pl, &iter);
    if (iter) {
        char *key = NULL;
        plist_t node = NULL;
        plist_dict_next_item(pl, iter, &key, &node);
        while (node) {
            plist_type nt = plist_get_node_type(node);
            if(nt == PLIST_DICT)
                dict_sort(node);
            psi i;
            i.key = key;
            i.item = plist_copy(node);
            ls.push_front(i);
            free(key);
            plist_dict_next_item(pl, iter, &key, &node);
        }
        free(iter);
    }

    ls.sort(compare_psi);

    list<psi>::iterator it;
    for (it = ls.begin(); it != ls.end(); ++it)
    {
        plist_dict_remove_item(pl, it->key.c_str());
        plist_dict_set_item(pl, it->key.c_str(), it->item);
    }
}

similar to this

nikias commented 1 year ago

I implemented it with https://github.com/libimobiledevice/libplist/commit/706771e357570d1bee268fc7c2233506da967bcd and follow up commit https://github.com/libimobiledevice/libplist/commit/52826a6c229ed3e353d4dae711a6c52a96d99764