tomo/stdlib/metamethods.c

61 lines
1.6 KiB
C
Raw Normal View History

2024-09-13 16:59:28 -07:00
// Metamethods are methods that all types share for hashing, equality, comparison, and textifying
#include <stdint.h>
2024-09-13 17:08:57 -07:00
#include <string.h>
2024-09-13 16:59:28 -07:00
#include "arrays.h"
#include "bools.h"
#include "channels.h"
2024-09-13 16:59:28 -07:00
#include "functiontype.h"
#include "metamethods.h"
#include "optionals.h"
#include "pointers.h"
2024-09-13 16:59:28 -07:00
#include "siphash.h"
#include "tables.h"
2024-09-13 16:59:28 -07:00
#include "text.h"
#include "util.h"
PUREFUNC public uint64_t generic_hash(const void *obj, const TypeInfo_t *type)
2024-09-13 16:59:28 -07:00
{
2024-11-29 09:55:14 -08:00
if (type->metamethods.hash)
return type->metamethods.hash(obj, type);
2024-11-29 09:55:14 -08:00
return siphash24((void*)obj, (size_t)(type->size));
2024-09-13 16:59:28 -07:00
}
PUREFUNC public int32_t generic_compare(const void *x, const void *y, const TypeInfo_t *type)
2024-09-13 16:59:28 -07:00
{
if (x == y) return 0;
2024-11-29 09:55:14 -08:00
if (type->metamethods.compare)
return type->metamethods.compare(x, y, type);
2024-11-29 09:55:14 -08:00
return (int32_t)memcmp((void*)x, (void*)y, (size_t)(type->size));
2024-09-13 16:59:28 -07:00
}
PUREFUNC public bool generic_equal(const void *x, const void *y, const TypeInfo_t *type)
2024-09-13 16:59:28 -07:00
{
if (x == y) return true;
2024-11-29 09:55:14 -08:00
if (type->metamethods.equal)
return type->metamethods.equal(x, y, type);
return (generic_compare(x, y, type) == 0);
2024-09-13 16:59:28 -07:00
}
public Text_t generic_as_text(const void *obj, bool colorize, const TypeInfo_t *type)
2024-09-13 16:59:28 -07:00
{
2024-11-29 09:55:14 -08:00
if (!type->metamethods.as_text)
fail("No text metamethod provided for type!");
2024-11-29 09:55:14 -08:00
return type->metamethods.as_text(obj, colorize, type);
2024-09-13 16:59:28 -07:00
}
public int generic_print(const void *obj, bool colorize, const TypeInfo_t *type)
2024-09-13 16:59:28 -07:00
{
Text_t text = generic_as_text(obj, colorize, type);
return Text$print(stdout, text) + printf("\n");
}
// vim: ts=4 sw=0 et cino=L2,l1,(0,W4,m1,\:0