/***********************************************************************
     "bool.o": manual implementation of sort Bool
***********************************************************************/

/***********************************
  (C) Copyright 1994; dit/upm
   Distributed under the conditions stated in the
   TOPO General Public License (see file LICENSE)
 ***********************************/

/* LINTLIBRARY */

#define bool_IMP

#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <kaos.hh>
#include "bool.hh"

PUBLIC int
BOOLequal (p1, p2)
  udatum p1, p2;
{
  return p1->ino == p2->ino;
}

PUBLIC char *
BOOLdraw (p)
  udatum p;
{
  if (p->ino)
    return "true";
  else
    return "false";
}

PUBLIC int
BOOLparse (ptr, r)
  char **ptr;
  udatum *r;
{
  typedef struct
  { char *name;
    int value;
  } tKEY;
  static tKEY key_tbl[]= { { "true",	TRUE },
			   { "false",	FALSE },
			   { NULL,	-1 }
			 };
  tKEY *k;
  int l;

  for (k= key_tbl; k->name != NULL; ++k)
  { l= strlen(k->name);
    if (strncmp(*ptr, k->name, l) == 0)
    { *ptr+= l;
      *r= BOOLdatum(k->value);
      return TRUE;
    }
  }
  return FALSE;
}

PUBLIC udatum
BOOLdatum (v)
  int v;
{
  if (v)
  { static udatum p= NULL;

    if (p == NULL)
    { p= ud_alloc();
      p->ino= TRUE;
      (void) ud_const(Bool, p);
    }
    return p;
  }
  else
  { static udatum p= NULL;

    if (p == NULL)
    { p= ud_alloc();
      p->ino= FALSE;
      (void) ud_const(Bool, p);
    }
    return p;
  }
}

PUBLIC int
BOOLvalue (p)
  udatum p;
{
  int v;

  v= p->ino;
  assert(v == TRUE ||
	 v == FALSE);
  ud_free(Bool, p);
  return v;
}
