SongSort.cxx 2.54 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2021 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
 * http://www.musicpd.org
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

20
#include "SongSort.hxx"
21
#include "Song.hxx"
22
#include "tag/Tag.hxx"
23
#include "lib/icu/Collate.hxx"
24 25

#include <stdlib.h>
26

27
static int
28
compare_utf8_string(const char *a, const char *b) noexcept
29
{
30 31
	if (a == nullptr)
		return b == nullptr ? 0 : -1;
32

33
	if (b == nullptr)
34 35
		return 1;

36
	return IcuCollate(a, b);
37 38 39 40
}

/**
 * Compare two string tag values, ignoring case.  Either one may be
41
 * nullptr.
42 43
 */
static int
44
compare_string_tag_item(const Tag &a, const Tag &b, TagType type) noexcept
45
{
46 47
	return compare_utf8_string(a.GetValue(type),
				   b.GetValue(type));
48 49
}

50 51
/**
 * Compare two tag values which should contain an integer value
52
 * (e.g. disc or track number).  Either one may be nullptr.
53 54
 */
static int
55
compare_number_string(const char *a, const char *b) noexcept
56
{
57 58
	long ai = a == nullptr ? 0 : strtol(a, nullptr, 10);
	long bi = b == nullptr ? 0 : strtol(b, nullptr, 10);
59 60 61 62 63 64 65 66 67 68 69

	if (ai <= 0)
		return bi <= 0 ? 0 : -1;

	if (bi <= 0)
		return 1;

	return ai - bi;
}

static int
70
compare_tag_item(const Tag &a, const Tag &b, TagType type) noexcept
71
{
72 73
	return compare_number_string(a.GetValue(type),
				     b.GetValue(type));
74 75
}

76
/* Only used for sorting/searchin a songvec, not general purpose compares */
77 78
gcc_pure
static bool
79
song_cmp(const Song &a, const Song &b) noexcept
80
{
81 82
	int ret;

83
	/* first sort by album */
84
	ret = compare_string_tag_item(a.tag, b.tag, TAG_ALBUM);
85
	if (ret != 0)
86
		return ret < 0;
87 88

	/* then sort by disc */
89
	ret = compare_tag_item(a.tag, b.tag, TAG_DISC);
90
	if (ret != 0)
91
		return ret < 0;
92 93

	/* then by track number */
94
	ret = compare_tag_item(a.tag, b.tag, TAG_TRACK);
95
	if (ret != 0)
96
		return ret < 0;
97 98

	/* still no difference?  compare file name */
99
	return IcuCollate(a.filename, b.filename) < 0;
100 101
}

102
void
103
song_list_sort(SongList &songs) noexcept
104
{
105
	songs.sort(song_cmp);
106
}