/*
 *  Copyright (c) 1992, 1993 John E. Davis  (davis@amy.tch.harvard.edu)
 *  All Rights Reserved.
 */


/* These routines are fast memcpy, memset routines.  When available, I
   use system rouines.  For msdos, I use inline assembly. */
      
#include <stdio.h>
#include "config.h"
#include "mem.h"

#ifndef HAS_MEMSET
void jed_memset(char *p, char space, int n)
{
#ifndef msdos
   register char *pmax;

   pmax = p + (n - 4);
   n = n % 4;
   while(p <= pmax) 
     {
	*p++ = space; *p++ = space; *p++ = space; *p++ = space; 
     }
   while (n--) *p++ = space;
#else
   asm mov al, space
   asm mov dx, di
   asm mov cx, n
   asm les di, p
   asm cld
   asm rep stosb
   asm mov di, dx
#endif
}
#endif

#ifndef HAS_MEMCPY
char *jed_memcpy(char *s1, char *s2, int n)
{
#ifdef msdos
   asm mov ax, ds
   asm mov bx, si
   asm mov dx, di
   asm mov cx, n
   asm les di, s1
   asm lds si, s2
   asm cld
   asm rep movsb
   asm mov ds, ax
   asm mov si, bx
   asm mov di, dx
   return(s1);
   
#else
   register char *smax, *s = s1;
   int n2;
   
   n2 = n % 4;
   smax = s + (n - 4);
   while(s <= smax) 
     {
	*s++ = *s2++; *s++ = *s2++; *s++ = *s2++; *s++ = *s2++;
     }
   while (n2--) *s++ = *s2++;
   return(s1); 
#endif
}
#endif

#ifndef HAS_MEMCMP   
int jed_memcmp(char *s1, char *s2, int n)
{
   int cmp;
   while(n--)
     {
	cmp = (unsigned char) *s1++ - (unsigned char) *s2++;
	if (cmp) return(cmp);
     }
   return(0);
}
#endif

#ifndef HAS_MEMCHR
char *jed_memchr(register char *p, register char c, register int n)
{
   int n2;
   register char *pmax;
   n2 = n % 32;
   pmax = p + (n - 32);
	
   while(p <= pmax)
     {
	if ((*p == c)
	    || (*++p == c)
	    || (*++p == c)
	    || (*++p == c)
	    || (*++p == c)
	    || (*++p == c)
	    || (*++p == c)
	    || (*++p == c)
	    || (*++p == c)
	    || (*++p == c)
	    || (*++p == c)
	    || (*++p == c)
	    || (*++p == c)
	    || (*++p == c)
	    || (*++p == c)
	    || (*++p == c)
	    || (*++p == c)
	    || (*++p == c)
	    || (*++p == c)
	    || (*++p == c)
	    || (*++p == c)
	    || (*++p == c)
	    || (*++p == c)
	    || (*++p == c)
	    || (*++p == c)
	    || (*++p == c)
	    || (*++p == c)
	    || (*++p == c)
	    || (*++p == c)
	    || (*++p == c)
	    || (*++p == c)
	    || (*++p == c))
	  {
	     return(p);
	  }
	p++;
     }
   
   while(n2--)
     {
	if (*p++ == c)
	  {
	     return p - 1;
	  }
     }
   return(NULL);
}
#endif

#ifdef USE_EFENCE
char *Xstrcpy(char *aa, char *b)
{
   char *a = aa;
   while ((*a++ = *b++) != 0);
   return aa;
}

int Xstrcmp(char *a, char *b)
{
   while (*a && (*a == *b))
     {
	a++;
	b++;
     }
   if (*a) return(1); else if (*b) return (-1); else return(0);
}

char *Xstrncpy(char *a, char *b, int n)
{
   char *aa = a;
   while ((n > 0) && *b) 
     {
	*aa++ = *b++;
	n--;
     }
   while (n-- > 0) *aa++ = 0;
   return (a);
}
#endif
