#include "string_btree.h"

int StringBTree::key_equal_op(const Key* const key, const void* const data)
{
	const void* ptr = data;

	const uint32_t length = extract_value_and_advance(&ptr);
	const uint32_t min_length = std::min(key->length, length);

	const char* const p1 = static_cast<const char*>(key->data);
	const char* const p2 = static_cast<const char*>(ptr);

	for (uint32_t i = 0; i < min_length; ++i) {
		if (p1[i] < p2[i])
			return -1;
		else if (p1[i] > p2[i])
			return 1;
	}

	if (key->length < length)
		return -1;
	else if (key->length > length)
		return 1;
	else
		return 0;
}

int StringBTree::key_less_than_op(const Key* const key, const void* const data)
{
	const void* ptr = data;
	const uint32_t index = extract_value_and_advance(&ptr);
	const int result = key_equal_op(key, ptr);
	return result != 0 ? result : 1;
}

const void* StringBTree::skip_node_data(const void* const node) const
{
	const void* ptr = node;
	const uint32_t length = extract_value_and_advance(&ptr);
	return advance_pointer(ptr, length);
}

int StringBTree::traverse_callback(const void* const data, void* const arg)
{
	const TraverseCallbackArgs<TraverseStringCallback>* const args = static_cast<const TraverseCallbackArgs<TraverseStringCallback>*>(arg);

	int action = kTRAVERSE_CONTINUE;

	String string;
	if (string.parse(data) && args->callback)
		action = (*args->callback)(&string, args->arg);

	return action;
}
