Blob: timeout-glib.c

Blob id: 3268d480c3a704b08b41250c763dbc6717eddc8e

Size: 1.8 KB

  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
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
// SPDX-License-Identifier: LGPL-2.1-or-later
/*
 *
 *  BlueZ - Bluetooth protocol stack for Linux
 *
 *  Copyright (C) 2014  Intel Corporation. All rights reserved.
 *
 *
 */

#include "timeout.h"

#include <glib.h>

struct timeout_data {
	timeout_func_t func;
	timeout_destroy_func_t destroy;
	void *user_data;
};

static gboolean timeout_callback(gpointer user_data)
{
	struct timeout_data *data  = user_data;

	if (data->func(data->user_data))
		return TRUE;

	return FALSE;
}

static void timeout_destroy(gpointer user_data)
{
	struct timeout_data *data = user_data;

	if (data->destroy)
		data->destroy(data->user_data);

	g_free(data);
}

unsigned int timeout_add(unsigned int timeout, timeout_func_t func,
			void *user_data, timeout_destroy_func_t destroy)
{
	struct timeout_data *data;
	guint id;

	data = g_try_new0(struct timeout_data, 1);
	if (!data)
		return 0;

	data->func = func;
	data->destroy = destroy;
	data->user_data = user_data;

	id = g_timeout_add_full(G_PRIORITY_DEFAULT, timeout, timeout_callback,
						data, timeout_destroy);
	if (!id)
		g_free(data);

	return id;
}

void timeout_remove(unsigned int id)
{
	GSource *source;

	if (!id)
		return;

	source = g_main_context_find_source_by_id(NULL, id);
	if (source)
		g_source_destroy(source);
}

unsigned int timeout_add_seconds(unsigned int timeout, timeout_func_t func,
			void *user_data, timeout_destroy_func_t destroy)
{
	struct timeout_data *data;
	guint id;

	data = g_try_new0(struct timeout_data, 1);
	if (!data)
		return 0;

	data->func = func;
	data->destroy = destroy;
	data->user_data = user_data;

	if (!timeout)
		id = g_idle_add_full(G_PRIORITY_DEFAULT_IDLE, timeout_callback,
							data, timeout_destroy);
	else
		id = g_timeout_add_seconds_full(G_PRIORITY_DEFAULT, timeout,
							timeout_callback, data,
							timeout_destroy);
	if (!id)
		g_free(data);

	return id;
}