#include "krb_locl.h"

RCSID("$Id: lsb_addr_comp.c,v 1.6 1996/06/07 22:35:19 joda Exp $");

#include "lsb_addr_comp.h"

int
krb_lsb_antinet_ulong_cmp(u_int32_t x, u_int32_t y)
{
    int i;
    u_int32_t a = 0, b = 0;
    u_int8_t *p = (u_int8_t*) &x;
    u_int8_t *q = (u_int8_t*) &y;

    for(i = sizeof(u_int32_t) - 1; i >= 0; i--){
	a = (a << 8) | p[i];
	b = (b << 8) | q[i];
    }
    if(a > b)
	return 1;
    if(a < b)
	return -1;
    return 0;
}

int
krb_lsb_antinet_ushort_cmp(u_int16_t x, u_int16_t y)
{
    int i;
    u_int16_t a = 0, b = 0;
    u_int8_t *p = (u_int8_t*) &x;
    u_int8_t *q = (u_int8_t*) &y;

    for(i = sizeof(u_int16_t) - 1; i >= 0; i--){
	a = (a << 8) | p[i];
	b = (b << 8) | q[i];
    }
    if(a > b)
	return 1;
    if(a < b)
	return -1;
    return 0;
}

u_int32_t
lsb_time(time_t t, struct sockaddr_in *src, struct sockaddr_in *dst)
{
    /*
     * direction bit is the sign bit of the timestamp.  Ok until
     * 2038??
     */
    /* For compatibility with broken old code, compares are done in VAX 
       byte order (LSBFIRST) */ 
    if (krb_lsb_antinet_ulong_less(src->sin_addr.s_addr, /* src < recv */ 
				   dst->sin_addr.s_addr) < 0) 
        t = -t;
    else if (krb_lsb_antinet_ulong_less(src->sin_addr.s_addr, 
					dst->sin_addr.s_addr)==0) 
        if (krb_lsb_antinet_ushort_less(src->sin_port, dst->sin_port) < 0)
            t = -t;
    /*
     * all that for one tiny bit!  Heaven help those that talk to
     * themselves.
     */
    t = t & 0xffffffff;
    return t;
}
