/*-
 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
 *
 * Copyright (c) 2021 Tobias Kortkamp <tobik@FreeBSD.org>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */
#pragma once

__noreturn void libias_panic(const char *, uint32_t, const char *, ...) __printflike(3, 4);
#define panic(...) libias_panic(__FILE__, __LINE__, __VA_ARGS__)
#define panic_if(x, ...) if (x) { panic(__VA_ARGS__); }
#define panic_unless(x, ...) unless (x) { panic(__VA_ARGS__); }

#define unless(x) if (!(x))

#define CONCAT(a, b) __CONCAT_1(a, b)
#define __CONCAT_1(a, b) a##b

#define GENSYM(name) \
	CONCAT(__gensym_##name##_, __COUNTER__)


#define ITERATOR_FOREACH(...) __ITERATOR_FOREACH(GENSYM(iter_var), GENSYM(iter_state), __VA_ARGS__)
#define __ITERATOR_FOREACH(ITERVAR, ITERSTATEVAR, ITERTYPE, ITERPREFIX, KEYTYPE, KEYCAST, KEYVAR, KEYINIT, VALTYPE, VALCAST, VALVAR, VALINIT, ...) \
	for (struct ITERTYPE##Iterator *ITERVAR __cleanup(ITERPREFIX##_iterator_cleanup) = ITERPREFIX##_iterator(__VA_ARGS__); ITERVAR != NULL; ITERPREFIX##_iterator_cleanup(&ITERVAR)) \
	for (size_t KEYVAR##_index = 0; ITERVAR != NULL; ITERPREFIX##_iterator_cleanup(&ITERVAR)) \
	for (KEYTYPE KEYVAR = KEYINIT; ITERVAR != NULL; ITERPREFIX##_iterator_cleanup(&ITERVAR)) \
	for (VALTYPE VALVAR = VALINIT; ITERVAR != NULL; ITERPREFIX##_iterator_cleanup(&ITERVAR)) \
	for (int ITERSTATEVAR = ITERPREFIX##_iterator_next(&ITERVAR, &KEYVAR##_index, (KEYCAST)&KEYVAR, (VALCAST)&VALVAR); ITERSTATEVAR; ITERSTATEVAR = ITERPREFIX##_iterator_next(&ITERVAR, &KEYVAR##_index, (KEYCAST)&KEYVAR, (VALCAST)&VALVAR))
