/*
** mg_dict_int.c for  in 
** 
** Made by vianney rancurel
** Login   <vianney@epita.fr>
** 
** Started on  Wed Aug 25 16:24:56 1999 vianney rancurel
** Last update Thu Oct 28 20:16:20 1999 
*/
#include <stdint.h>
#include "mg.h"

/* is a t_vec_cmp_proc.
   It causes the dictionary to be ordered according numerical order.
   Returns negative, zero or positive value */
int			dict_int_walk_sorted_cmpproc(p1,p2)
VOID_PTR		*p1;
VOID_PTR		*p2;
{
  t_hash_elt		*he1;
  t_hash_elt		*he2;
  
  he1 = (t_hash_elt *)(*p1);
  he2 = (t_hash_elt *)(*p2);
  return ((intptr_t)(he1->value) - (intptr_t)(he2->value));
}

/* walks a dictionary according to numerical order of the values */
int			dict_int_walk_sorted(dict,proc,data)
t_dict			*dict;
t_dict_walk_proc	proc;
VOID_PTR		data;
{
  return (dict_walk_sorted_cmp(dict,
			       proc,
			       (t_vec_cmp_proc)dict_int_walk_sorted_cmpproc,
			       data));
}

/* transforms a "ala-enum" string to a dictionary of integers.
   String must be on the form key1[=n],key2,...,keyn. Keyn worthes 
   keyn-1 + 1 unless Keyn has a new starting base (=m).
   Dict keys are always overrided. Note that dict might contains values
   before the call of this function.
   Returns 0 if OK, might returns various errors */
t_status		dict_int_enum(dict,str,sep)
t_dict			*dict;
char			*str;	/* String to be parsed */
int			sep;	/* Separator: e.g. comma */
{
  t_vec			*vec_str;
  intptr_t		value;
  t_status		status;

  value = 0;
  if ((vec_str = vec_new(VEC_BASE,
			 FALSE,
			 dict->ht->alloc_algorithm_proc,
			 dict->ht->alloc_proc,
			 dict->ht->realloc_proc,
			 dict->ht->free_proc,
			 dict->ht->comment,
			 &status)) == NULL)
    return (status);
  if ((status = vec_str_split(vec_str,str,sep)) != 0)
    {
      vec_str_delete(vec_str);
      return (status);
    }
  VEC_FOR(vec_str,char *str)
    {
      char		*s;

      if (s = index(str,'='))
	{
	  *s++ = 0;
	  value = atoi(s);
	}
      if ((status = dict_override(dict,str,(VOID_PTR)value)) != 0)
	{
	  vec_str_delete(vec_str);
	  return (status);
	}
      value = value + 1;
    }
  VEC_ENDFOR;
  vec_str_delete(vec_str);
  return (0);
}
