libcyaml icon indicating copy to clipboard operation
libcyaml copied to clipboard

Define locale for parsing float values

Open MasterMind2k opened this issue 1 year ago • 2 comments

Hi.

Float parsing uses system configuration and will print out and load floats as locale aware. In our usecase, we use libcyaml as confiuration schema and is unacceptable to have floats in locale format, as it prehibits compatibility of configuration values cross-machines.

MasterMind2k avatar May 20 '23 14:05 MasterMind2k

Why not just create wrappers that set and restore the locale around cyaml load/save calls?

For example something like this (untested):

bool my_yaml_loader(
		const char *path,
		my_data_t **data_out)
{
	char *old_locale, *saved_locale;
	unsigned sequence_count;
	bool ret = false;
	my_data_t *data;
	cyaml_err_t err;

	/* Get the name of the current locale.  */
	old_locale = setlocale (LC_ALL, NULL);

	/* Copy the name so it won’t be clobbered by setlocale. */
	saved_locale = strdup(old_locale);
	if (saved_locale == NULL) {
		fprintf(stderr, "Out of memory\n");
		return false;
	}

	/* Now change the locale to the one we want for loading. */
	setlocale (LC_ALL, "C");

	/* Do the load. */
	err = cyaml_load_file(path, config, schema, &data, &sequence_count);
	if (err != CYAML_OK) {
		fprintf(stderr, "Error loading %s: %s\n",
				path, cyaml_strerror(err));
		goto restore;
	}

	*data_out = data;
	ret = true;

restore:
	/* Restore the original locale. */
	setlocale (LC_ALL, saved_locale);
	free(saved_locale);

	return ret;
}

tlsa avatar May 22 '23 07:05 tlsa

It is a work-around. I was hoping on using float parsing library that is not dependant on locale. To remove additional complexitz of setting locale.

MasterMind2k avatar May 22 '23 15:05 MasterMind2k