/* string.c - some string handling functions.
   Copyright (C) 2000, 2001, 2002, 2003 Cris van Pelt
   Copyright (C) 2003, 2004, 2006 Peter Palfrader

   $Id: string.c 741 2008-10-07 16:16:29Z carsten-guest $

   Distributed under the terms of the Artistic License.
*/
#include <string.h>

#include <deborphan.h>
#include <xalloc.h>

/* Simple function to hash a string to an unsigned int. 
*/
inline unsigned int
strhash(const char *line)
{
    unsigned int r = 0;

    do {
	r ^= *line;
	r <<= 1;
    }
    while (*(line++));

    return r;
}

/* This function removes all occurences of the character 'c' from the
   string 's'.
*/
inline void
strstripchr(char *s, int c)
{
    register char *t;

    s = strchr(s, c);
    if (!(s && *s)) 
	return;

    t = s;

    do {
	if (*s != c)
	    *(t++) = *s;
    }
    while (*(s++));
}

/* Searches for c in *str. *str is updated to point past the first occurrence 
 * of c. And a copy (which has to be free()d by the main program!), starting
 * from the beginning and ending at the character before the first occurence
 * of c, is returned. On error NULL is returned.
 *
 * *str[n] is not modified. *str is, though!
 */
char *
sstrsep(char **str, int c)
{
    char *t, *new;

    if (! (**str && *str))
	return NULL;

    t = strchr(*str, c);

    if (!t)
	return NULL;

    new = (char *) xmalloc((size_t) (t - (*str)) + 1); /* Safe? */
    memcpy(new, *str, (size_t) (t - *str + 1));
    *(new + (t - (*str))) = '\0';
    *str = t + 1;

    return new;
}

int
string_to_priority(const char *priority)
{
    switch (upcase(*priority)) {
    case 'R':			/*equired */
	return 1;
    case 'I':			/*mportant */
	return 2;
    case 'S':			/*tandard */
	return 3;
    case 'O':			/*ptional */
	return 4;
    case 'E':			/*xtra */
	return 5;
    default:			/*unknown/error */
	return 0;
    }
}

const char *
priority_to_string(int priority)
{
    static const char *priorities[] = { "unknown", "required", "important",
	"standard", "optional", "extra"
    };

    return priorities[(priority > 5 || priority < 0) ? 0 : priority];
}
