/* $Id: util.c,v 1.12 1999/07/15 03:49:15 levitte Exp $ */

#include "gnu_extras.h"

#include <string.h>
#include <lib$routines.h>
#include <starlet.h>
#include <stdlib.h>
#include <ssdef.h>

#include "fish.h"
#define NO_DESTROY
#include "util.h"
#undef NO_DESTROY
#include "fishmsg.h"

/* The invert_byte_order() routine has been borrowed from Dave Jones VMS
   SSH server.  The following comment is his: */
/*
 * Some routines in SSLeay load the cipher blocks big-endian, while
 * the same code in SSH loads the 32-bit words little-endian.
 */
void invert_byte_order ( int len, unsigned char *data )
{
    int i;
    unsigned char b0, b1, b2, b3, b4;

    for ( i = 0; i < len; i += 4 ) {
	b0 = data[i]; b1 = data[i+1];
	data[i] = data[i+3]; data[i+1] = data[i+2];
	data[i+2] = b1; data[i+3] = b0;
    }
}

/* Some other misc. routines we use */
void *xmalloc(size_t size)
{
    void *buf;
    int oldast = sys$setast(0);

    if ((buf = malloc(size)) == NULL)
	ssh_F_malloc(size);

    sys$setast(oldast == SS$_WASSET);
    return buf;
}

void *xrealloc(void *buf, size_t size)
{
    int oldast = sys$setast(0);

    if ((buf = realloc(buf, size)) == NULL)
	ssh_F_realloc();
    
    sys$setast(oldast);
    return buf;
}

void _xfree(void *buf)
{
    int oldast = sys$setast(0);

    free(buf);

    sys$setast(oldast);
}

char *xstrndup(const char *s, int len)
{
    char *r;
    int l = strlen(s);

    if (len < l)
	l = len;

    r = xmalloc(l + 1);
    strncpy(r, s, l);
    r[l] = '\0';

    return r;
}

char *xstrdup(const char *s)
{
    char *r = xstrndup(s, strlen(s) + 1);

    return r;
}

void dump_buffer (FILE *fp, char *heading,
		  const unsigned char *buffer, int bufsize)
{
    int i, j;
    fprintf(fp, "%s (%d bytes):", heading, bufsize);
    j = 15;
    for ( i = 0; i < bufsize; i++ ) {
	j++;
	if ( j > 15 ) {
	    fprintf(fp, "\n   %04x:", i ); j = 0; }
	fprintf(fp, " %02x", 255&buffer[i] );
    }
    fprintf(fp, "\n");
}

/* Emacs local variables

Local variables:
eval: (set-c-style "BSD")
end:

*/
