ocarina/core/tags/album.c

118 lines
2.3 KiB
C

/*
* Copyright 2014 (c) Anna Schumaker.
*/
#include <core/string.h>
#include <core/tags/album.h>
static struct database album_db;
static gchar *__album_key(const gchar *name, unsigned int year)
{
return g_strdup_printf("%u/%s", year, name);
}
static struct album *__album_alloc(gchar *name, unsigned int year)
{
struct album *album = g_malloc(sizeof(struct album));
dbe_init(&album->al_dbe, album);
album->al_year = year;
album->al_name = name;
album->al_lower = string_lowercase(album->al_name);
return album;
}
static struct db_entry *album_alloc(const gchar *key)
{
unsigned int year;
gchar *name;
if (sscanf(key, "%u/%m[^\n]", &year, &name) == 1)
name = g_strdup("");
return &__album_alloc(name, year)->al_dbe;
}
static void album_free(struct db_entry *dbe)
{
g_free(ALBUM(dbe)->al_name);
g_free(ALBUM(dbe)->al_lower);
g_free(ALBUM(dbe));
}
static gchar *album_key(struct db_entry *dbe)
{
return __album_key(ALBUM(dbe)->al_name, ALBUM(dbe)->al_year);
}
static struct db_entry *album_read(struct file *file)
{
unsigned int year;
gchar *line, *name;
line = file_readl(file);
if (sscanf(line, "%u %m[^\n]", &year, &name) == 1)
name = g_strdup("");
g_free(line);
return &__album_alloc(name, year)->al_dbe;
}
static void album_write(struct file *file, struct db_entry *dbe)
{
file_writef(file, "%u %s", ALBUM(dbe)->al_year, ALBUM(dbe)->al_name);
}
static const struct db_ops album_ops = {
album_alloc,
album_free,
album_key,
album_read,
NULL,
album_write,
};
void album_db_init()
{
db_init(&album_db, "album.db", true, &album_ops);
db_load_idle(&album_db);
}
void album_db_deinit()
{
db_deinit(&album_db);
}
struct album *album_find(const gchar *name, unsigned int year)
{
gchar *key = __album_key(name, year);
struct album *album = ALBUM(db_find(&album_db, key));
g_free(key);
return album;
}
struct album *album_get(const unsigned int index)
{
return ALBUM(db_at(&album_db, index));
}
int album_compare(struct album *lhs, struct album *rhs)
{
return string_compare(lhs->al_lower, rhs->al_lower);
}
int album_compare_year(struct album *lhs, struct album *rhs)
{
if (lhs->al_year - rhs->al_year == 0)
return album_compare(lhs, rhs);
return lhs->al_year - rhs->al_year;
}
#ifdef CONFIG_TESTING
const struct db_ops *test_album_ops() { return &album_ops; }
#endif /* CONFIG_TESTING */