/***************************************************************************
 *   copyright           : (C) 2002 by Hendrik Sattler                     *
 *   mail                : post@hendrik-sattler.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     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include "helper.h"
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>

inline
size_t str_len (const char* s) {
  if (s != NULL) return strlen(s);
  else return 0;
}

char* strn_dup (const char* input, size_t insize) {
  void* retval = NULL;

  if (input != NULL) {
    retval = mem_alloc(insize+1,1);
    strncpy(retval,input,insize);
  }
  return retval;
}

char* str_dup (const char* input) {
  return strn_dup(input,str_len(input));
}

size_t strn_width (const char* s, size_t len) {
  size_t i = 0;
  size_t result = 0;

  i = str_len(s);
  if (i < len) len = i;
  if (MB_CUR_MAX != 6) return (len/MB_CUR_MAX);
  else { /* assume UTF-8 */
    for (i = 0; i < len; ++i)
      if ((s[i]&0xC0) != 0x80) ++result;
    return result;
  }
}

size_t str_width (const char* s) {
  return strn_width(s,str_len(s));
}

int strn_valid (const char* s, size_t len) {
  size_t i = 0;
  unsigned char size = 0;
  unsigned char zero = 0;

  if (MB_CUR_MAX == 6) { /* assume UTF-8 */
    for (; i < len; ++i)
      if ((s[i]&0xC0) != 0x80) {
	if (size != 0) return 0;
	zero = 0x40;
	if (s[i]&0x40) { ++size; zero >>= 1; }
	if (s[i]&0x20) { ++size; zero >>= 1; }
	if (s[i]&0x10) { ++size; zero >>= 1; }
	if (s[i]&0x08) { ++size; zero >>= 1; }
	if (s[i]&0x04) { ++size; zero >>= 1; }
	if (s[1]&zero) return 0;
      } else {
	if (size == 0) return 0;
	else --size;
      }
    return (size == 0);
  } else {
    return ((len%MB_CUR_MAX) == 0);
  }
}

int str_valid (const char* s) {
  return strn_valid(s,str_len(s));
}
