#include <sr-general.h>
#include <stdio.h>


/* Flyttet fra highlvl/client/records.c */
octetString *oscpy (octetString *dest, octetString *src)
{
   int nonullterm = 0;

   dest->len = src->len;
   if (src->len > 0 && src->value[src->len - 1])
      nonullterm = 1;
   dest->value = (char *) malloc (src->len + nonullterm);
   (void) memcpy (dest->value, src->value, src->len);
   if (nonullterm)		/* Maybe 'len' should be increased by one */
      dest->value[dest->len] = '\0'; /* Makes even octet strings null-term.*/
   return dest;
}


/* Flyttet fra lib/<isode og tcpip>/sr.c */
octetString *osalloc ( void )
{
   return (octetString *) smalloc ( sizeof ( octetString ) );
}

void osfree ( octetString *os )
{
   if ( os )
   {
      if ( os->value )
	 free ( os->value );
      free ( os );
   }
}

octetString *str2os ( const char *str )
{
   octetString	*os;

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

   os = osalloc();
   os->value	= strdup ( str );
   os->len	= strlen ( str );

   return os;
}

char *os2str ( octetString *oc )
{
   if ( !oc )
      return (char *) NULL;
   
   if ( oc->len )
   {
      /* Check if it is null-terminated */
      if ( oc->value[oc->len - 1] )
      {
         char *str = (char *) malloc(oc->len + 1);
         LOG(facLow, llevNotice, "os2str: handling non-nullterminated str.");
         (void) memcpy (str, oc->value, oc->len);
         str[oc->len] = '\0';
	 return str;
      }
      return strdup ( oc->value );
   }
   return (char *) NULL;
}

octetString *osdup ( octetString *oc )
{
   octetString	*os;

   if ( !oc )
      return (octetString *) NULL;

   os = osalloc();
   os->value = os2str ( oc );
   os->len   = (os->value ? strlen ( os->value ) : 0);

   return os;
}
