/*****************************************************************/
/**                                                             **/
/**             (C) Copyright 1992 the Regents of the           **/
/**        University of California.  All Rights Reserved.      **/
/**                                                             **/
/**        This work was produced under the sponsorship of      **/
/**         the U.S. Department of Energy.  The Government      **/
/**                retains certain rights therein.              **/
/**                                                             **/
/**                         Written by                          **/
/**         Distributed Programming Environments Project        **/
/**           Computer Software and Networking Division,        **/
/**                   Livermore Computer Center,                **/
/**            Lawrence Livermore National Laboratory           **/
/**                                                             **/
/*****************************************************************/

static char sccsid_enc_length[] = "@(#)enc_length.c	1.17 10/20/92 05:40:30 LLNL ";

/*
	Embedded Language for Remote Operations Services
	ELROS

	AUTHOR:		Robyne M. Sumpter	
			Network Systems Division

	DATE WRITTEN:	7/9/90

	ROUTINE:	__ROr_enc_length	

PURPOSE:
	Encode the value as a length in the header of an asn.1 encoding.


IN:
	instance-
	  Send state used.
	value - value to be encoded.
	valuelength - number of bytes in var to be encoded.
	maxlength - maximum number of byte to be encoded.


OUT:
	instance-
	  Send state and error state are updated.


CALLED ROUTINES:
	

	
MODIFICATION HISTORY:


*/

#include <elros/enc_dcd.h>
#include <elros/instance.h>

static unsigned int high_byte = 0xff << ( (sizeof(unsigned int) - 1) * 8);

int __ROr_enc_length( buffer, count, length )
    char	*buffer;
    int		*count;
    unsigned long *length;
    {

    unsigned int mask;
    int x,
	i;
    char *buffermarker;

    buffermarker = buffer;


					/* if the length is indefinite,
					   signify */

    if(*length == ASN_LEN_INDF)
      {
      *(buffer++) = (ASN_LEN_XTND);
      *count = 1; 
      return( SUCCESS );
      }

					/* if the length is less than 128,
					   write the length byte and return */
    if(*length < ASN_LEN_SMAX)
      {
      *(buffer++) = (*length & 0xff);
      *count = 1;
      return( SUCCESS );
      }

					/* if the length is greater than 127,
					   write it out a byte at a time */

    mask = high_byte;

    for(i = sizeof(unsigned int) - 1; i >= 0; i--)
      {

      if((*length & mask) != 0)
	{
	break;
	}

      mask = mask >> 8;

      }


    *(buffer++) = ( (i + 1) | ASN_LEN_XTND);

    for(; i>= 0; i--)
      {
      *(buffer++) = ( (*length & mask) >> (i*8) );
      mask = mask >> 8;
      }

    *count = buffer - buffermarker;
    return( SUCCESS );
  }
