summaryrefslogtreecommitdiff
path: root/src/liana/list_cmp.h
blob: 6bc7c6926d42db634a1f1d32aeefbf115c84d6d3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#pragma once

#include <al/str.h>

#include "list.h"

AL_IGNORE_WARNING("-Wunused-function")

static void camu_db_num_from_path(str *path, s64 *id, s64 *index)
{
    u32 last_slash = al_str_rfind(path, '/');
    if (last_slash == AL_WSTR_NO_POS) {
        return;
    }
    str sub = al_str_substr(path, last_slash + 1, path->length);

    // Skip 2 '_' characters.
    if (!(al_str_tok(&sub, '_') && al_str_tok(&sub, '_'))) {
        return;
    }

    u32 target = al_str_find(&sub, '_');
    if (target == AL_WSTR_NO_POS) {
        return;
    }
    sub = al_str_substr(&sub, 0, target);

    bool error;
    s64 num = al_str_to_long(&sub, 10, &error);
    if (error) return;
    *id = num;

    u32 ext_dot = al_str_rfind(path, '.');
    u32 a_of_media = al_str_rfind(path, 'a');
    if (ext_dot == AL_WSTR_NO_POS || a_of_media == AL_WSTR_NO_POS) {
        return;
    }
    sub = al_str_substr(path, a_of_media + 1, ext_dot);

    num = al_str_to_long(&sub, 10, &error);
    if (error) return;
    *index = num;
}

static s32 camu_db_compare(const void *a, const void *b)
{
    struct lia_list_entry *aa = *((struct lia_list_entry **)a);
    struct lia_list_entry *bb = *((struct lia_list_entry **)b);
    s64 a_id = -1, a_index = -1;
    s64 b_id = -1, b_index = -1;
    // Assuming brief is the file path.
    camu_db_num_from_path(&aa->brief, &a_id, &a_index);
    camu_db_num_from_path(&bb->brief, &b_id, &b_index);
    if (a_id == b_id) {
        if (a_index > b_index) return 1;
        else if (a_index < b_index) return -1;
    } else {
        if (a_id > b_id) return 1;
        else if (a_id < b_id) return -1;
    }
    return 0;
}

AL_IGNORE_WARNING_END