/*
 * Copyright (C) 2023-2025 Hasl Developers
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, see <https://www.gnu.org/licenses/>.
 */

#include "haslsaslname.h"

#include "haslstring.h"

/******************************************************************************
 * Public API
 *****************************************************************************/
char *
hasl_saslname_encode(const char *saslname) {
	GString *str = NULL;

	if(saslname == NULL) {
		return NULL;
	}

	str = g_string_new("");

	/* Iterate through the saslname and replace ,'s with =2C and ='s with
	 * =3D.
	 */
	for(const char *p = saslname; *p != '\0'; p++) {
		if(*p == ',') {
			g_string_append(str, "=2C");
		} else if(*p == '=') {
			g_string_append(str, "=3D");
		} else {
			g_string_append_c(str, *p);
		}
	}

	return g_string_free_and_steal(str);
}

char *
hasl_saslname_decode(const char *saslname) {
	GString *str = NULL;

	if(saslname == NULL) {
		return NULL;
	}

	str = g_string_new("");

	for(const char *p = saslname; *p != '\0'; p++) {
		/* We drop ','s as they're invalid. */
		if(*p == ',') {
			continue;
		}

		/* Everything else that isn't an `=` just gets appended directly. */
		if(*p != '=') {
			g_string_append_c(str, *p);
			continue;
		}

		/* These checks don't test the length because they will die early if a
		 * null terminator is found.
		 */
		if(p[1] == '2' && p[2] == 'C') {
			g_string_append_c(str, ',');
			p += 2;
		} else if(p[1] == '3' && p[2] == 'D') {
			g_string_append_c(str, '=');
			p += 2;
		}
	}

	return g_string_free_and_steal(str);
}
