/*-------------------------------------------------------------------------
 *
 *   FILE
 *	pgmisc.cc
 *
 *   DESCRIPTION
 *       miscellaneous useful functions
 *
 * Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
 *    /usr/local/devel/pglite/cvs/src/libpq++/pgmisc.cc,v 1.1 1995/01/10 00:41:11 jolly Exp
 *
 *-------------------------------------------------------------------------
 */

#include <stdlib.h>
#include <stdio.h>

/* dupstr : copies a string, while allocating space for it. 
   the CALLER is responsible for freeing the space
   returns NULL if the argument is NULL*/
char* 
dupstr(char *s)
{
  char* result;

  if (s == NULL) return NULL;

  result = (char*)malloc(strlen(s)+1);
  strcpy(result, s);
  return result;
}

int
pqGets(char* s, int len, FILE* f)
{
  int c;

  if (f == NULL)
    return 1;
  
  while (len-- && (c = getc(f)) != EOF && c)
    *s++ = c;
  *s = '\0';

  return 0;
}

int
pqGetInt(int* result, int bytes, FILE* f)
{
  int c;
  int p;
  int n;

  if (f == NULL)
    return 1;
  
  p = 0;
  n = 0;
  while (bytes && (c = getc(f)) != EOF)
    {
      n |= (c & 0xff) << p;
      p += 8;
      bytes--;
    }

  if (bytes != 0)
    return 1;

  *result = n;
  return 0;
}


int
pqPuts(char* s, FILE* f)
{
  int c;

  if (f == NULL)
    return 1;
  
  if (fputs(s,f) == EOF)
    return 1;

  fputc('\0',f); // important to send an ending EOF since backend expects it
  fflush(f);
  return 0;
}

