/*
 * memory.c  -  Byte copying and conversion handling
 *
 * Copyright (C) 1998-2007 Gero Kuhlmann <gero@gkminix.han.de>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  any later version.
 *
 *  This program 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 General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 * $Id: memory.c,v 1.17 2007/01/06 18:31:38 gkminix Exp $
 */

#include <common.h>
#include <nblib.h>
#include "privlib.h"



/*
 * Compare a string in a binary buffer with a string. We can't use
 * strcmp() here, because characters might be represented with a different
 * size on the host system than on the x86 target system. It returns
 * TRUE, if the byte buffer contents and the string are identical.
 */
int bytecmp __F((str, buf, len),
			const char *str AND
			const __u8 *buf AND
			size_t len)
{
  hchar_t c;

  while (*str && len > 0) {
	if ((c = charcollect(*str++)) > 0) {
		if ((__u8)chartotarget(c) != *(buf++))
			break;
		len--;
	}
  }
  return(len == 0);
}



/*
 * Copy a string into a byte array. We can't use strcpy() here because
 * characters might be represented differently on the system than on the
 * target x86 system. This does NOT copy the zero at the end of the
 * source string.
 */
void bytecpy __F((str, buf, len),
			const char *str AND
			__u8 *buf AND
			size_t len)
{
  hchar_t c;

  while (*str && len > 0) {
	if ((c = charcollect(*str++)) > 0) {
		*buf++ = (__u8)chartotarget(c);
		len--;
	}
  }
}



/*
 * Copy a string out of a byte array
 */
char *bytestr __F((buf, len), const __u8 *buf AND size_t len)
{
  const __u8 *bp;
  size_t srclen, destlen, i;
  char *cp, *ret;

  /* Determine length of string */
  srclen = 0;
  destlen = 0;
  for (bp = buf; *bp != 0 && (len == 0 || srclen < len); bp++, srclen++)
	destlen += charlen(chartohost((pcchar_t)(*bp)));

  /* Create new string and do the copy */
  ret = cp = (char *)nbmalloc(destlen + 1);
  while (*buf != 0 && srclen > 0 && destlen > 0) {
	i = savechar(chartohost((pcchar_t)(*buf++)), cp, destlen);
	cp += i;
	destlen -= i;
	srclen--;
  }
  *cp = '\0';
  return(ret);
}



/*
 * Determine the number of bytes required to store a source
 * string into a byte array
 */
size_t bytelen __F((str), const char *str)
{
  const char *cp = str;
  size_t len = 0;

  while (*cp) {
	if (charcollect(*cp) != 0)
		len++;
	cp++;
  }
  return(len);
}

