SmallInteger.st
author Jan Vrany <jan.vrany@fit.cvut.cz>
Sun, 02 Feb 2014 14:16:24 +0000
branchjv
changeset 18117 eb433f2c42b2
parent 18080 9ae1db7ef04a
parent 15910 33ea5acc0934
child 18120 e3a375d5f6a8
permissions -rw-r--r--
Merged bf7f37b63ea2 and 80810829f468 (branch default - CVS HEAD)

"
 COPYRIGHT (c) 1988 by Claus Gittinger
	      All Rights Reserved

 This software is furnished under a license and may be used
 only in accordance with the terms of that license and with the
 inclusion of the above copyright notice.   This software may not
 be provided or otherwise made available to, or used by, any
 other person.  No title to or ownership of the software is
 hereby transferred.
"
"{ Package: 'stx:libbasic' }"

Integer subclass:#SmallInteger
	instanceVariableNames:''
	classVariableNames:'ZeroString'
	poolDictionaries:''
	category:'Magnitude-Numbers'
!

!SmallInteger primitiveDefinitions!
%{
#include <stdio.h>
%}
! !

!SmallInteger class methodsFor:'documentation'!

copyright
"
 COPYRIGHT (c) 1988 by Claus Gittinger
	      All Rights Reserved

 This software is furnished under a license and may be used
 only in accordance with the terms of that license and with the
 inclusion of the above copyright notice.   This software may not
 be provided or otherwise made available to, or used by, any
 other person.  No title to or ownership of the software is
 hereby transferred.
"
!

documentation
"
    SmallIntegers are Integers in the range of at least +/- 2^30
    (i.e. 31 bits, which is not a guaranteed: on an alpha, 63 bits are used,
     if the system was configured for 64bit mode).

    These are no real objects - they have no instances (not even storage !!)
    and cannot be subclassed.
    The reason is to save both storage and runtime by not collecting
    SmallIntegers in the system. SmallInts are marked by having the TAG_INT
    bit set, in contrast to all other objects which do not.
    Since this knowledge is hardwired into the system (and there is no
    class-field stored with SmallIntegers) there can be no subclass of
    SmallInteger (sorry).

    If you really need this kind of thing, create a subclass of Integer,
    with an instance variable holding the value.

    [author:]
	Claus Gittinger

    [see also:]
	Number
	Float Fraction FixedPoint
	LargeInteger
"
! !

!SmallInteger class methodsFor:'instance creation'!

basicNew
    "catch instance creation
     - SmallIntegers cannot be created with new"

    self error:'instances of SmallInteger cannot be created with new'
!

basicNew:size
    "catch instance creation
     - SmallIntegers cannot be created with new"

    self error:'instances of SmallInteger cannot be created with new'
! !

!SmallInteger class methodsFor:'bit mask constants'!

bitMaskFor:index
    "return a bitmask for the index's bit (index starts at 1)"

    (index between:1 and:SmallInteger maxBits) ifFalse:[
	^ SubscriptOutOfBoundsSignal
		raiseRequestWith:index
		errorString:'index out of bounds'
    ].
    ^ 1 bitShift:(index - 1)
! !

!SmallInteger class methodsFor:'class initialization'!

initialize
    ZeroString := '0'
! !

!SmallInteger class methodsFor:'constants'!

maxBits
    "return the number of bits in instances of me.
     For very special uses only - not constant across implementations"

%{  /* NOCONTEXT */
    RETURN ( __mkSmallInteger(N_INT_BITS) );
%}

    "SmallInteger maxBits"
!

maxBytes
    "return the number of bytes in instances of me.
     For very special uses only - not constant across implementations"

%{  /* NOCONTEXT */
    RETURN ( __mkSmallInteger(N_INT_BITS / 8 + 1) );
%}

    "
     SmallInteger maxBytes
    "
!

maxVal
    "return the largest Integer representable as SmallInteger.
     For very special uses only - not constant across implementations"

%{  /* NOCONTEXT */
    RETURN ( __mkSmallInteger(_MAX_INT) );
%}

    "SmallInteger maxVal"
!

minVal
    "return the smallest Integer representable as SmallInteger.
     For very special uses only - not constant across implementations"

%{  /* NOCONTEXT */
    RETURN ( __mkSmallInteger(_MIN_INT) );
%}

    "SmallInteger minVal"
! !

!SmallInteger class methodsFor:'queries'!

canBeSubclassed
    "return true, if its allowed to create subclasses of the receiver.
     Return false here - since it is NOT possible for SmallInteger
     (due to the tagged representation of SmallIntegers)"

    ^ false

    "Modified: / 5.11.1998 / 16:11:27 / cg"
!

hasImmediateInstances
    "return true if this class has immediate instances
     i.e. if the instances are represented in the pointer itself and
     no real object header/storage is used for the object.
     Redefined from Behavior"

    ^ true

    "Created: 3.6.1997 / 12:01:26 / cg"
!

isBuiltInClass
    "return true if this class is known by the run-time-system.
     Here, true is returned."

    ^ true

    "Modified: 23.4.1996 / 16:00:33 / cg"
! !

!SmallInteger methodsFor:'arithmetic'!

* aNumber
    "return the product of the receiver and the argument"

%{  /* NOCONTEXT */

    /*
     * notice:
     * the following inline code handles some common cases,
     * and exists as an optimization, to speed up those cases.
     *
     * Conceptionally, (and for most other argument types),
     * mixed arithmetic is implemented by double dispatching
     * (see the message send at the bottom)
     */

    INT myValue, otherValue;
    unsigned INT productLow, productHi;
    int negative;

#   define low16Bits(foo)  ((foo) & 0xFFFF)
#   define hi16Bits(foo)   ((foo) >> 16)
#   define low32Bits(foo)  ((foo) & 0xFFFFFFFFL)
#   define hi32Bits(foo)   ((foo) >> 32)

    /*
     * can we use long long arithmetic ?
     *
     * long-long arithmetic seems to be buggy with some systems
     * (took me a while to find this out :-(
     * (try 10000 * 10000)
     */
#if defined(__sparc__) && defined(__GNUC__) && (__GNUC__ >= 2)
# define USE_LONGLONG_FOR_MUL
#endif

#if defined(__i386__) && defined(__GNUC__) && (__GNUC__ >= 2)
# define USE_LONGLONG_FOR_MUL
#endif

    if (__isSmallInteger(aNumber)) {
	myValue = __intVal(self);
	otherValue = __intVal(aNumber);

#if defined(USE_LONGLONG_FOR_MUL)
	{
# if defined(__alpha__) && !defined(__alpha64__)
#  define LONGLONG      INT64
# else
#  define LONGLONG      long long
# endif
	    LONGLONG product;

	    product = (LONGLONG)myValue * (LONGLONG)otherValue;
	    if ((product >= (LONGLONG)_MIN_INT)
	     && (product <= (LONGLONG)_MAX_INT)) {
		RETURN ( __mkSmallInteger((INT)product) );
	    }
	    if (product < 0) {
		negative = -1;
		product = -product;
	    } else {
		negative = 1;
	    }
	    productHi = product >> 32;
	    productLow = product & 0xFFFFFFFFL;
	}
#else /* no long-long */
	negative = 1;
	if (myValue < 0) {
	    negative = -1;
	    myValue = -myValue;
	}
	if (otherValue < 0) {
	    negative = -negative;
	    otherValue = -otherValue;
	}

# if defined(__GNUC__) && defined(__mc68k__)
	asm ("mulu%.l %3,%1:%0"
		: "=d"  ((unsigned long)(productLow)),
		  "=d"  ((unsigned long)(productHi))
		: "%0"  ((unsigned long)(myValue)),
		  "dmi" ((unsigned long)(otherValue)));
# else
#  if defined (__GNUC__) && defined(__i386__)
	asm ("mull %3"
		: "=a"  ((unsigned long)(productLow)),
		  "=d"  ((unsigned long)(productHi))
		: "%0"  ((unsigned long)(myValue)),
		  "rm"  ((unsigned long)(otherValue)));
#  else
#   if defined(WIN32) && defined(__BORLANDC__)
	asm {
	    mov   eax, myValue
	    mov   edx, otherValue
	    mul   edx
	    mov   productLow, eax
	    mov   productHi, edx
	}
#   else /* generic */
	{
	    unsigned INT pHH, pHL, pLH, pLL;
	    unsigned INT low1, low2, hi1, hi2;
	    unsigned INT t;

	    /* unsigned multiply myValue * otherValue -> productHi, productLow
	     *
	     * this is too slow:
	     * since most machines can do 32*32 to 64 bit multiply,
	     * (or at least 32*32 with Overflow check)
	     * - need more assembler (inline) functions here
	     */
#    if __POINTER_SIZE__ == 8
	    low1 = low32Bits((unsigned INT)myValue);
	    hi1 = hi32Bits((unsigned INT)myValue);
	    low2 = low32Bits((unsigned INT)otherValue);
	    hi2 = hi32Bits((unsigned INT)otherValue);
#     define LLMASK 0xC000000000000000L
#    else
	    low1 = low16Bits((unsigned INT)myValue);
	    hi1 = hi16Bits((unsigned INT)myValue);
	    low2 = low16Bits((unsigned INT)otherValue);
	    hi2 = hi16Bits((unsigned INT)otherValue);
#     define LLMASK 0xC0000000
#    endif

	    pLH = low1 * hi2;
	    pHL = hi1 * low2;
	    pLL = low1 * low2;
	    pHH = hi1 * hi2;

	    /*
	     * the common case ...
	     */
	    if ((pHL == 0)
	     && (pLH == 0)
	     && (pHH == 0)
	     && ((pLL & LLMASK) == 0)) {
		if (negative < 0) {
		    RETURN ( __mkSmallInteger(- ((INT)pLL)) );
		}
		RETURN ( __mkSmallInteger((INT)pLL) );
	    }

	    /*
	     *   pHH |--------|--------|
	     *   pLH          |--------|--------|
	     *   pHL          |--------|--------|
	     *   pLL                   |--------|--------|
	     */

#    if __POINTER_SIZE__ == 8
	    t = low32Bits(pLH) + low32Bits(pHL) + hi32Bits(pLL);
	    productLow = (t << 32) + low32Bits(pLL);
	    productHi = pHH + hi32Bits(t) + hi32Bits(pHL) + hi32Bits(pLH);
#    else
	    t = low16Bits(pLH) + low16Bits(pHL) + hi16Bits(pLL);
	    productLow = (t << 16) + low16Bits(pLL);
	    productHi = pHH + hi16Bits(t) + hi16Bits(pHL) + hi16Bits(pLH);
#    endif
	}
#   endif /* ! WIN32 */
#  endif /* ! (__GNUC__ && __i386__) */
# endif /* ! (__GNUC__ && __mc68k__) */

	if (productHi == 0) {
	    if (negative < 0) {
		if (productLow <= -(_MIN_INT)) {
		    RETURN ( __mkSmallInteger(-((INT)productLow)) );
		}
	    } else {
		if (productLow <= _MAX_INT) {
		    RETURN ( __mkSmallInteger(productLow) );
		}
	    }
	}
#endif /* ! USE_LONGLONG */

#if __POINTER_SIZE__ == 8
	RETURN (__MKLARGEINT128(negative, productLow, productHi));
#else
	RETURN (__MKLARGEINT64(negative, productLow, productHi));
#endif
    } else if (__isFloatLike(aNumber)) {
	OBJ newFloat;
	double val = (double)__intVal(self) * __floatVal(aNumber);

	__qMKFLOAT(newFloat, val);
	RETURN ( newFloat );
    } else if (__isShortFloat(aNumber)) {
	OBJ newFloat;
	float val = (float)__intVal(self) * __shortFloatVal(aNumber);

	__qMKSFLOAT(newFloat, val);
	RETURN ( newFloat );
    }
%}.
    ^ aNumber productFromInteger:self
!

+ aNumber
    "return the sum of the receivers value and the arguments value"

%{  /* NOCONTEXT */

    /*
     * notice:
     * the following inline code handles some common cases,
     * and exists as an optimization, to speed up those cases.
     *
     * Conceptionally, (and for most other argument types),
     * mixed arithmetic is implemented by double dispatching
     * (see the message send at the bottom)
     */

    if (__isSmallInteger(aNumber)) {
#ifdef _ADD_IO_IO
	RETURN ( _ADD_IO_IO(self, aNumber) );
#else
	REGISTER INT sum;

	sum =  __intVal(self) + __intVal(aNumber);
	if (__ISVALIDINTEGER(sum)) {
	    RETURN ( __mkSmallInteger(sum) );
	}
	RETURN ( __MKLARGEINT(sum) );
#endif
    }
    if (__isFloatLike(aNumber)) {
	OBJ newFloat;
	double val = (double)__intVal(self) + __floatVal(aNumber);

	__qMKFLOAT(newFloat, val);
	RETURN ( newFloat );
    }
    if (__isShortFloat(aNumber)) {
	OBJ newFloat;
	float val = (float)__intVal(self) + __shortFloatVal(aNumber);

	__qMKSFLOAT(newFloat, val);
	RETURN ( newFloat );
    }
%}.
    ^ aNumber sumFromInteger:self
!

- aNumber
    "return the difference of the receivers value and the arguments value"

%{  /* NOCONTEXT */

    /*
     * notice:
     * the following inline code handles some common cases,
     * and exists as an optimization, to speed up those cases.
     *
     * Conceptionally, (and for most other argument types),
     * mixed arithmetic is implemented by double dispatching
     * (see the message send at the bottom)
     */

    if (__isSmallInteger(aNumber)) {
#ifdef _SUB_IO_IO
	RETURN ( _SUB_IO_IO(self, aNumber) );
#else
	REGISTER INT diff;

	diff =  __intVal(self) - __intVal(aNumber);
	if (__ISVALIDINTEGER(diff)) {
	    RETURN ( __mkSmallInteger(diff) );
	}
	RETURN ( __MKLARGEINT(diff) );
#endif
    }
    if (__isFloatLike(aNumber)) {
	OBJ newFloat;
	double val = (double)__intVal(self) - __floatVal(aNumber);

	__qMKFLOAT(newFloat, val);
	RETURN ( newFloat );
    }
    if (__isShortFloat(aNumber)) {
	OBJ newFloat;
	float val = (float)__intVal(self) - __shortFloatVal(aNumber);

	__qMKSFLOAT(newFloat, val);
	RETURN ( newFloat );
    }
%}.
    ^ aNumber differenceFromInteger:self
!

/ aNumber
    "return the quotient of the receivers value and the arguments value"

%{  /* NOCONTEXT */

    /*
     * notice:
     * the following inline code handles some common cases,
     * and exists as an optimization, to speed up those cases.
     *
     * Conceptionally, (and for most other argument types),
     * mixed arithmetic is implemented by double dispatching
     * (see the message send at the bottom)
     */

    INT me, t, val;
    double dval;

    if (__isSmallInteger(aNumber)) {
	val = __intVal(aNumber);
	if (val != 0) {
	    me = __intVal(self);
	    t = me / val;
#ifdef GOOD_OPTIMIZER
	    if (me % val == 0) {
#else
	    /* this is stupid - all I want is to look for a remainder ...
	       but most compilers are too stupid and generate an extra modulus
	       instruction for "if (me % val)".
	       Even if most divide instructions already leave the remainder in
	       some register.
	       Therefore I use a multiplication which is faster than a modulo
	       on most machines. Hint to GNU people :-)
	    */
	    if ((t * val) == me) {
#endif
		RETURN ( __mkSmallInteger(t) );
	    }
	}
    } else {
	if (__isFloatLike(aNumber)) {
	    dval = __floatVal(aNumber);
	    if (dval != 0.0) {
		OBJ newFloat;
		double val = (double)__intVal(self) / dval;

		__qMKFLOAT(newFloat, val);
		RETURN ( newFloat );
	    }
	}
    }
%}.
    aNumber isInteger ifTrue:[
	aNumber == 0 ifTrue:[
	    ^ ZeroDivide raiseRequestWith:thisContext.
	].
	^ Fraction numerator:self denominator:aNumber
    ].
    ^ aNumber quotientFromInteger:self

    "
     8 / 4
     9 / 4
     9 // 4
     9 quo:4

     -8 / 4
     -9 / 4
     -9 // 4
     -9 quo:4
    "
!

// aNumber
    "return the integer part of the quotient of the receivers value
     and the arguments value. The result is truncated toward negative infinity
     and negative, if the operands signs differ.
     Be careful with negative results: 9 // 4 -> 2, while -9 // 4 -> -3.
     Especially surprising:     
        -1 // 10 -> -1 (because -(1/10) is truncated towards next smaller integer, which is -1.
     The following is always true:
        (receiver // aNumber) * aNumber + (receiver \\ aNUmber) = receiver
     See #quo: which returns -2 in the latter."

%{  /* NOCONTEXT */

    /*
     * notice:
     * the following inline code handles some common cases,
     * and exists as an optimization, to speed up those cases.
     *
     * Conceptionally, (and for most other argument types),
     * mixed arithmetic is implemented by double dispatching
     * (see the message send at the bottom)
     */

    INT dividend, divisor, rslt;

    if (__isSmallInteger(aNumber)) {
        divisor = __intVal(aNumber);
        if (divisor != 0) {
            dividend = __intVal(self);
            rslt = dividend / divisor;
            /*
             * Optimized to speed up positive result
             */
            if (rslt <= 0) {
                if (rslt == 0) {
                    if ((dividend ^ divisor) < 0) {
                        /*
                         * result (negative) has been truncated toward 0.
                         * Return -1, because we truncate toward negative inf.
                         */
                         rslt = -1;
                    }
                } else {
                    /*
                     * If result (negative) has been truncated toward 0,
                     * subtract 1, because we truncate toward negative inf.
                     */
                    if (divisor > 0) {
                        if (rslt * divisor > dividend) {
                            rslt--;
                        }
                    } else {
                        if (rslt * divisor < dividend) {
                            rslt--;
                        }
                    }
                }
            }
            RETURN ( __mkSmallInteger(rslt) );
        }
    } else {
        if (__isFraction(aNumber)) {
            OBJ t;
            INT num, den;

            t = __FractionInstPtr(aNumber)->f_numerator;
            if (__isSmallInteger(t)) {
                num = __intVal(t);
                t = __FractionInstPtr(aNumber)->f_denominator;
                if (__isSmallInteger(t)) {
                    den = __intVal(t);
                    RETURN ( __mkSmallInteger(__intVal(self) * den / num ));
                }
            }
        }
    }
%}.
    (aNumber = 0) ifTrue:[
        ^ ZeroDivide raiseRequestWith:thisContext.
    ].
    ^ aNumber integerQuotientFromInteger:self

    "
     9 // 4     ~~ 2 ifTrue:[self halt].
     -9 // 4    ~~ -3 ifTrue:[self halt].
     9 // -4    ~~ -3 ifTrue:[self halt].
     -9 // -4   ~~ 2 ifTrue:[self halt].
     1 // 2     ~~ 0 ifTrue:[self halt].
     -1 // 2    ~~ -1 ifTrue:[self halt].
     1 // -2    ~~ -1 ifTrue:[self halt].
     -1 // -2   ~~ 0 ifTrue:[self halt].
     10000 // 3600000 ~~ 0 ifTrue:[self halt].

     9 quo:4   => 2
     -9 quo:4  => -2
     9 quo:-4  => -2
     -9 quo:-4 => 2
    "

    "Modified: / 09-08-2010 / 19:50:23 / cg"
!

\\ aNumber
    "Answer the integer remainder m defined by division with truncation toward
     negative infinity. The remainder has the same sign as aNumber.
     m < |aNumber| AND there is an integer k with (k * aNumber + m) = self
     The following is always true:
	(receiver // aNumber) * aNumber + (receiver \\ aNumber) = receiver
     Compare with #rem:

     Redefined for speed."

%{  /* NOCONTEXT */

    /*
     * notice:
     * the following inline code handles some common cases,
     * and exists as an optimization, to speed up those cases.
     *
     * Conceptionally, (and for most other argument types),
     * mixed arithmetic is implemented by double dispatching
     * (see the message send at the bottom)
     */

    INT dividend, divisor, rem;

    if (__isSmallInteger(aNumber)
	&& (divisor = __intVal(aNumber)) != 0) {
	/*
	 * Note that the sign of something modulo a negative number is undefined
	 * in C!
	 */
	dividend = __intVal(self);
	rem = dividend % divisor;
	if (rem) {
	    if ((rem ^ divisor) < 0) {
		/* sign of remainder is different from sign of divisor */
		rem = -rem;
	    }
	    if ((dividend ^ divisor) < 0) {
		/* different signs, so division would have returned a
		 * negative number.
		 * C rounds toward zero, this code will simulate
		 * rounding towards negative infinity.
		 */
		rem = divisor - rem;
	    }
	}
	RETURN ( __mkSmallInteger(rem) );
    }
%}.
    (aNumber = 0) ifTrue:[
	^ ZeroDivide raiseRequestWith:thisContext.
    ].
    ^ aNumber moduloFromInteger:self

    "
     9 \\ 4  == 1 ifFalse:[self halt].
     -9 \\ 4 == 3 ifFalse:[self halt].
     9 \\ -4 == -3 ifFalse:[self halt].
     -9 \\ -4 == -1 ifFalse:[self halt].
     (9 rem:4) == 1 ifFalse:[self halt].
     (-9 rem:4) == -1 ifFalse:[self halt].
     1000 \\ 3600000 == 1000 ifFalse:[self halt]
    "

    "Modified: / 12-02-2012 / 20:43:40 / cg"
!

abs
    "return the absolute value of the receiver
     reimplemented here for speed"

%{  /* NOCONTEXT */

    INT val = __intVal(self);

    if (val >= 0) {
	RETURN (self);
    }
    if (val != _MIN_INT) {
	RETURN ( __mkSmallInteger(-val) );
    }
    /* only reached for minVal */
    RETURN( __MKLARGEINT(-_MIN_INT));
%}.
    ^ super abs
!

negated
    "return the negative value of the receiver
     reimplemented here for speed"

%{  /* NOCONTEXT */

    INT val = __intVal(self);

    if (val != _MIN_INT) {
	RETURN ( __mkSmallInteger(- val) );
    }
    /* only reached for minVal */
    RETURN (__MKLARGEINT( -_MIN_INT));
%}.
    ^ 0 - self
"/    "only reached for minVal"
"/    ^ (LargeInteger value:(SmallInteger maxVal)) + 1
!

quo:aNumber
    "return the integer part of the quotient of the receivers value
     and the arguments value. The result is truncated towards zero
     and negative, if the operands signs differ..
     The following is always true:
	(receiver quo: aNumber) * aNumber + (receiver rem: aNumber) = receiver
     For positive results, this is the same as #//,
     for negative results, the remainder is ignored.
     I.e.: '9 // 4 = 2' and '-9 // 4 = -3'
     in contrast: '9 quo: 4 = 2' and '-9 quo: 4 = -2'"

%{  /* NOCONTEXT */
    INT val;

    if (__isSmallInteger(aNumber)) {
	val = __intVal(aNumber);
	if (val != 0) {
	    RETURN ( __mkSmallInteger(__intVal(self) / val) );
	}
    } else {
	if (__isFraction(aNumber)) {
	    OBJ t;
	    INT num, den;

	    t = __FractionInstPtr(aNumber)->f_numerator;
	    if (__isSmallInteger(t)) {
		num = __intVal(t);
		t = __FractionInstPtr(aNumber)->f_denominator;
		if (__isSmallInteger(t)) {
		    den = __intVal(t);
		    RETURN ( __mkSmallInteger(__intVal(self) * den / num ));
		}
	    }
	}
    }
%}.
    (aNumber = 0) ifTrue:[
	^ ZeroDivide raiseRequestWith:thisContext.
    ].
    ^ self retry:#quo: coercing:aNumber

    "
     9 // 4
     -9 // 4
     9 quo:4
     -9 quo:4
    "
! !



!SmallInteger methodsFor:'bit operators'!

bitAnd:anInteger
    "return the bitwise-and of the receiver and the argument, anInteger"

%{  /* NOCONTEXT */

    /* anding the tags doesn't change it */
    if (__isSmallInteger(anInteger)) {
	RETURN ( ((OBJ) ((INT)self & (INT)anInteger)) );
    }
%}.
    anInteger class == LargeInteger ifTrue:[
	^ anInteger bitAnd:self
    ].
    ^ self retry:#bitAnd: coercing:anInteger

    "(2r001010100 bitAnd:2r00001111) radixPrintStringRadix:2"
!

bitAt:anIntegerIndex
    "return the value of the index's bit (index starts at 1) as 0 or 1.
     Notice: the result of bitAt: on negative receivers is not
             defined in the language standard (since the implementation
             is free to choose any internal representation for integers)"

%{  /* NOCONTEXT */

    if (__isSmallInteger(anIntegerIndex)) {
        INT idx = __smallIntegerVal(anIntegerIndex);
        if (idx > 0) {
            if (idx > N_INT_BITS) {
                RETURN(__mkSmallInteger(0));
            }
            RETURN((__smallIntegerVal(self) & (1 << (idx-1))) ? __mkSmallInteger(1) : __mkSmallInteger(0));
        }
    }
%}.

    ^ SubscriptOutOfBoundsError
            raiseRequestWith:anIntegerIndex
            errorString:'index out of bounds'

    "
     16r00000001 bitAt:0
     16r00000001 bitAt:1
     16r00000001 bitAt:2
     16r00008000 bitAt:16
     16r00800000 bitAt:24
     16r08000000 bitAt:28
     16r10000000 bitAt:29
     16r20000000 bitAt:30
     16r40000000 bitAt:31
     16r80000000 bitAt:32
     16r100000000 bitAt:33
    "

" Smalltalk implementation:
    |mask|

    anIntegerIndex <= 0 ifTrue:[
        ^ SubscriptOutOfBoundsSignal
                raiseRequestWith:anIntegerIndex
                errorString:'index out of bounds'
    ].
    (anIntegerIndex > SmallInteger maxBits) ifTrue:[^ 0].
    mask := 1 bitShift:(anIntegerIndex - 1).
    ((self bitAnd:mask) == 0) ifTrue:[^ 0].
    ^ 1
"
!

bitClear:anInteger
    "return the bitwise-and of the receiver and the complement of the argument, anInteger,
     returning the receiver with bits of the argument cleared."

%{  /* NOCONTEXT */

    /* anding the tags doesn't change it */
    if (__isSmallInteger(anInteger)) {
	RETURN ( ((OBJ) (((INT)self & ~(INT)anInteger) | TAG_INT)) );
    }
%}.
    ^ self retry:#bitClear: coercing:anInteger

    "
     (2r001010100 bitClear:2r00001111) radixPrintStringRadix:2
     (2r111111111 bitClear:2r00001000) radixPrintStringRadix:2
    "
!

bitCount
    "return the number of 1-bits in the receiver"

%{  /* NOCONTEXT */
    unsigned int _cnt;
    unsigned INT _self = __intVal(self);

# define ALGORIHTM_3

# ifdef ALGORITHM_1
    // old k&r code; might be better if only one or two bits are set

    _cnt = 0;
    while (_self) {
        _cnt++;
        _self = _self & (_self - 1);
    }
# else
#  ifdef ALGORITHM_2
    // seems to be faster on the average (and has better worst case)

    static unsigned char table[] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 };

    _cnt = 0;
    while (_self) {
        _cnt += table[ _self & 0x0F ];
        _self >>= 4;
    }
#  else
#   ifdef ALGORIHTM_3
    // the fastest, but hard (impossible) to understand (google for fastest bit count)
#    if __POINTER_SIZE__ == 8
    unsigned int _v1, _v2;

    _v1 = _self & 0xFFFFFFFF;
    _v1 = _v1 - ((_v1 >> 1) & 0x55555555);
    _v1 = (_v1 & 0x33333333) + ((_v1 >> 2) & 0x33333333);
    _v1 = ((_v1 + (_v1 >> 4)) & 0x0F0F0F0F);

    _v2 = (unsigned int)(_self >> 32);
    _v2 = _v2 - ((_v2 >> 1) & 0x55555555);
    _v2 = (_v2 & 0x33333333) + ((_v2 >> 2) & 0x33333333);
    _v2 = ((_v2 + (_v2 >> 4)) & 0x0F0F0F0F);

    _cnt = ((_v1 * 0x01010101) >> 24) + ((_v2 * 0x01010101) >> 24);
#    else
    _cnt = _self - ((_self >> 1) & 0x55555555);
    _cnt = (_cnt & 0x33333333) + ((_cnt >> 2) & 0x33333333);
    _cnt = ((_cnt + (_cnt >> 4)) & 0x0F0F0F0F);
    _cnt = (_cnt * 0x01010101) >> 24;
#    endif
#   else
     error error error
#   endif
#  endif
# endif

    RETURN ( __MKSMALLINT(_cnt));
%}

    "

     1 to:1000000 do:[:n |
        self assert:(n bitCount = ((n printStringRadix:2) occurrencesOf:$1))
     ].

     #(
        16r00010000 16r00100000 16r01000000 16r10000000
        16r00020000 16r00200000 16r02000000 16r20000000
        16r00040000 16r00400000 16r04000000 16r40000000
        16r00080000 16r00800000 16r08000000 16r80000000

        16rFFFFFFFF 16r7FFFFFFF 16r3FFFFFFF 16r1FFFFFFF
        16rEEEEEEEE 16r7EEEEEEE 16r3EEEEEEE 16r1EEEEEEE
        16rDDDDDDDD 16r7DDDDDDD 16r3DDDDDDD 16r1DDDDDDD
        16rCCCCCCCC 16r7CCCCCCC 16r3CCCCCCC 16r1CCCCCCC
     ) do:[:n |
        self assert:(n bitCount = ((n printStringRadix:2) occurrencesOf:$1))
     ]

     1 to:10000000 do:[:n |
        (n bitCount)
     ]
    "

    "Modified: / 09-01-2012 / 19:12:41 / cg"
!

bitInvert
    "return the value of the receiver with all bits inverted"

%{  /* NOCONTEXT */

    /* invert anything except tag bits */
    RETURN ( ((OBJ) ((INT)self ^ ~TAG_MASK)) );
%}.
    ^ self primitiveFailed
!

bitOr:anInteger
    "return the bitwise-or of the receiver and the argument, anInteger"

%{  /* NOCONTEXT */

    /* oring the tags doesn't change it */
    if (__isSmallInteger(anInteger)) {
	RETURN ( ((OBJ) ((INT)self | (INT)anInteger)) );
    }
%}.
    ^ self retry:#bitOr: coercing:anInteger

    "
     (2r000000100 bitOr:2r00000011) radixPrintStringRadix:2
     (0 bitOr:16r20000000) hexPrintString
     (0 bitOr:16r40000000) hexPrintString
     (0 bitOr:16r80000000) hexPrintString
    "
!

bitShift:shiftCount
    "return the value of the receiver shifted by shiftCount bits;
     leftShift if shiftCount > 0; rightShift otherwise.
     Notice: the result of bitShift: on negative receivers is not
	     defined in the language standard (since the implementation
	     is free to choose any internal representation for integers).
	     However, ST/X preserves the sign."

%{  /* NOCONTEXT */

    INT bits, count;

    if (__isSmallInteger(shiftCount)) {
	bits = __intVal(self);
	if (bits == 0) {
	    RETURN (self);
	}

	count = __intVal(shiftCount);

	if (count > 0) {
	    /*
	     * a left shift
	     */
#if defined(USE_LONGLONG_FOR_SHIFT)
	    if (count <= N_INT_BITS) {
		unsigned LONGLONG result;

		result = (unsigned LONGLONG)bits;
		result <<= count;
		if (result <= _MAX_INT) {
		    RETURN ( __mkSmallInteger(result) );
		}
		{
		    RETURN (__MKLARGEINT64(1, (INT)(result >> 32), (INT)(result & 0xFFFFFFFF)));
		}
	    }
#else
	    /*
	     * check for overflow
	     */
	    if (count < (N_INT_BITS-1)) {
		if (! (bits >> (N_INT_BITS - 1 - count))) {
		    RETURN ( __mkSmallInteger(bits << count) );
		}
		/*
		 * so, there is an overflow ...
		 * handle it as largeInteger
		 */
		/* FALL THROUGH */
	    }
#endif
	} else {
	    if (count == 0) {
		RETURN (self);
	    }

	    /*
	     * right shifts cannot overflow
	     *
	     * some machines ignore shifts bigger than
	     * the number of bits in an int ...
	     */
	    count = -count;
	    if (count > (N_INT_BITS-1)) {
		RETURN (__mkSmallInteger(0));
	    }

	    RETURN ( __mkSmallInteger(bits >> count) );
	}
    }
%}.
    (shiftCount isMemberOf:SmallInteger) ifTrue:[
	^ (LargeInteger value:self) bitShift:shiftCount
    ].
    ^ self bitShift:(1 coerce:shiftCount)   "/ is this a good idea ?
!

bitTest:aMask
    "return true, if any bit from aMask is set in the receiver.
     I.e. true, if the bitwise-AND of the receiver and the argument, anInteger
     is non-0, false otherwise."

%{  /* NOCONTEXT */

    /* and all bits except tag */
    if (__isSmallInteger(aMask)) {
	RETURN ( ((INT)self & ((INT)aMask & ~TAG_MASK)) ? true : false );
    }
%}.
    aMask class == LargeInteger ifTrue:[
	^ (aMask bitAnd:self) ~~ 0
    ].
    ^ self retry:#bitTest: coercing:aMask

    "
     2r10001 bitTest:2r00001
     2r10001 bitTest:2r00010
     2r10001 bitTest:2r00100
     2r10001 bitTest:2r01000
     2r10001 bitTest:2r10000
     2r10001 bitTest:2r10001
     2r10001 bitTest:2r10010
    "
!

bitXor:anInteger
    "return the bitwise-exclusive-or of the receiver and the argument, anInteger"

%{  /* NOCONTEXT */

    /* xoring the tags turns it off - or it in again */
    if (__isSmallInteger(anInteger)) {
	RETURN ( (OBJ)( ((INT)self ^ (INT)anInteger) | TAG_INT) );
    }
%}.
    ^ self retry:#bitXor: coercing:anInteger
!

clearBit:anInteger
    "return a new integer where the specified bit is off.
     Bits are counted from 1 starting with the least significant.
     The methods name may be misleading: the receiver is not changed,
     but a new number is returned. Should be named #withBitCleared:"

%{  /* NOCONTEXT */

    if (__isSmallInteger(anInteger)) {
        int index = __intVal(anInteger);

        if (index > 0) {
#if __POINTER_SIZE__ == 8
            if (index <= 62)
#else
            if (index <= 30)
#endif
            {
                INT mask = __MASKSMALLINT(1 << (index-1));

                RETURN ( ((OBJ) ((INT)self & ~(INT)mask)) );
            }
            RETURN (self);  /* nothing to do ... */
        }
    }
%}.
    ^ super clearBit:anInteger

    "
     (16r401 clearBit:1     ) hexPrintString
     (16r401 clearBit:0     ) hexPrintString
     (16r3fffffff clearBit:1) hexPrintString
     (16r3fffffff clearBit:29) hexPrintString
     (16r3fffffff clearBit:30) hexPrintString
     (16r3fffffff clearBit:31) hexPrintString
     (16r3fffffff bitAt:29) hexPrintString
     (16r3fffffff bitAt:30) hexPrintString
     (16r3fffffff bitAt:31) hexPrintString
     (16r40000001 clearBit:1) hexPrintString
     (16rF0000001 clearBit:29) hexPrintString
     (16rF0000001 clearBit:30) hexPrintString
     (16rF0000001 clearBit:31) hexPrintString
     (16rF0000001 clearBit:32) hexPrintString
    "
!

highBit
    "return the bitIndex of the highest bit set. The returned bitIndex
     starts at 1 for the least significant bit.
     Returns 0 if no bit is set."

%{  /* NOCONTEXT */

    unsigned INT bits;
    int index;

    bits = __intVal(self);
    if (bits == 0) {
	RETURN ( __mkSmallInteger(0) );
    }

#ifdef __BSR
    /*
     * so much for CISC CPUS:
     * the following code is not faster on a PIII-400
     * (but saves a few code-bytes, though)
     */
    index = __BSR(bits);
#else

    index = 0;

# if __POINTER_SIZE__ == 8
    if (bits & 0xFFFFFFFF00000000L) {
	index += 32; bits = bits >> 32;
    }
# endif
    if (bits & 0xFFFF0000L) {
	index += 16; bits = bits >> 16;
    }
    if (bits & 0xFF00) {
	index += 8; bits = bits >> 8;
    }
    if (bits & 0xF0) {
	index += 4; bits = bits >> 4;
    }
    if (bits & 0xC) {
	index += 2; bits = bits >> 2;
    }
    if (bits & 0x2) {
	index += 1; bits = bits >> 1;
    }
#endif /* no BSR instruction */

    RETURN ( __mkSmallInteger(index+1) );
%}
    "
     2r0 highBit
     2r1 highBit
     2r10 highBit
     2r100 highBit
     2r1000 highBit
     2r100000000000 highBit

     ((0 to:64) collect:[:s | 1 bitShift:s])
	collect:[:n | n highBit]

     (((0 to:64) collect:[:s | 1 bitShift:s])
	collect:[:n | n highBit]) = (1 to:65)
    "

    "
     Time millisecondsToRun:[
	1000000 timesRepeat:[
	    2r1 highBit
	]
     ]
    "
    "
     Time millisecondsToRun:[
	1000000 timesRepeat:[
	    2r1111 highBit
	]
     ]
    "
    "
     Time millisecondsToRun:[
	1000000 timesRepeat:[
	    2r11111111111111 highBit
	]
     ]
    "
    "
     Time millisecondsToRun:[
	1000000 timesRepeat:[
	    2r11111111111111111111111111 highBit
	]
     ]
    "

    "
     2r000100 highBit
     2r010100 highBit
     2r000001 highBit
     0 highBit
     SmallInteger maxVal highBit
    "
!

invertBit:anInteger
    "return a new number where the specified bit is inverted.
     Bits are counted from 1 starting with the least significant.
     The methods name may be misleading: the receiver is not changed,
     but a new number is returned. Should be named #withBitInverted:"

%{  /* NOCONTEXT */

    if (__isSmallInteger(anInteger)) {
        int index = __intVal(anInteger);

        if (index > 0) {
#if __POINTER_SIZE__ == 8
            if (index <= 62)
#else
            if (index <= 30)
#endif
            {
                INT mask = __MASKSMALLINT(1 << (index-1));

                RETURN ( ((OBJ) ((INT)self ^ (INT)mask)) );
            }
        }
    }
%}.
    ^ super invertBit:anInteger

    "
     (16r401 invertBit:2     ) hexPrintString
     (16r401 invertBit:1     ) hexPrintString
     (16r30000000 invertBit:1) hexPrintString
     (16r40000000 invertBit:0) hexPrintString
     (16r0 invertBit:29) hexPrintString
     (16r0 invertBit:30) hexPrintString
     (16r0 invertBit:31) hexPrintString
     (16r0 invertBit:32) hexPrintString
     (16r0 invertBit:33) hexPrintString
     (16r0 invertBit:100) hexPrintString
    "
!

lowBit
    "return the bitIndex of the lowest bit set. The returned bitIndex
     starts at 1 for the least significant bit.
     Returns 0 if no bit is set."

%{  /* NOCONTEXT */

    unsigned INT bits;
    int index;

    bits = __intVal(self);
    if (bits == 0) {
	RETURN ( __mkSmallInteger(0) );
    }

#ifdef __BSF
    /*
     * so much for CISC CPUS:
     * the following code is only marginally faster on a PIII-400
     * (and not at all faster on an Athlon...)
     * but saves a few code-bytes, though.
     */
    index = __BSF(bits);
    RETURN ( __mkSmallInteger(index + 1) );
#else

    index = 1;

# if __POINTER_SIZE__ == 8
    if ((bits<<32) == 0) {
	index += 32; bits >>= 32;
    }
# endif

    if ((bits & 0xFFFF)==0) {
	index += 16; bits >>= 16;
    }
    if ((bits & 0xFF)==0) {
	index += 8; bits >>= 8;
    }
    if ((bits & 0xF)==0) {
	index += 4; bits >>= 4;
    }
    if ((bits & 0x3)==0) {
	index += 2; bits >>= 2;
    }
    if ((bits & 0x1)==0) {
	index += 1;
    }
#endif

    RETURN ( __mkSmallInteger(index) );
%}

    "
     0 lowBit
     2r0001 lowBit
     2r0010 lowBit
     2r0100 lowBit
     2r1000 lowBit

     2r000100 lowBit
     2r010010 lowBit
     2r100001 lowBit
     16r1000 lowBit
     16r1000000 lowBit
     16r1000000000000000 lowBit

     Time millisecondsToRun:[
	1000000 timesRepeat:[
	    2r1000 lowBit
	]
     ]

     Time millisecondsToRun:[
	1000000 timesRepeat:[
	    2r11110000000 lowBit
	]
     ]

     Time millisecondsToRun:[
	1000000 timesRepeat:[
	    2r1000000000000 lowBit
	]
     ]

     Time millisecondsToRun:[
	1000000 timesRepeat:[
	    2r1000000000000000000000000000 lowBit
	]
     ]
    "
!

rightShift:shiftCount
    "return the value of the receiver shifted by shiftCount bits;
     right shift if shiftCount > 0; left shift  otherwise.
     Notice: the result of bitShift: on negative receivers is not
	     defined in the language standard (since the implementation
	     is free to choose any internal representation for integers).
	     However, ST/X preserves the sign."

%{  /* NOCONTEXT */

    INT bits, count;

    if (__isSmallInteger(shiftCount)) {
	bits = __intVal(self);
	if (bits == 0) {
	    RETURN (self);
	}

	count = __intVal(shiftCount);

	if (count < 0) {
	    /*
	     * a left shift
	     */
	    count = -count;
#if defined(USE_LONGLONG_FOR_SHIFT)
	    if (count <= N_INT_BITS) {
		unsigned LONGLONG result;

		result = (unsigned LONGLONG)bits;
		result <<= count;
		if (result <= _MAX_INT) {
		    RETURN ( __mkSmallInteger(result) );
		}
		{
		    RETURN (__MKLARGEINT64(1, (INT)(result >> 32), (INT)(result & 0xFFFFFFFF)));
		}
	    }
#else
	    /*
	     * check for overflow
	     */
	    if (count < (N_INT_BITS-1)) {
		if (! (bits >> (N_INT_BITS - 1 - count))) {
		    RETURN ( __mkSmallInteger(bits << count) );
		}
		/*
		 * so, there is an overflow ...
		 * handle it as largeInteger
		 */
		/* FALL THROUGH */
	    }
#endif
	} else {
	    if (count == 0) {
		RETURN (self);
	    }

	    /*
	     * right shifts cannot overflow
	     *
	     * some machines ignore shifts bigger than
	     * the number of bits in an int ...
	     */
	    if (count > (N_INT_BITS-1)) {
		RETURN (__mkSmallInteger(0));
	    }

	    RETURN ( __mkSmallInteger(bits >> count) );
	}
    }
%}.
    (shiftCount isMemberOf:SmallInteger) ifTrue:[
	^ (LargeInteger value:self) rightShift:shiftCount
    ].
    ^ self rightShift:(1 coerce:shiftCount)   "/ is this a good idea ?


    "
	16 rightShift:2
	 4 rightShift:-2
    "
!

setBit:anInteger
    "return a new integer where the specified bit is on.
     Bits are counted from 1 starting with the least significant.
     The methods name may be misleading: the receiver is not changed,
     but a new number is returned. Should be named #withBitSet:"

%{  /* NOCONTEXT */

    if (__isSmallInteger(anInteger)) {
        int index = __intVal(anInteger);

        if (index > 0) {
#if __POINTER_SIZE__ == 8
            if (index <= 62)
#else
            if (index <= 30)
#endif
            {
                INT mask = __MASKSMALLINT(1 << (index-1));

                RETURN ( ((OBJ) ((INT)self | (INT)mask)) );
            }
        }
    }
%}.
    ^ super setBit:anInteger

    "
     (16r401 setBit:2     ) hexPrintString
     (16r30000000 setBit:1) hexPrintString
     (16r40000000 setBit:0) hexPrintString
     (16r0 setBit:29) hexPrintString
     (16r0 setBit:30) hexPrintString
     (16r0 setBit:31) hexPrintString
     (16r0 setBit:32) hexPrintString
     (16r0 setBit:33) hexPrintString
     (16r0 setBit:100) hexPrintString
    "
! !

!SmallInteger methodsFor:'bit operators-32bit'!

bitInvert32
    "return the value of the receiver with all bits inverted in 32bit signed int space
     (changes the sign)"

%{  /* NOCONTEXT */
    unsigned INT v;

    v = __intVal(self);
    v = ~v;
#if __POINTER_SIZE__ == 8
    v &= 0xFFFFFFFFL;
#endif
    RETURN ( __MKUINT(v) );
%}.
    ^ self primitiveFailed

    "
     1 bitInvert32
     16r40000000 bitInvert32
     16r80000000 bitInvert32
    "
!

bitRotate32:shiftCount
    "return the value of the receiver rotated by shiftCount bits,
     but only within 32 bits, rotating left for positive, right for negative counts.
     Rotates through the sign bit.
     Useful for crypt algorithms, or to emulate C/Java semantics."

%{  /* NOCONTEXT */

    unsigned INT bits;
    int count;

    if (__isSmallInteger(shiftCount)) {
	count = __intVal(shiftCount);
	count = count % 32;

	bits = __intVal(self);
	if (count > 0) {
	    bits = (bits << count) | (bits >> (32-count));
	} else {
	    bits = (bits >> (-count)) | (bits << (32-(-count)));
	}
#if __POINTER_SIZE__ == 8
	bits &= 0xFFFFFFFFL;
#endif
	RETURN (__MKUINT(bits));
    }
%}.
    ^ self primitiveFailed

    "
     128 rotate32:1

     1 rotate32:1
     1 rotate32:2
     1 rotate32:31
     1 rotate32:32

     1 rotate32:-1
     1 rotate32:-2
     1 rotate32:-3
     1 rotate32:-32
    "
!

bitShift32:shiftCount
    "return the value of the receiver shifted by shiftCount bits,
     but only within 32 bits, shifting into/out-of the sign bit.
     May be useful for communication interfaces, to create ST-numbers
     from a signed 32bit int value given as individual bytes,
     or to emulate C/Java semantics."

%{  /* NOCONTEXT */

    INT bits, count;

    if (__isSmallInteger(shiftCount)) {
	count = __intVal(shiftCount);
	if (count >= 32) {
	    RETURN (__mkSmallInteger(0));
	}

	bits = __intVal(self);
	if (count > 0) {
	    bits = bits << count;
	} else {
	    bits = bits >> (-count);
	}
#if __POINTER_SIZE__ == 8
	bits &= 0xFFFFFFFFL;
#endif
	RETURN (__MKINT(bits));
    }
%}.
    ^ self primitiveFailed

    "
     128 bitShift:24
     128 bitShift32:24

     1 bitShift:31
     1 bitShift32:31
    "
!

bitXor32:aNumber
    "return the xor of the receiver and the argument.
     The argument must be another SmallInteger or a 4-byte LargeInteger.
     If the result overflows the 32 bit range, the value modulo 16rFFFFFFFF is returned.
     This is of course not always correct, but allows for C/Java behavior to be emulated."

%{  /* NOCONTEXT */
    INT rslt;

    rslt =  __unsignedLongIntVal(self) ^ __unsignedLongIntVal(aNumber);
#if __POINTER_SIZE__ == 8
    rslt &= 0xFFFFFFFFL;
#endif
    RETURN ( __MKUINT(rslt));
%}.
    self primitiveFailed

    "
     16r7FFFFFFF bitXor: 16r80000000          4294967295
     16r7FFFFFFF bitXor32: 16r80000000
    "
!

unsignedBitShift32:shiftCount
    "return the value of the receiver shifted by shiftCount bits,
     but only within 32 unsigned bits.
     May be useful for communication interfaces, to create ST-numbers
     from an unsigned 32bit int value given as individual byte,
     or to emulate C/Java semantics."

%{  /* NOCONTEXT */

    unsigned INT bits;
    INT count;

    if (__isSmallInteger(shiftCount)) {
	count = __intVal(shiftCount);
	if (count >= 32) {
	    RETURN (__mkSmallInteger(0));
	}

	bits = __intVal(self);
	if (count > 0) {
	    bits = bits << count;
	} else {
	    bits = bits >> (-count);
	}
#if __POINTER_SIZE__ == 8
	bits &= 0xFFFFFFFFL;
#endif
	RETURN (__MKUINT(bits));
    }
%}.
    ^ self primitiveFailed

    "
     128 unsignedBitShift:24
     128 unsignedBitShift32:24

     1 unsignedBitShift:31
     1 unsignedBitShift32:31

     -1 unsignedBitShift32:-1
     -1 unsignedBitShift32:1
    "
! !

!SmallInteger methodsFor:'byte access'!

byteSwapped 
    "lsb -> msb;
     i.e. a.b.c.d -> d.c.b.a"

    SmallInteger maxBytes == 8 ifTrue:[
        ^ self byteSwapped64
    ] ifFalse:[
        ^ self byteSwapped32
    ].

    "
     16r11223344 byteSwapped hexPrintString  
     16r44332211 byteSwapped hexPrintString   
    "

    "Created: / 09-01-2012 / 23:01:33 / cg"
!

byteSwapped16
    "for 16bit values only:
     lsb -> msb;
     i.e. a.b -> b.a"

%{  /* NOCONTEXT */
    unsigned INT v = __intVal(self);
    unsigned INT swapped;

    swapped = ((v>>8)&0xFF) | ((v & 0xFF)<<8);
    RETURN (__mkSmallInteger(swapped));
%}.

    "
     16r1122 byteSwapped16 hexPrintString   
     16r2211 byteSwapped16 hexPrintString   
     16r332211 byteSwapped16 hexPrintString   
    "
!

byteSwapped32
    "for 32bit values only:
     lsb -> msb;
     i.e. a.b.c.d -> d.c.b.a"

%{  /* NOCONTEXT */
    unsigned INT v = __intVal(self);
    unsigned INT swapped;

#undef HAVE_BSWAP
#if __POINTER_SIZE__ == 4

# if defined(USE_BSWAP) && defined(__BORLANDC__)
#   define HAVE_BSWAP

    _asm {
        mov eax, v
        bswap eax
        mov swapped, eax
    };
# endif
# if defined(USE_BSWAP) && defined(__VISUALC__)
#   define HAVE_BSWAP

    _asm {
        mov eax, v
        xchg al, ah
        rol eax, 16
        xchg al, ah
        mov swapped, eax
    };
# endif
# if defined(USE_BSWAP) && defined(__GNUC__)
#   define HAVE_BSWAP

    asm("movl %0, %%eax \n\
         bswap %%eax    \n\
         movl %%eax, %1 \n\
        "
        : "=rm"  (swapped)
        : "rm"   (v));
# endif
#endif /* __POINTER_SIZE__ == 4 */

#if __POINTER_SIZE__ == 8
    v &= 0xFFFFFFFF;

# if defined(__x86_64__) && defined(__GNUC__)
#   define HAVE_BSWAP

    asm("movq %0, %%rax \n\
         bswap %%eax    \n\
         movq %%rax, %1 \n\
        "
        : "=rm"  (swapped)
        : "rm"   (v));
# endif
#endif

#ifndef HAVE_BSWAP
    swapped = ((v>>24) | ((v>>8)&0xFF00) | ((v & 0xFF00)<<8) | ((v & 0xFF)<<24));
#endif

    RETURN (__MKUINT(swapped));
%}.

    "
     16r11223344 byteSwapped32 hexPrintString  
     16r44332211 byteSwapped32 hexPrintString   
    "

    "Created: / 09-01-2012 / 23:01:33 / cg"
!

byteSwapped64
    "for 64bit values only:
     lsb -> msb;
     i.e. a.b.c.d.e.f.g.h -> h.g.f.e.d.c.b.a"

%{  /* NOCONTEXT */
    unsigned INT v = __intVal(self);
    unsigned INT swapped;

#if __POINTER_SIZE__ == 4
    //   xxxxxxxx 00000000 00000000 00000000 -> 00000000 00000000 00000000 xxxxxxxx  
    //            xxxxxxxx                                        xxxxxxxx
    //                     xxxxxxxx                      xxxxxxxx
    //                              xxxxxxxx    xxxxxxxx
    swapped = (v>>24) | ((v>>8)&0xFF00) | ((v & 0xFF00)<<8) | ((v & 0xFF)<<24);
#else
    //   xxxxxxxx 00000000 00000000 00000000 -> 00000000 00000000 00000000 xxxxxxxx  
    //            xxxxxxxx                                        xxxxxxxx
    //                     xxxxxxxx                      xxxxxxxx
    //                              xxxxxxxx    xxxxxxxx
    swapped =  (v>>56) | ((v>>40)&0xFF00) | ((v>>24) & 0xFF0000) | ((v>>8) & 0xFF000000)
                | ((v & 0xFF000000)<<8) | ((v & 0x00FF0000)<<24) | ((v & 0x0000FF00)<<40)
                | ((v & 0xFF)<<56);
#endif
    return __MKUINT( swapped );
%}.

    "
     16r11223344 byteSwapped64 hexPrintString  
     16r44332211 byteSwapped64 hexPrintString   
    "

    "Created: / 09-01-2012 / 23:01:33 / cg"
!

digitAt:index
    "return 8 bits of value, starting at byte index"

%{  /* NOCONTEXT */

    REGISTER INT val;
    INT idx;

    if (__isSmallInteger(index)) {
	val = __intVal(self);
	if (val < 0)
	    val = -val;
	switch (idx = __intVal(index)) {
	    case 1:
		break;
	    case 2:
		val = (val >> 8);
		break;
	    case 3:
		val = (val >> 16);
		break;
	    case 4:
		val = (val >> 24);
		break;
#if __POINTER_SIZE__ == 8
	    case 5:
		val = (val >> 32);
		break;
	    case 6:
		val = (val >> 40);
		break;
	    case 7:
		val = (val >> 48);
		break;
	    case 8:
		val = (val >> 56);
		break;
#endif
	    default:
		if (idx < 1)
		    goto bad;   /* sorry */
		RETURN (__mkSmallInteger(0));
	}
	RETURN ( __mkSmallInteger( val & 0xFF) );
    }
  bad: ;
%}.
    index > 0 ifFalse:[
	"
	 index less than 1 - not allowed
	"
	^ self primitiveFailed
    ].
    ^ 0

    "
     (16r12345678 digitAt:1) printStringRadix:16
     (16r12345678 digitAt:3) printStringRadix:16
     (16r12345678 digitAt:15) printStringRadix:16
     (16r12345678 digitAt:0) printStringRadix:16
     (16r12345678 digitAt:-10) printStringRadix:16
    "
!

digitByteAt:index
    "return 8 bits of my signed value, starting at byte index.
     For positive receivers, this is the same as #digitAt:;
     for negative ones, the actual bit representation is returned."

%{  /* NOCONTEXT */

    REGISTER INT val;
    INT idx;

    if (__isSmallInteger(index)) {
	val = __intVal(self);
	switch (idx = __intVal(index)) {
	    case 1:
		break;
	    case 2:
		val = (val >> 8);
		break;
	    case 3:
		val = (val >> 16);
		break;
	    case 4:
		val = (val >> 24);
		break;
#if __POINTER_SIZE__ == 8
	    case 5:
		val = (val >> 32);
		break;
	    case 6:
		val = (val >> 40);
		break;
	    case 7:
		val = (val >> 48);
		break;
	    case 8:
		val = (val >> 56);
		break;
#endif
	    default:
		if (idx < 1)
		    goto bad;   /* sorry */
		if (val < 0) {
		    RETURN (__mkSmallInteger(0xFF));
		}
		RETURN (__mkSmallInteger(0));
	}
	RETURN ( __mkSmallInteger( val & 0xFF) );
    }
  bad: ;
%}.
    index > 0 ifFalse:[
	"
	 index less than 1 - not allowed
	"
	^ self primitiveFailed
    ].
    ^ 0

    "
     (10 digitByteAt:1) printStringRadix:16
     (10 digitByteAt:3) printStringRadix:16
     (-10 digitByteAt:1) printStringRadix:16
     (-10 digitByteAt:3) printStringRadix:16
    "
!

digitBytes
    "return a byteArray filled with the receivers bits
     (8 bits of the absolute value per element),
     least significant byte is first"

    |absValue
     b1 "{ Class: SmallInteger }"
     b2 "{ Class: SmallInteger }"
     b3 "{ Class: SmallInteger }"
     b4 "{ Class: SmallInteger }"
     b5 "{ Class: SmallInteger }"
     b6 "{ Class: SmallInteger }"
     b7 "{ Class: SmallInteger }" digitByteArray|

    "
     could have simply created a 4-byte largeinteger and normalize it.
     The code below does the normalize right away, avoiding the
     overhead of producing any intermediate byte-arrays (and the scanning)
    "
    self == 0 ifTrue: [
        ^ ByteArray with:0.
    ].

    self < 0 ifTrue: [
        absValue := self negated
    ] ifFalse: [
        absValue := self.
    ].

    b1 := absValue bitAnd:16rFF.
    absValue := absValue bitShift:-8.
    absValue == 0 ifTrue:[
        digitByteArray := ByteArray with:b1
    ] ifFalse:[
        b2 := absValue bitAnd:16rFF.
        absValue := absValue bitShift:-8.
        absValue == 0 ifTrue:[
            digitByteArray := ByteArray with:b1 with:b2
        ] ifFalse:[
            b3 := absValue bitAnd:16rFF.
            absValue := absValue bitShift:-8.
            absValue == 0 ifTrue:[
                digitByteArray := ByteArray with:b1 with:b2 with:b3
            ] ifFalse:[
                b4 := absValue bitAnd:16rFF.
                absValue := absValue bitShift:-8.
                absValue == 0 ifTrue:[
                    digitByteArray := ByteArray with:b1 with:b2 with:b3 with:b4
                ] ifFalse:[
                    b5 := absValue bitAnd:16rFF.
                    absValue := absValue bitShift:-8.
                    absValue == 0 ifTrue:[
                        digitByteArray := ByteArray new:5.
                        digitByteArray at:1 put:b1.
                        digitByteArray at:2 put:b2.
                        digitByteArray at:3 put:b3.
                        digitByteArray at:4 put:b4.
                        digitByteArray at:5 put:b5.
                    ] ifFalse:[
                        b6 := absValue bitAnd:16rFF.
                        absValue := absValue bitShift:-8.
                        absValue == 0 ifTrue:[
                            digitByteArray := ByteArray new:6.
                            digitByteArray at:1 put:b1.
                            digitByteArray at:2 put:b2.
                            digitByteArray at:3 put:b3.
                            digitByteArray at:4 put:b4.
                            digitByteArray at:5 put:b5.
                            digitByteArray at:6 put:b6.
                        ] ifFalse:[
                            b7 := absValue bitAnd:16rFF.
                            absValue := absValue bitShift:-8.
                            absValue == 0 ifTrue:[
                                digitByteArray := ByteArray new:7.
                                digitByteArray at:1 put:b1.
                                digitByteArray at:2 put:b2.
                                digitByteArray at:3 put:b3.
                                digitByteArray at:4 put:b4.
                                digitByteArray at:5 put:b5.
                                digitByteArray at:6 put:b6.
                                digitByteArray at:7 put:b7.
                            ] ifFalse:[
                                digitByteArray := ByteArray new:8.
                                digitByteArray at:1 put:b1.
                                digitByteArray at:2 put:b2.
                                digitByteArray at:3 put:b3.
                                digitByteArray at:4 put:b4.
                                digitByteArray at:5 put:b5.
                                digitByteArray at:6 put:b6.
                                digitByteArray at:7 put:b7.
                                digitByteArray at:8 put:absValue.
                            ]
                        ]
                    ]
                ]
            ]
        ]
    ].

    ^ digitByteArray

    "
      16r12 digitBytes hexPrintString
      16r1234 digitBytes hexPrintString
      16r12345678 digitBytes hexPrintString
    "
!

digitBytesMSB
    "return a byteArray filled with the receivers bits
     (8 bits of the absolute value per element),
     most significant byte is first"

    |absValue
     b1 "{ Class: SmallInteger }"
     b2 "{ Class: SmallInteger }"
     b3 "{ Class: SmallInteger }"
     b4 "{ Class: SmallInteger }"
     b5 "{ Class: SmallInteger }"
     b6 "{ Class: SmallInteger }"
     b7 "{ Class: SmallInteger }" digitByteArray|

    "
     could have simply created a 4-byte largeinteger and normalize it.
     The code below does the normalize right away, avoiding the
     overhead of producing any intermediate byte-arrays (and the scanning)
    "
    self == 0 ifTrue: [
        ^ ByteArray with:0.
    ].

    self < 0 ifTrue: [
        absValue := self negated
    ] ifFalse: [
        absValue := self.
    ].

    b1 := absValue bitAnd:16rFF.
    absValue := absValue bitShift:-8.
    absValue == 0 ifTrue:[
        digitByteArray := ByteArray with:b1
    ] ifFalse:[
        b2 := absValue bitAnd:16rFF.
        absValue := absValue bitShift:-8.
        absValue == 0 ifTrue:[
            digitByteArray := ByteArray with:b2 with:b1
        ] ifFalse:[
            b3 := absValue bitAnd:16rFF.
            absValue := absValue bitShift:-8.
            absValue == 0 ifTrue:[
                digitByteArray := ByteArray with:b3 with:b2 with:b1
            ] ifFalse:[
                b4 := absValue bitAnd:16rFF.
                absValue := absValue bitShift:-8.
                absValue == 0 ifTrue:[
                    digitByteArray := ByteArray with:b4 with:b3 with:b2 with:b1
                ] ifFalse:[
                    b5 := absValue bitAnd:16rFF.
                    absValue := absValue bitShift:-8.
                    absValue == 0 ifTrue:[
                        digitByteArray := ByteArray new:5.
                        digitByteArray at:1 put:b5.
                        digitByteArray at:2 put:b4.
                        digitByteArray at:3 put:b3.
                        digitByteArray at:4 put:b2.
                        digitByteArray at:5 put:b1.
                    ] ifFalse:[
                        b6 := absValue bitAnd:16rFF.
                        absValue := absValue bitShift:-8.
                        absValue == 0 ifTrue:[
                            digitByteArray := ByteArray new:6.
                            digitByteArray at:1 put:b6.
                            digitByteArray at:2 put:b5.
                            digitByteArray at:3 put:b4.
                            digitByteArray at:4 put:b3.
                            digitByteArray at:5 put:b2.
                            digitByteArray at:6 put:b1.
                        ] ifFalse:[
                            b7 := absValue bitAnd:16rFF.
                            absValue := absValue bitShift:-8.
                            absValue == 0 ifTrue:[
                                digitByteArray := ByteArray new:7.
                                digitByteArray at:1 put:b7.
                                digitByteArray at:2 put:b6.
                                digitByteArray at:3 put:b5.
                                digitByteArray at:4 put:b4.
                                digitByteArray at:5 put:b3.
                                digitByteArray at:6 put:b2.
                                digitByteArray at:7 put:b1.
                            ] ifFalse:[
                                digitByteArray := ByteArray new:8.
                                digitByteArray at:1 put:absValue.
                                digitByteArray at:2 put:b7.
                                digitByteArray at:3 put:b6.
                                digitByteArray at:4 put:b5.
                                digitByteArray at:5 put:b4.
                                digitByteArray at:6 put:b3.
                                digitByteArray at:7 put:b2.
                                digitByteArray at:8 put:b1.
                            ]
                        ]
                    ]
                ]
            ]
        ]
    ].

    ^ digitByteArray

    "
      16r12 digitBytesMSB hexPrintString
      16r1234 digitBytesMSB hexPrintString
      16r12345678 digitBytesMSB hexPrintString
    "
!

digitLength
    "return the number bytes required to represent this Integer.
     For negative receivers, the digitLength of its absolute value
     is returned."

%{  /* NOCONTEXT */

    INT val = __intVal(self);

    if (val < 0) {
	val = -val;
    }
#if __POINTER_SIZE__ == 8
    if (val & 0xFFFFFFFF00000000L) {
	if (val & 0xFFFF000000000000L) {
	    if (val & 0xFF00000000000000L) {
		RETURN ( __mkSmallInteger(8));
	    } else {
		RETURN ( __mkSmallInteger(7));
	    }
	} else {
	    if (val & 0x0000FF0000000000L) {
		RETURN ( __mkSmallInteger(6));
	    } else {
		RETURN ( __mkSmallInteger(5));
	    }
	}
    }
#endif

    if (val & 0xFFFF0000) {
	if (val & 0xFF000000) {
	    RETURN ( __mkSmallInteger(4));
	} else {
	    RETURN ( __mkSmallInteger(3));
	}
    } else {
	if (val & 0x0000FF00) {
	    RETURN ( __mkSmallInteger(2));
	} else {
	    RETURN ( __mkSmallInteger(1));
	}
    }

%}.
    ^ self abs highBit - 1 // 8 + 1

    "
     16rFF00000000000000 digitLength
     -16rFF00000000000000 digitLength

     16rFF000000 digitLength
     16rFF0000 digitLength
     16rFF00 digitLength
     16rFF digitLength
     -16rFF000000 digitLength
     -16rFF0000 digitLength
     -16rFF00 digitLength
     -16rFF digitLength
    "
!

swapBytes
    "swap byte pair-wise in an integer
     i.e. a.b.c.d -> b.a.d.c"

%{  /* NOCONTEXT */

    unsigned INT v = __intVal(self);
    unsigned INT swapped;

#if __POINTER_SIZE__ == 8
    swapped = ((v >> 8) & 0x00FF00FF00FF00FF) | ((v & 0x00FF00FF00FF00FF) << 8);
#else
    swapped = ((v >> 8) & 0x00FF00FF) | ((v & 0x00FF00FF) << 8);
#endif /* __POINTER_SIZE__ */
    if (__ISVALIDINTEGER(swapped)) {
        RETURN ( __mkSmallInteger(swapped) );
    }
    RETURN (__MKUINT(swapped));
%}.
    ^ super swapBytes

    "
     16r11223344 swapBytes hexPrintString   
     16r44332211 swapBytes hexPrintString   
     16r1122334455667788 swapBytes hexPrintString   
     16r11223344556677889900 swapBytes hexPrintString   
    "

    "Created: / 09-01-2012 / 23:01:33 / cg"
! !

!SmallInteger methodsFor:'catching messages'!

basicAt:index
    "catch indexed access - report an error
     defined here since basicAt: in Object ommits the SmallInteger check."

    ^ self notIndexed
!

basicAt:index put:anObject
    "catch indexed access - report an error
     defined here since basicAt:put: in Object ommits the SmallInteger check."

    self notIndexed
!

basicSize
    "return the number of indexed instvars - SmallIntegers have none.
     Defined here since basicSize in Object ommits the SmallInteger check."

    ^ 0
!

size
    "return the number of indexed instvars - SmallIntegers have none."

    ^ 0
! !

!SmallInteger methodsFor:'coercing & converting'!

asCharacter
    "Return a character with the receiver as ascii value"

    ^ Character value:self
!

asFloat
    "return a Float with same value as receiver.
     Redefined for performance (machine can do it faster)"

%{  /* NOCONTEXT */

    OBJ newFloat;
    double dVal = (double)__intVal(self);

    __qMKFLOAT(newFloat, dVal);
    RETURN ( newFloat );
%}.
    ^ self primitiveFailed
!

asLargeInteger
    "return a LargeInteger with same value as receiver"

    ^ LargeInteger value:self
!

asShortFloat
    "return a ShortFloat with same value as receiver.
     Redefined for performance (machine can do it faster)"

%{  /* NOCONTEXT */

    OBJ dummy = @global(ShortFloat);
    OBJ newFloat;
    float fVal = (float)__intVal(self);

    __qMKSFLOAT(newFloat, fVal);
    RETURN ( newFloat );
%}.
    ^ self primitiveFailed
!

codePoint
    "for compatibility with Characters.
     (Allows for integers to be stored into U16/U32 strings)"

    ^ self
!

coerce:aNumber
    "convert the argument aNumber into an instance of the receivers class and return it."

    ^ aNumber asInteger
!

generality
    "return the generality value - see ArithmeticValue>>retry:coercing:"

    ^ 20
!

signExtended24BitValue
    "return a smallInteger from sign-extending the 24'th bit.
     May be useful for communication interfaces"

%{  /* NOCONTEXT */
    INT i = __intVal(self);

    if (i & 0x800000) {
	i = i | ~0xFFFFFFL;
    } else {
	i = i & 0x7FFFFF;
    }

    RETURN (__mkSmallInteger(i));
%}.
    ^ self primitiveFailed

    "
     16rFFFFFF signExtended24BitValue
     16r800000 signExtended24BitValue
     16r7FFFFF signExtended24BitValue
    "
!

signExtendedByteValue
    "return a smallInteger from sign-extending the 8'th bit.
     May be useful for communication interfaces"

%{  /* NOCONTEXT */
    INT i = __intVal(self);

    if (i & 0x80) {
	i = i | ~0xFFL;
    } else {
	i = i & 0x7F;
    }

    RETURN (__mkSmallInteger(i));
%}.
    ^ self primitiveFailed

    "
     16rFF signExtendedByteValue
     16r80 signExtendedByteValue
     16r7F signExtendedByteValue
    "
!

signExtendedLongValue
    "return a smallInteger from sign-extending the 32'th bit.
     May be useful for communication interfaces"

%{  /* NOCONTEXT */
    INT i = __intVal(self);

    if (i & 0x80000000) {
        i = i | ~0xFFFFFFFFL;
    } else {
        i = i & 0x7FFFFFFF;
    }

    RETURN (__mkSmallInteger(i));
%}.
    ^ self primitiveFailed

    "
     16rFFFFFFFF signExtendedLongValue
     16r80000000 signExtendedLongValue
     16r7FFFFFFF signExtendedLongValue
    "
!

signExtendedShortValue
    "return a smallInteger from sign-extending the 16'th bit.
     May be useful for communication interfaces"

%{  /* NOCONTEXT */
    INT i = __intVal(self);

    if (i & 0x8000) {
	i = i | ~0xFFFFL;
    } else {
	i = i & 0x7FFF;
    }

    RETURN (__mkSmallInteger(i));
%}.
    ^ self primitiveFailed

    "
     16rFFFF signExtendedShortValue
     16r8000 signExtendedShortValue
     16r7FFF signExtendedShortValue
    "
! !

!SmallInteger methodsFor:'comparing'!

< aNumber
    "return true, if the argument is greater than the receiver"

%{  /* NOCONTEXT */

    if (__isSmallInteger(aNumber)) {
#ifdef POSITIVE_ADDRESSES
	RETURN ( (__intVal(self) < __intVal(aNumber)) ? true : false );
#else
	/* tag bit does not change ordering */
	RETURN ( ((INT)self < (INT)aNumber) ? true : false );
#endif
    }
    if (__isFloatLike(aNumber)) {
	RETURN ( ((double)__intVal(self) < __floatVal(aNumber)) ? true : false );
    }
%}.
    ^ aNumber lessFromInteger:self
    "^ self retry:#< coercing:aNumber"
!

<= aNumber
    "return true, if the argument is greater or equal"

%{  /* NOCONTEXT */

    if (__isSmallInteger(aNumber)) {
#ifdef POSITIVE_ADDRESSES
	RETURN ( (__intVal(self) <= __intVal(aNumber)) ? true : false );
#else
	/* tag bit does not change ordering */
	RETURN ( ((INT)self <= (INT)aNumber) ? true : false );
#endif
    }
    if (__isFloatLike(aNumber)) {
	RETURN ( ((double)__intVal(self) <= __floatVal(aNumber)) ? true : false );
    }
%}.
    ^ (self > aNumber) not

    "Modified: / 31.7.2002 / 10:07:17 / cg"
!

= aNumber
    "return true, if the argument represents the same numeric value
     as the receiver, false otherwise"

%{  /* NOCONTEXT */

    if (aNumber == self) {
	RETURN ( true );
    }
    if (! __isNonNilObject(aNumber)) {
	/* a smallint or nil */
	RETURN ( false );
    }

    if (__qIsFloatLike(aNumber)) {
	RETURN ( ((double)__intVal(self) == __floatVal(aNumber)) ? true : false );
    }
    if (__qIsShortFloat(aNumber)) {
	RETURN ( ((double)__intVal(self) == __shortFloatVal(aNumber)) ? true : false );
    }
%}.
    ^ aNumber equalFromInteger:self
!

> aNumber
    "return true, if the argument is less than the receiver"

%{  /* NOCONTEXT */

    if (__isSmallInteger(aNumber)) {
#ifdef POSITIVE_ADDRESSES
	RETURN ( (__intVal(self) > __intVal(aNumber)) ? true : false );
#else
	/* tag bit does not change ordering */
	RETURN ( ((INT)self > (INT)aNumber) ? true : false );
#endif
    }
    if (__isFloatLike(aNumber)) {
	RETURN ( ((double)__intVal(self) > __floatVal(aNumber)) ? true : false );
    }
%}.
    ^ (aNumber < self)

    "Modified: / 31.7.2002 / 10:07:05 / cg"
!

>= aNumber
    "return true, if the argument is less or equal"

%{  /* NOCONTEXT */

    if (__isSmallInteger(aNumber)) {
#ifdef POSITIVE_ADDRESSES
	RETURN ( (__intVal(self) >= __intVal(aNumber)) ? true : false );
#else
	/* tag bit does not change ordering */
	RETURN ( ((INT)self >= (INT)aNumber) ? true : false );
#endif
    }
    if (__isFloatLike(aNumber)) {
	RETURN ( ((double)__intVal(self) >= __floatVal(aNumber)) ? true : false );
    }
%}.
    ^ (self < aNumber) not

    "Modified: / 31.7.2002 / 10:07:11 / cg"
!

hash
    "return an integer useful for hashing on value"

    self >= 0 ifTrue:[^ self].
    ^ self negated
!

identityHash
    "return an integer useful for hashing on identity"

     self >= 0 ifTrue:[^ self].
     ^ self negated

    "Modified: 11.11.1996 / 18:42:14 / cg"
!

max:aNumber
    "return the receiver or the argument, whichever is greater"

%{  /* NOCONTEXT */

    if (__isSmallInteger(aNumber)) {
#if TAG_INT == 1
	/* tag bit does not change ordering */
	if ((INT)(self) > (INT)(aNumber))
#else
	if (__intVal(self) > __intVal(aNumber))
#endif
	{
	    RETURN ( self );
	}
	RETURN ( aNumber );
    }
    if (__isFloatLike(aNumber)) {
	if ( (double)__intVal(self) > __floatVal(aNumber) ) {
	    RETURN ( self );
	}
	RETURN ( aNumber );
    }
%}.
    "/ fallback for non-smallInteger argument

    (self > aNumber) ifTrue:[^ self].
    ^ aNumber
!

min:aNumber
    "return the receiver or the argument, whichever is smaller"

%{  /* NOCONTEXT */

    if (__isSmallInteger(aNumber)) {
#if TAG_INT == 1
	/* tag bit does not change ordering */
	if ((INT)(self) < (INT)(aNumber))
#else
	if (__intVal(self) < __intVal(aNumber))
#endif
	{
	    RETURN ( self );
	}
	RETURN ( aNumber );
    }
    if (__isFloatLike(aNumber)) {
	if ( (double)__intVal(self) < __floatVal(aNumber) ) {
	    RETURN ( self );
	}
	RETURN ( aNumber );
    }
%}.
    "/ fallback for non-smallInteger argument

    (self < aNumber) ifTrue:[^ self].
    ^ aNumber
!

~= aNumber
    "return true, if the arguments value is not equal to mine"

%{  /* NOCONTEXT */

    if (aNumber == self) {
	RETURN ( false );
    }
    if (! __isNonNilObject(aNumber)) {
	/* a smallint or nil */
	RETURN ( true );
    }

    if (__qIsFloatLike(aNumber)) {
	RETURN ( ((double)__intVal(self) != __floatVal(aNumber)) ? true : false );
    }
    if (__qIsShortFloat(aNumber)) {
	RETURN ( ((double)__intVal(self) != __shortFloatVal(aNumber)) ? true : false );
    }
%}.
    ^ (self = aNumber) not
! !

!SmallInteger methodsFor:'copying'!

deepCopy
    "return a deep copy of myself
     - reimplemented here since smallintegers are unique"

    ^ self
!

deepCopyUsing:aDictionary postCopySelector:postCopySelector
    "return a deep copy of myself
     - reimplemented here since smallintegers are unique"

    ^ self
!

shallowCopy
    "return a shallow copy of myself
     - reimplemented here since smallintegers are unique"

    ^ self
!

simpleDeepCopy
    "return a deep copy of myself
     - reimplemented here since smallintegers are unique"

    ^ self
! !

!SmallInteger methodsFor:'iteration'!

timesRepeat:aBlock
    "evaluate the argument, aBlock self times.
     Reimplemented as primitive for speed"

%{
    REGISTER INT tmp;
    static struct inlineCache blockVal = __ILC0(0);

    tmp = __intVal(self);
    if (tmp > 0) {
	if (__isBlockLike(aBlock)
	 && (__BlockInstPtr(aBlock)->b_nargs == __mkSmallInteger(0))) {
	    {
		REGISTER OBJFUNC codeVal;

		/*
		 * specially tuned version for compiled blocks,
		 * (the most common case)
		 */
		if (((codeVal = __BlockInstPtr(aBlock)->b_code) != (OBJFUNC)nil)
#ifdef PARANOIA
		 && (! ((INT)(__BlockInstPtr(aBlock)->b_flags) & __MASKSMALLINT(F_DYNAMIC)))
#endif
		) {

#ifdef NEW_BLOCK_CALL

#                   define BLOCK_ARG  aBlock

#else

#                   define BLOCK_ARG  rHome
		    REGISTER OBJ rHome;

		    /*
		     * home on stack - no need to refetch
		     */
		    rHome = __BlockInstPtr(aBlock)->b_home;
		    if ((rHome == nil) || (__qSpace(rHome) >= STACKSPACE))
#endif
		    {
#ifdef __UNROLL_LOOPS__

			/*
			 * you are not supposed to program like this - I know what I do
			 */
			while (tmp > 8) {
			    if (InterruptPending != nil) goto interrupted0;
	continue0:
			    (*codeVal)(BLOCK_ARG);
			    if (InterruptPending != nil) goto interrupted1;
	continue1:
			    (*codeVal)(BLOCK_ARG);
			    if (InterruptPending != nil) goto interrupted2;
	continue2:
			    (*codeVal)(BLOCK_ARG);
			    if (InterruptPending != nil) goto interrupted3;
	continue3:
			    (*codeVal)(BLOCK_ARG);
			    if (InterruptPending != nil) goto interrupted4;
	continue4:
			    (*codeVal)(BLOCK_ARG);
			    if (InterruptPending != nil) goto interrupted5;
	continue5:
			    (*codeVal)(BLOCK_ARG);
			    if (InterruptPending != nil) goto interrupted6;
	continue6:
			    (*codeVal)(BLOCK_ARG);
			    if (InterruptPending != nil) goto interrupted7;
	continue7:
			    (*codeVal)(BLOCK_ARG);
			    tmp -= 8;
			}
#endif /* __UNROLL_LOOPS__ */
			do {
			    if (InterruptPending != nil) goto interruptedX;
	continueX:
			    (*codeVal)(BLOCK_ARG);
			} while(--tmp);

			RETURN (self);
			if (0) {
#ifdef __UNROLL_LOOPS__
			    interrupted0:
						__interruptL(@line); goto continue0;
			    interrupted1:
						__interruptL(@line); goto continue1;
			    interrupted2:
						__interruptL(@line); goto continue2;
			    interrupted3:
						__interruptL(@line); goto continue3;
			    interrupted4:
						__interruptL(@line); goto continue4;
			    interrupted5:
						__interruptL(@line); goto continue5;
			    interrupted6:
						__interruptL(@line); goto continue6;
			    interrupted7:
						__interruptL(@line); goto continue7;
#endif /* __UNROLL_LOOPS__ */
			    interruptedX:
						__interruptL(@line); goto continueX;
			}
		    }
		}
	    }

#           undef BLOCK_ARG

#ifdef NEW_BLOCK_CALL
#           define BLOCK_ARG  aBlock
#           define IBLOCK_ARG nil
#else
#           define BLOCK_ARG  (__BlockInstPtr(aBlock)->b_home)
#           define IBLOCK_ARG (__BlockInstPtr(aBlock)->b_home)
#endif

	    /*
	     * sorry - must check for the blocks code within the loops;
	     * it could be recompiled or flushed (in the interrupt)
	     */
	    do {
		REGISTER OBJFUNC codeVal;

		if ((codeVal = __BlockInstPtr(aBlock)->b_code) != (OBJFUNC)nil) {
		    /*
		     * arg is a compiled block with code -
		     * directly call it without going through Block>>value
		     * however, if there is an interrupt, refetch the code pointer.
		     */
		    /* stay here, while no interrupts are pending ... */
		    do {
			(*codeVal)(BLOCK_ARG);
			if (InterruptPending != nil) goto outerLoop;
		    } while (--tmp);
		    RETURN (self);
		} else {
		    if (InterruptPending != nil) __interruptL(@line);

		    if (__BlockInstPtr(aBlock)->b_bytecodes != nil) {
			/*
			 * arg is a compiled block with bytecode -
			 * directly call interpreter without going through Block>>value
			 */
			__interpret(aBlock, 0, nil, IBLOCK_ARG, nil, nil);
		    } else {
			/*
			 * arg is something else - call it with #value
			 */
			(*blockVal.ilc_func)(aBlock, @symbol(value), nil, &blockVal);
		    }
		}
    outerLoop: ;
	    } while (--tmp);

#           undef BLOCK_ARG
#           undef IBLOCK_ARG

	    RETURN (self);
	}

	/*
	 * not a block-like thingy - call it with #value
	 */
	do {
	    if (InterruptPending != nil) __interruptL(@line);
	    (*blockVal.ilc_func)(aBlock, @symbol(value), nil, &blockVal);
	} while(--tmp);
	RETURN (self);
    }
%}.
    ^ super timesRepeat:aBlock

"/    |count "{ Class: SmallInteger }" |
"/
"/    count := self.
"/    [count > 0] whileTrue:[
"/        aBlock value.
"/        count := count - 1
"/    ]
!

to:stop by:incr do:aBlock
    "reimplemented as primitive for speed"

%{
    REGISTER INT tmp, step;
    REGISTER INT final;
    static struct inlineCache blockVal = __ILC1(0);

    if (__bothSmallInteger(incr, stop)) {
	tmp = __intVal(self);
	final = __intVal(stop);
	step = __intVal(incr);

	if (__isBlockLike(aBlock)
	 && (__BlockInstPtr(aBlock)->b_nargs == __mkSmallInteger(1))) {
	    {
		REGISTER OBJFUNC codeVal;

		/*
		 * specially tuned version for static compiled blocks, called with
		 * home on the stack (the most common case)
		 */
		if (((codeVal = __BlockInstPtr(aBlock)->b_code) != (OBJFUNC)nil)
#ifdef PARANOIA
		 && (! ((INT)(__BlockInstPtr(aBlock)->b_flags) & __MASKSMALLINT(F_DYNAMIC)))
#endif
		) {

#ifdef NEW_BLOCK_CALL

#                   define BLOCK_ARG  aBlock

#else

#                   define BLOCK_ARG  rHome
		    REGISTER OBJ rHome;
		    rHome = __BlockInstPtr(aBlock)->b_home;
		    if ((rHome == nil) || (__qSpace(rHome) >= STACKSPACE))

#endif
		    {
			if (step < 0) {
			    if (step == -1) {
				while (tmp >= final) {
				    if (InterruptPending != nil) __interruptL(@line);
				    (*codeVal)(BLOCK_ARG, __mkSmallInteger(tmp));
				    tmp--;
				}
			    } else {
				while (tmp >= final) {
				    if (InterruptPending != nil) __interruptL(@line);
				    (*codeVal)(BLOCK_ARG, __mkSmallInteger(tmp));
				    tmp += step;
				}
			    }
			} else {
			    if (step == 1) {
				while (tmp <= final) {
				    if (InterruptPending != nil) __interruptL(@line);
				    (*codeVal)(BLOCK_ARG, __mkSmallInteger(tmp));
				    tmp++;
				}
			    } else {
				while (tmp <= final) {
				    if (InterruptPending != nil) __interruptL(@line);
				    (*codeVal)(BLOCK_ARG, __mkSmallInteger(tmp));
				    tmp += step;
				}
			    }
			}
			RETURN (self);
		    }
		}
	    }

	    /*
	     * sorry - must check for the blocks code within the loops;
	     * it could be recompiled or flushed (in the interrupt)
	     */

#           undef BLOCK_ARG

#ifdef NEW_BLOCK_CALL
#           define BLOCK_ARG  aBlock
#           define IBLOCK_ARG nil
#else
#           define BLOCK_ARG  (__BlockInstPtr(aBlock)->b_home)
#           define IBLOCK_ARG (__BlockInstPtr(aBlock)->b_home)
#endif

	    if (step < 0) {
		while (tmp >= final) {
		    REGISTER OBJFUNC codeVal;

		    if (InterruptPending != nil) __interruptL(@line);

		    if ((codeVal = __BlockInstPtr(aBlock)->b_code) != (OBJFUNC)nil) {
			/*
			 * arg is a compiled block with code -
			 * directly call it without going through Block>>value
			 */
			(*codeVal)(BLOCK_ARG, __mkSmallInteger(tmp));
		    } else {
			if (__BlockInstPtr(aBlock)->b_bytecodes != nil) {
			    /*
			     * arg is a compiled block with bytecode -
			     * directly call interpreter without going through Block>>value
			     */
#ifdef PASS_ARG_POINTER
			    {
				OBJ idx;

				idx = __mkSmallInteger(tmp);
				__interpret(aBlock, 1, nil, IBLOCK_ARG, nil, nil, &idx);
			    }
#else
			    __interpret(aBlock, 1, nil, IBLOCK_ARG, nil, nil, __mkSmallInteger(tmp));
#endif

			} else {
			    /*
			     * arg is something else - call it with #value
			     */
			    (*blockVal.ilc_func)(aBlock, @symbol(value:), nil, &blockVal, __mkSmallInteger(tmp));
			}
		    }
		    tmp += step;
		}
	    } else {
		while (tmp <= final) {
		    REGISTER OBJFUNC codeVal;

		    if (InterruptPending != nil) __interruptL(@line);

		    if ((codeVal = __BlockInstPtr(aBlock)->b_code) != (OBJFUNC)nil) {
			/*
			 * arg is a compiled block with code -
			 * directly call it without going through Block>>value
			 */
			(*codeVal)(BLOCK_ARG, __mkSmallInteger(tmp));
		    } else {
			if (__BlockInstPtr(aBlock)->b_bytecodes != nil) {
			    /*
			     * arg is a compiled block with bytecode -
			     * directly call interpreter without going through Block>>value
			     */
#ifdef PASS_ARG_POINTER
			    {
				OBJ idx;

				idx = __mkSmallInteger(tmp);
				__interpret(aBlock, 1, nil, IBLOCK_ARG, nil, nil, &idx);
			    }
#else
			    __interpret(aBlock, 1, nil, IBLOCK_ARG, nil, nil, __mkSmallInteger(tmp));
#endif

			} else {
			    /*
			     * arg is something else - call it with #value:
			     */
			    (*blockVal.ilc_func)(aBlock, @symbol(value:), nil, &blockVal, __mkSmallInteger(tmp));
			}
		    }
		    tmp += step;
		}
	    }

#           undef BLOCK_ARG
#           undef IBLOCK_ARG

	} else {
	    /*
	     * arg is something else - call it with #value:
	     */
	    if (step < 0) {
		while (tmp >= final) {
		    if (InterruptPending != nil) __interruptL(@line);

		    (*blockVal.ilc_func)(aBlock,
					 @symbol(value:),
					 nil, &blockVal,
					 __mkSmallInteger(tmp));
		    tmp += step;
		}
	    } else {
		while (tmp <= final) {
		    if (InterruptPending != nil) __interruptL(@line);

		    (*blockVal.ilc_func)(aBlock,
					 @symbol(value:),
					 nil, &blockVal,
					 __mkSmallInteger(tmp));
		    tmp += step;
		}
	    }
	}
	RETURN ( self );
    }
%}.
    "/
    "/ arrive here if stop is not a smallInteger
    "/ pass on to super ...

    ^ super to:stop by:incr do:aBlock

    "
     1 to:10 by:3 do:[:i | i printNewline]
    "
!

to:stop do:aBlock
    "evaluate aBlock for every integer between (and including) the receiver
     and the argument, stop.
     Reimplemented as primitive for speed"

%{
    REGISTER INT tmp;
    INT final;
    static struct inlineCache blockVal = __ILC1(0);

    if (__isSmallInteger(stop)) {
	tmp = __intVal(self);
	final = __intVal(stop);

	if (__isBlockLike(aBlock)
	 && (__BlockInstPtr(aBlock)->b_nargs == __mkSmallInteger(1))) {
	    {
		/*
		 * specially tuned version for the most common case,
		 * where called with home on the stack
		 */
		REGISTER OBJFUNC codeVal;

		if ((codeVal = __BlockInstPtr(aBlock)->b_code) != (OBJFUNC)nil) {

#ifdef NEW_BLOCK_CALL

#                   define BLOCK_ARG  aBlock

#else

#                   define BLOCK_ARG  rHome
		    REGISTER OBJ rHome;
		    rHome = __BlockInstPtr(aBlock)->b_home;
		    if ((rHome == nil) || (__qSpace(rHome) >= STACKSPACE))
#endif
		    {

#ifdef PARANOIA
			if (! ((INT)(__BlockInstPtr(aBlock)->b_flags) & __MASKSMALLINT(F_DYNAMIC)))
#endif
			{
			    /*
			     * static compiled blocks ...
			     */
#ifdef __UNROLL_LOOPS__
			    /*
			     * The following code is designed to run as fast as possible;
			     *  - taken branches only if interrupts are pending
			     *  - only forward branches (which are usually predicted as not taken)
			     *  - unrolled the loop
			     *
			     * you are not supposed to program like this - I know what I do
			     */
# if TAG_INT==1
			    INT t8 = (INT)(__mkSmallInteger(tmp+8));
			    tmp = (INT)(__mkSmallInteger(tmp));
			    final = (INT)(__mkSmallInteger(final));
# else
			    INT t8 = tmp+8;
# endif

			    for (;;) {

				while (t8 <= final) {
# if TAG_INT==1
				    t8 += (INT)(__MASKSMALLINT(8));
# else
				    t8 += 8;
# endif
				    if (InterruptPending != nil) goto interrupted0;
	continue0:
# if TAG_INT==1
				    (*codeVal)(BLOCK_ARG, tmp);
# else
				    (*codeVal)(BLOCK_ARG, __mkSmallInteger(tmp));
# endif
				    if (InterruptPending != nil) goto interrupted1;
	continue1:
# if TAG_INT==1
				    (*codeVal)(BLOCK_ARG, tmp+(INT)(__MASKSMALLINT(1)) );
# else
				    (*codeVal)(BLOCK_ARG, __mkSmallInteger(tmp+1));
# endif
				    if (InterruptPending != nil) goto interrupted2;
	continue2:
# if TAG_INT==1
				    (*codeVal)(BLOCK_ARG, tmp+(INT)(__MASKSMALLINT(2)) );
# else
				    (*codeVal)(BLOCK_ARG, __mkSmallInteger(tmp+2));
# endif
				    if (InterruptPending != nil) goto interrupted3;
	continue3:
# if TAG_INT==1
				    (*codeVal)(BLOCK_ARG, tmp+(INT)(__MASKSMALLINT(3)) );
# else
				    (*codeVal)(BLOCK_ARG, __mkSmallInteger(tmp+3));
# endif
				    if (InterruptPending != nil) goto interrupted4;
	continue4:
# if TAG_INT==1
				    (*codeVal)(BLOCK_ARG, tmp+(INT)(__MASKSMALLINT(4)) );
# else
				    (*codeVal)(BLOCK_ARG, __mkSmallInteger(tmp+4));
# endif
				    if (InterruptPending != nil) goto interrupted5;
	continue5:
# if TAG_INT==1
				    (*codeVal)(BLOCK_ARG, tmp+(INT)(__MASKSMALLINT(5)) );
# else
				    (*codeVal)(BLOCK_ARG, __mkSmallInteger(tmp+5));
# endif
				    if (InterruptPending != nil) goto interrupted6;
	continue6:
# if TAG_INT==1
				    (*codeVal)(BLOCK_ARG, tmp+(INT)(__MASKSMALLINT(6)) );
# else
				    (*codeVal)(BLOCK_ARG, __mkSmallInteger(tmp+6));
# endif
				    if (InterruptPending != nil) goto interrupted7;
	continue7:
# if TAG_INT==1
				    (*codeVal)(BLOCK_ARG, tmp+(INT)(__MASKSMALLINT(7)) );
# else
				    (*codeVal)(BLOCK_ARG, __mkSmallInteger(tmp+7));
# endif

# if TAG_INT==1
				    tmp += (INT)(__MASKSMALLINT(8));
# else
				    tmp += 8;
# endif
				}
				while (tmp <= final) {
				    if (InterruptPending != nil) goto interruptedX;
	continueX:
# if TAG_INT==1
				    (*codeVal)(BLOCK_ARG, tmp);
				    tmp += (INT)(__MASKSMALLINT(1));
# else
				    (*codeVal)(BLOCK_ARG, __mkSmallInteger(tmp));
				    tmp++;
# endif
				}
				RETURN (self);

				if (0) {
				    /*
				     * no discussion about those gotos ...
				     * ... its better for your CPU's pipelines
				     * (if you dont understand why, just dont argue).
				     */
				    interrupted7:
						    __interruptL(@line); goto continue7;
				    interrupted6:
						    __interruptL(@line); goto continue6;
				    interrupted5:
						    __interruptL(@line); goto continue5;
				    interrupted4:
						    __interruptL(@line); goto continue4;
				    interrupted3:
						    __interruptL(@line); goto continue3;
				    interrupted2:
						    __interruptL(@line); goto continue2;
				    interrupted1:
						    __interruptL(@line); goto continue1;
				    interrupted0:
						    __interruptL(@line); goto continue0;
				    interruptedX:
						    __interruptL(@line); goto continueX;
				}
			    }
#else
			    while (tmp <= final) {
				if (InterruptPending != nil) __interruptL(@line);
				(*codeVal)(BLOCK_ARG, __mkSmallInteger(tmp));
				tmp ++;
			    }
			    RETURN (self);
#endif /* __UNROLL_LOOPS__ */
			}

			/*
			 * mhmh - seems to be a block with dynamic code
			 * must refetch, to allow dynamic recompilation or code flush.
			 */
			while (tmp <= final) {
			    if (InterruptPending != nil) __interruptL(@line);
			    if ((codeVal = __BlockInstPtr(aBlock)->b_code) == (OBJFUNC)nil) break;
			    (*codeVal)(BLOCK_ARG, __mkSmallInteger(tmp));
			    tmp ++;
			}

			if (tmp > final) {
			    RETURN (self);
			}
		    }
		}
	    }

#           undef BLOCK_ARG

#ifdef NEW_BLOCK_CALL
#           define BLOCK_ARG  aBlock
#           define IBLOCK_ARG nil
#else
#           define BLOCK_ARG  (__BlockInstPtr(aBlock)->b_home)
#           define IBLOCK_ARG (__BlockInstPtr(aBlock)->b_home)
#endif

	    /*
	     * sorry - must check for the blocks code within the loops;
	     * it could be recompiled or flushed (in the interrupt)
	     */
	    while (tmp <= final) {
		REGISTER OBJFUNC codeVal;

		if ((codeVal = __BlockInstPtr(aBlock)->b_code) != (OBJFUNC)nil) {
		    /*
		     * arg is a compiled block with code -
		     * directly call it without going through Block>>value
		     */

		    /* stay here, while no interrupts are pending ... */
		    do {
			(*codeVal)(BLOCK_ARG, __mkSmallInteger(tmp));
			if (InterruptPending != nil) goto outerLoop;
			tmp++;
		    } while (tmp <= final);
		    RETURN (self);
		} else {
		    if (InterruptPending != nil) __interruptL(@line);

		    if (__BlockInstPtr(aBlock)->b_bytecodes != nil) {
			/*
			 * arg is a compiled block with bytecode -
			 * directly call interpreter without going through Block>>value
			 */
#ifdef PASS_ARG_POINTER
			{
			    OBJ idx;

			    idx = __mkSmallInteger(tmp);
			    __interpret(aBlock, 1, nil, IBLOCK_ARG, nil, nil, &idx);
			}
#else
			__interpret(aBlock, 1, nil, IBLOCK_ARG, nil, nil, __mkSmallInteger(tmp));
#endif

		    } else {
			/*
			 * arg is something else - call it with #value:
			 */
			(*blockVal.ilc_func)(aBlock, @symbol(value:), nil, &blockVal, __mkSmallInteger(tmp));
		    }
		}
	    outerLoop: ;
		tmp++;
	    }

#           undef BLOCK_ARG
#           undef IBLOCK_ARG

	    RETURN (self);
	}
	/*
	 * arg is something else - call it with #value:
	 */
	while (tmp <= final) {
	    if (InterruptPending != nil) __interruptL(@line);

	    (*blockVal.ilc_func)(aBlock,
					 @symbol(value:),
					 nil, &blockVal,
					 __mkSmallInteger(tmp));
	    tmp++;
	}
	RETURN ( self );
    }
%}.

    "/
    "/ arrive here if stop is not a smallInteger
    "/ pass on to super ...
    "/
    ^ super to:stop do:aBlock

    "
     1 to:10 do:[:i | i printNewline]
    "
! !

!SmallInteger methodsFor:'misc math'!

bernoulli
    "returns the nth Bernoulli number.
     The series runs this:
	 1/6, 1/30, 1/42, 1/30, 5/66, 691/2730, etc
     Uses a table of the first 20 bernoulli numbers.
     So bernoulli(42) will fail for now.
     Used with taylor series for tan"

    |table p|

    table := #(
		(1 6)
		(-1 30)
		(1 42)
		(-1 30)
		(5 66)
		(-691 2730)
		(7 6)
		(-3617 510)
		(43867 798)
		(-174611 330)
		(854513 138)
		(-236364091 2730)
		(8553103 6)
		(-23749461029 870)
		(8615841276005 14322)
		(-7709321041217 510)
		(2577687858367 6)
		(-26315271553053477373 1919190)
		(2929993913841559 6)
		(-261082718496449122051 13530)
	      ).

    self even ifTrue:[
	self == 0 ifTrue:[^1].
	p := table at:(self / 2).
	^ Fraction numerator:(p first) denominator:(p second).
    ].
    self == 1 ifTrue:[ ^ (1 / 2) ].
    ^ 0.

    "
     0 bernoulli
     1 bernoulli
     2 bernoulli
     3 bernoulli
     4 bernoulli
     5 bernoulli
     6 bernoulli
     8 bernoulli
     38 bernoulli
     40 bernoulli
     41 bernoulli
     42 bernoulli
    "
!

divMod:aNumber
    "return an array filled with self // aNumber and
     self \\ aNumber.
     The result is only defined for positive receiver and
     argument."

%{  /* NOCONTEXT */
    INT val, div, mod, mySelf;

    if (__isSmallInteger(aNumber) &&
	(val = __intVal(aNumber)) > 0) {
	mySelf = __intVal(self);
	div = mySelf / val;
	mod = mySelf % val;

	RETURN (__ARRAY_WITH2( __mkSmallInteger(div),
			       __mkSmallInteger(mod)));
    }
%}.
    ^ super divMod:aNumber

    "
     10 // 3
     10 \\ 3
     10 divMod:3
    "
!

gcd:anInteger
    "return the greatest common divisor (Euclid's algorithm).
     This has been redefined here for more speed since due to the
     use of gcd in Fraction code, it has become time-critical for
     some code. (thanx to MessageTally)"

%{  /* NOCONTEXT */

    if (__isSmallInteger(anInteger)) {
	INT orgArg, ttt, selfInt, orgSelfInt, temp;

	ttt = orgArg = __intVal(anInteger);
	if (ttt) {
	    selfInt = orgSelfInt = __intVal(self);
	    while (ttt != 0) {
		temp = selfInt % ttt;
		selfInt = ttt;
		ttt = temp;
	    }
	    /*
	     * since its not defined in C, what the sign of
	     * a modulus result is when the arg is negative,
	     * change it explicitely here ...
	     */
	    if (orgArg < 0) {
		/* result should be negative */
		if (orgSelfInt > 0) selfInt = -selfInt;
	    } else {
		/* result should be positive */
		if (orgSelfInt < 0) selfInt = -selfInt;
	    }
	    RETURN ( __mkSmallInteger(selfInt) );
	}
    }
%}
.
    ^ super gcd:anInteger
!

gcd_helper:anInteger
    "same as gcd - see knuth & Integer>>gcd:"

    ^ self gcd:anInteger

    "Created: 1.3.1997 / 16:58:01 / cg"
!

intlog10
    "return the truncation of log10 of the receiver.
     The same as (self log:10) floor.
     Stupid implementation, which is used to find out the number of digits needed
     to print a number/and for conversion to a LargeInteger.
     Implemented that way, to allow for tiny systems (PDAs) without a Float class
     (i.e. without log)."

    self > 0 ifTrue:[
        self < 10000 ifTrue:[
            self < 10 ifTrue:[^ 0].
            self < 100 ifTrue:[^ 1].
            self < 1000 ifTrue:[^ 2].
            ^ 3
        ].
        self < 100000000 ifTrue:[
            self < 100000 ifTrue:[^ 4].
            self < 1000000 ifTrue:[^ 5].
            self < 10000000 ifTrue:[^ 6].
            ^ 7
        ].
        self < 1000000000 ifTrue:[^ 8].

        SmallInteger maxBytes == 4 ifTrue:[
            ^ 9
        ] ifFalse:[    
            self < 10000000000 ifTrue:[^ 9].
            self < 100000000000 ifTrue:[^ 10].
            self < 1000000000000 ifTrue:[^ 11].
            self < 10000000000000 ifTrue:[^ 12].
            self < 100000000000000 ifTrue:[^ 13].
            self < 1000000000000000 ifTrue:[^ 14].
            self < 10000000000000000 ifTrue:[^ 15].
            self < 100000000000000000 ifTrue:[^ 16].
            self < 1000000000000000000 ifTrue:[^ 17].
            ^ 18.
        ].
        "/ not reached
    ].
    ^ self class
        raise:#domainErrorSignal
        receiver:self
        selector:#intlog10
        arguments:#()
        errorString:'logarithm of negative integer'

    "
      99 intlog10 
      100 intlog10  
      101 intlog10
      (101 log:10) floor
      120 intlog10
      -1 intlog10
    "
! !

!SmallInteger methodsFor:'modulo arithmetic'!

plus32:aNumber
    "return the sum of the receiver and the argument, as SmallInteger.
     The argument must be another SmallInteger.
     If the result overflows the 32 bit range, the value modulo 16rFFFFFFFF is returned.
     This is of course not always correct, but allows for C/Java behavior to be emulated."

%{  /* NOCONTEXT */
    INT sum;

    sum =  __unsignedLongIntVal(self) + __unsignedLongIntVal(aNumber);
#if __POINTER_SIZE__ == 8
    sum &= 0xFFFFFFFFL;
#endif
    RETURN ( __MKUINT(sum));
%}.
    self primitiveFailed

    "
     16r7FFFFFFF + 1          2147483648
     16r7FFFFFFF plus32: 1
    "
!

plus:aNumber
    "return the sum of the receiver and the argument, as SmallInteger.
     The argument must be another SmallInteger.
     If the result overflows the smallInteger range, the value modulo the
     smallInteger range is returned (i.e. the low bits of the sum).
     This is of course not always correct, but some code does a modulo anyway
     and can therefore speed things up by not going through LargeIntegers."

%{  /* NOCONTEXT */

    if (__isSmallInteger(aNumber)) {
	INT sum;

	sum =  __intVal(self) + __intVal(aNumber);
	if (!__ISVALIDINTEGER(sum)) {
	    /* keep the sign */
	    sum %= _MAX_INT;
	}
	RETURN ( __mkSmallInteger(sum));
    }
%}.
    self primitiveFailed

    "
	5 plus:-1
	5 plus:1
	1 plus:-5
	self maxVal plus:1
	self maxVal + 1
    "
!

subtract:aNumber
    "return the difference of the receiver and the argument, as SmallInteger.
     The argument must be another SmallInteger.
     If the result overflows the smallInteger range, the value modulo the
     smallInteger range is returned (i.e. the low bits of the sum).
     This is of course not always correct, but some code does a modulo anyway
     and can therefore speed things up by not going through LargeIntegers."

%{  /* NOCONTEXT */

    if (__isSmallInteger(aNumber)) {
	INT diff;

	diff = __intVal(self) - __intVal(aNumber);
	if (!__ISVALIDINTEGER(diff)) {
	    /* keep the sign */
	    diff %= _MAX_INT;
	}
	RETURN ( __mkSmallInteger(diff));
    }
%}.
    self primitiveFailed

    "
	-1 subtract:5
	5 subtract:1
	1 subtract:-5
	self minVal subtract:1
	self minVal - 1
    "
!

times:aNumber
    "return the product of the receiver and the argument, as SmallInteger.
     The argument must be another SmallInteger.
     If the result overflows the smallInteger range, the value modulo the
     smallInteger range is returned (i.e. the low bits of the product).
     This is of course not always correct, but some code does a modulo anyway
     and can therefore speed things up by not going through LargeIntegers."

%{  /* NOCONTEXT */

    INT myValue, otherValue;
    unsigned INT productLow, productHi;
    int negative;

#   define low16Bits(foo)  ((foo) & 0xFFFF)
#   define hi16Bits(foo)   ((foo) >> 16)
#   define low32Bits(foo)  ((foo) & 0xFFFFFFFFL)
#   define hi32Bits(foo)   ((foo) >> 32)

    /*
     * can we use long long arithmetic ?
     *
     * long-long arithmetic seems to be buggy with some systems
     * (took me a while to find this out :-(
     * (try 10000 * 10000)
     */
#if defined(__sparc__) && defined(__GNUC__) && (__GNUC__ >= 2)
# define USE_LONGLONG_FOR_MUL
#endif

#if defined(__i386__) && defined(__GNUC__) && (__GNUC__ >= 2)
# define USE_LONGLONG_FOR_MUL
#endif

    if (__isSmallInteger(aNumber)) {
	myValue = __intVal(self);
	otherValue = __intVal(aNumber);

#if defined(USE_LONGLONG_FOR_MUL)
	{
# if defined(__alpha__) && !defined(__alpha64__)
#  define LONGLONG      INT64
# else
#  define LONGLONG      long long
# endif
	    LONGLONG product;

	    product = (LONGLONG)myValue * (LONGLONG)otherValue;
	    if (product < 0) {
		RETURN ( __mkSmallInteger(-(INT)(-product & _MAX_INT)));
	    }
	    RETURN ( __mkSmallInteger((INT)(product & _MAX_INT)));
	}
#else /* no long-long */
	negative = 1;
	if (myValue < 0) {
	    negative = -1;
	    myValue = -myValue;
	}
	if (otherValue < 0) {
	    negative = -negative;
	    otherValue = -otherValue;
	}

# if defined(__GNUC__) && defined(__mc68k__)
	asm ("mulu%.l %3,%1:%0"
		: "=d"  ((unsigned long)(productLow)),
		  "=d"  ((unsigned long)(productHi))
		: "%0"  ((unsigned long)(myValue)),
		  "dmi" ((unsigned long)(otherValue)));
# else
#  if defined (__GNUC__) && defined(__i386__)
	asm ("mull %3"
		: "=a"  ((unsigned long)(productLow)),
		  "=d"  ((unsigned long)(productHi))
		: "%0"  ((unsigned long)(myValue)),
		  "rm"  ((unsigned long)(otherValue)));
#  else
#   if defined(WIN32) && defined(__BORLANDC__)
	asm {
	    mov   eax, myValue
	    mov   edx, otherValue
	    mul   edx
	    mov   productLow, eax
	    mov   productHi, edx
	}
#   else /* generic */
	{
	    unsigned INT pHH, pHL, pLH, pLL;
	    unsigned INT low1, low2, hi1, hi2;
	    unsigned INT t;

	    /* unsigned multiply myValue * otherValue -> productHi, productLow
	     *
	     * this is too slow:
	     * since most machines can do 32*32 to 64 bit multiply,
	     * (or at least 32*32 with Overflow check)
	     * - need more assembler (inline) functions here
	     */
#    if __POINTER_SIZE__ == 8
	    low1 = low32Bits((unsigned INT)myValue);
	    hi1 = hi32Bits((unsigned INT)myValue);
	    low2 = low32Bits((unsigned INT)otherValue);
	    hi2 = hi32Bits((unsigned INT)otherValue);
#     define LLMASK 0xC000000000000000L
#    else
	    low1 = low16Bits((unsigned INT)myValue);
	    hi1 = hi16Bits((unsigned INT)myValue);
	    low2 = low16Bits((unsigned INT)otherValue);
	    hi2 = hi16Bits((unsigned INT)otherValue);
#     define LLMASK 0xC0000000
#    endif

	    pLH = low1 * hi2;
	    pHL = hi1 * low2;
	    pLL = low1 * low2;
	    pHH = hi1 * hi2;

	    /*
	     * the common case ...
	     */
	    if ((pHL == 0)
	     && (pLH == 0)
	     && (pHH == 0)
	     && ((pLL & LLMASK) == 0)) {
		if (negative < 0) {
		    RETURN ( __mkSmallInteger(- ((INT)pLL)) );
		}
		RETURN ( __mkSmallInteger((INT)pLL) );
	    }

	    /*
	     *   pHH |--------|--------|
	     *   pLH          |--------|--------|
	     *   pHL          |--------|--------|
	     *   pLL                   |--------|--------|
	     */

#    if __POINTER_SIZE__ == 8
	    t = low32Bits(pLH) + low32Bits(pHL) + hi32Bits(pLL);
	    productLow = (t << 32) + low32Bits(pLL);
	    productHi = pHH + hi32Bits(t) + hi32Bits(pHL) + hi32Bits(pLH);
#    else
	    t = low16Bits(pLH) + low16Bits(pHL) + hi16Bits(pLL);
	    productLow = (t << 16) + low16Bits(pLL);
	    productHi = pHH + hi16Bits(t) + hi16Bits(pHL) + hi16Bits(pLH);
#    endif
	}
#   endif /* ! WIN32 */
#  endif /* ! (__GNUC__ && __i386__) */
# endif /* ! (__GNUC__ && __mc68k__) */

	if (negative < 0) {
	    RETURN ( __mkSmallInteger(-(INT)(productLow & _MAX_INT)));
	}
	RETURN ( __mkSmallInteger((INT)(productLow & _MAX_INT)));
#endif /* ! USE_LONGLONG */
    }
%}.

    self primitiveFailed

    "
	5 times:-1
	5 times:1
	self maxVal-1 times:2
	self maxVal-1 times:-2
	self maxVal-1 * 2  bitAnd:16r3fffffff
    "
! !

!SmallInteger methodsFor:'printing & storing'!

printOn:aStream
    "append my printstring (base 10) to aStream."

    aStream nextPutAll:(self printString)
!

printOn:aStream base:base showRadix:showRadix
    "append a string representation of the receiver in the specified numberBase to aStream
     (if showRadix is true, with initial XXr)
     The base argument should be between 2 and 36."

    showRadix ifTrue:[
	base printOn:aStream.
	aStream nextPut:$r.
    ].

    (base isInteger and:[ base between:2 and:36 ]) ifTrue:[
	aStream nextPutAll:(self printStringRadix:base)
    ] ifFalse:[
	super printOn:aStream base:base showRadix:false.
    ].

    "Created: / 07-09-2001 / 13:54:40 / cg"
    "Modified: / 02-08-2010 / 12:25:20 / cg"
!

printString
    "return my printstring (base 10)"

    "since this was heavily used in some applications,
     here is an exception to the rule of basing printString
     upon the printOn: method."

%{  /* NOCONTEXT */
    char buffer[30];    /* enough for 64 bit machines */
    char *cp;
    OBJ newString = nil;
    INT myValue;
    int negative = 0;
    int len;

    if (self == __MKSMALLINT(0)) {
        RETURN (@global(ZeroString));
//        RETURN (__MKSTRING_L("0", 1));
    }
    myValue = __intVal(self);
#ifdef SLOW_CODE
    /*
     * this takes twice as long as the code below ...
     * (printf is soooo slow)
     */

    /*
     * PROTECT_REGISTERS: 
     * actually only needed on sparc: since thisContext is
     * in a global register, which gets destroyed by printf,
     * manually save it here - very stupid ...
     */
    __BEGIN_PROTECT_REGISTERS__
    len = snprintf(buffer, sizeof(buffer), "%"_ld_"", myValue);
    __END_PROTECT_REGISTERS__

    if (len >= 0 && len <= sizeof(buffer)) {
        newString = __MKSTRING_L(buffer, len);
    }
#else
    if (myValue < 0) {
        negative = 1;
        myValue = -myValue;
    }
    cp = buffer + sizeof(buffer) - 1;
    *cp-- = '\0';
    while (myValue != 0) {
        *cp = '0' + (myValue % 10);
        myValue = myValue / 10;
        cp--;
    }
    if (negative) {
        *cp-- = '-';
    }
    newString = __MKSTRING_L(cp+1, (buffer + sizeof(buffer) - 2 - cp));
#endif
    if (newString != nil) {
        RETURN (newString);
    }
%}.
    "/ only arrive here,
    "/  when having memory problems (i.e. no space for string) ...
    ^ super printString

    "
     1234 printString
     0    printString
     -100 printString

    Time millisecondsToRun:[ 1000000 timesRepeat:[ 123456789012 printString ]] 180 180 180 170 180
    Time millisecondsToRun:[ 1000000 timesRepeat:[ 12345678 printString ]]     140 150 140 150 140
    Time millisecondsToRun:[ 1000000 timesRepeat:[ 1234 printString ]]         130 140 130 130 130
    Time millisecondsToRun:[ 1000000 timesRepeat:[ 12 printString ]]           130 120 120 120 110
    Time millisecondsToRun:[ 1000000 timesRepeat:[ 5 printString ]]            110 110 100 110 90
    Time millisecondsToRun:[ 1000000 timesRepeat:[ 0 printString ]]             60 
    "
!

printStringRadix:base
    "return my printstring (optimized for bases 16, 10 and 8)"

    |s|

%{
    char buffer[64+3];  /* for 64bit machines, base 2, plus sign, plus 0-byte */
    char *cp;
    OBJ newString;
    INT myValue;
    int negative = 0;
    INT __base;

    if (__isSmallInteger(base)) {
        if (self == __MKSMALLINT(0)) {
            RETURN (__MKSTRING_L("0", 1));
        }
        myValue = __intVal(self);
        __base = __intVal(base);

#ifdef SLOW_CODE
        /* disabled, because printf is slower than the code below */

        switch (__base) {
            case 10:
                format = "%"_ld_"";
                break;
            case 16:
                format = "%"_lx_"";
                break;
            case 8:
                format = "%"_lo_"";
                break;
        }

        if (format) {
            /*
             * actually only needed on sparc: since thisContext is
             * in a global register, which gets destroyed by printf,
             * manually save it here - very stupid ...
             */
            __BEGIN_PROTECT_REGISTERS__

            len = snprintf(buffer, sizeof(buffer), format, (long)myValue);

            __END_PROTECT_REGISTERS__

            if (len > 0 && len <= sizeof(buffer)) {
                newString = __MKSTRING_L(buffer, len);
                if (newString != nil) {
                    RETURN (newString);
                }
            }
        }
#else
        if ((__base <= 36) && (__base > 1)) {
            if (myValue < 0) {
                negative = 1;
                myValue = -myValue;
            }
            cp = buffer + sizeof(buffer) - 1;
            *cp-- = '\0';
            while (myValue != 0) {
                int digit;

                digit = myValue % __base;
                if (digit <= 9) {
                    *cp = '0' + digit;
                } else {
                    *cp = 'A' + digit - 10;
                }
                myValue = myValue / __base;
                cp--;
            }
            if (negative) {
                *cp-- = '-';
            }
            newString = __MKSTRING_L(cp+1, (buffer + sizeof(buffer) - 2 - cp));
            if (newString != nil) {
                RETURN (newString);
            }
        }
#endif
    }
%}.
    "/ arrive here, for bad base,
    "/ or when having memory problems (i.e. no space for string) ...

    "/
    "/ fall back for seldom used bases
    "/ Notice: cannt use super>>printStringRadix: here,
    "/ since that would lead to endless recursion ...
    "/ (a consequence of reversing printOn / printString functionality)

    s := WriteStream on:(String new:10).
    super printOn:s base:base.
    ^ s contents.

    "
      127 printStringRadix:16
      123 printStringRadix:12
      123 printStringRadix:10
      123 printStringRadix:8
      123 printStringRadix:3
      123 printStringRadix:2
      123 printStringRadix:1

      -127 printStringRadix:16
      -123 printStringRadix:12
      -123 printStringRadix:10
      -123 printStringRadix:8
      -123 printStringRadix:3
      -123 printStringRadix:2
    "
!

printfPrintString:formatString
    "non-standard, but sometimes useful.
     return a printed representation of the receiver
     as specified by formatString, which is defined by the C-function 'printf'.
     No checking for string overrun - the resulting string
     must be shorter than 256 chars or else ...
     This method is NONSTANDARD and may be removed without notice;
     it is provided to allow special conversions in very special situations.
     Notice that a conversion may not be portable; for example,
     to correctly convert an int on a 64-bit alpha, a %ld is required,
     on 64bit mingw or visualc, %lld is required,
     while other systems may be happy with a %d.
     You cannot use lld unconditionally, because some (old) c printfs do not support it!!)
     Use at your own risk (if at all).
     WARNNG: this goes directly to the C-printf function and may therefore be inherently unsafe.
     Please use the printf: method, which is safe as it is completely implemented in Smalltalk."

%{  /* STACK: 400 */
    char buffer[256];
    OBJ s;
    int len;

    if (__isStringLike(formatString)) {
        /*
         * actually only needed on sparc: since thisContext is
         * in a global register, which gets destroyed by printf,
         * manually save it here - very stupid ...
         */
        __BEGIN_PROTECT_REGISTERS__

        len = snprintf(buffer, sizeof(buffer), __stringVal(formatString), __intVal(self));

        __END_PROTECT_REGISTERS__

        if (len < 0) goto fail;

        s = __MKSTRING_L(buffer, len);
        if (s != nil) {
            RETURN (s);
        }
    }
fail: ;
%}.
    self primitiveFailed

    "
        123 printfPrintString:'%%d -> %d'
        123 printfPrintString:'%%6d -> %6d'   
        123 printfPrintString:'%%x -> %x'     
        123 printfPrintString:'%%4x -> %4x'   
        123 printfPrintString:'%%04x -> %04x' 
    "
! !

!SmallInteger methodsFor:'private'!

sign:aNumber
    "private: for protocol completeness with LargeIntegers"

    |absVal|

    absVal := self abs.
    aNumber < 0 ifTrue:[
	^ absVal negated
    ].
    aNumber == 0 ifTrue:[^ 0].
    ^ absVal

    "
     -4 sign:-1
     -4 sign:0
     -4 sign:1
     -4 sign:-1
     -4 sign:0
     -4 sign:1
    "
! !

!SmallInteger methodsFor:'testing'!

between:min and:max
    "return true if the receiver is less than or equal to the argument max
     and greater than or equal to the argument min.
     - reimplemented here for speed"

%{  /* NOCONTEXT */

    if (__bothSmallInteger(min, max)) {
#if TAG_INT == 1
        // tag bit does not change the magnitude order
        if ((INT)self < (INT)(min)) {
             RETURN ( false );
        }
        if ((INT)self > (INT)(max)) {
             RETURN ( false );
        }
        RETURN ( true );
#else
        REGISTER INT selfVal;

        selfVal = __intVal(self);
        if (selfVal < __intVal(min)) {
             RETURN ( false );
        }
        if (selfVal > __intVal(max)) {
             RETURN ( false );
        }
        RETURN ( true );
#endif
    }
%}.
    (self < min) ifTrue:[^ false].
    (self > max) ifTrue:[^ false].
    ^ true
!

even
    "return true, if the receiver is even"

%{  /* NOCONTEXT */

    RETURN ( ((INT)self & (INT)__MASKSMALLINT(1)) ? false : true );
%}.
    ^ super even
!

isPowerOfTwo
    "return true, if the receiver is a power of 2"

"/ mhmh: how about the following
"/    self == 0 ifTrue:[^ false].

    ^ (self bitAnd:(self - 1)) == 0

    "
     0 isPowerOfTwo
     1 isPowerOfTwo
     2 isPowerOfTwo
     3 isPowerOfTwo
     4 isPowerOfTwo
     16r8000000000000000 isPowerOfTwo
     16r8000000000000001 isPowerOfTwo

     10000 factorial isPowerOfTwo
     |n| n := 10000 factorial. Time millisecondsToRun:[1000 timesRepeat:[ n isPowerOfTwo]]
    "

    "Modified: / 20-06-2011 / 12:41:18 / cg"
!

negative
    "return true, if the receiver is less than zero
     reimplemented here for speed"

%{  /* NOCONTEXT */

#if TAG_INT == 1
    /* tag bit does not change sign */
    RETURN ( ((INT)(self) < 0) ? true : false );
#else
    RETURN ( (__intVal(self) < 0) ? true : false );
#endif
%}.
    ^ self < 0
!

nextPowerOf2
    "return the power of 2 at or above the receiver.
     Useful for padding."

%{  /* NOCONTEXT */
    INT x;

    x = __intVal(self) - 1;
    x |= (x >> 1);
    x |= (x >> 2);
    x |= (x >> 4);
    x |= (x >> 8);
    x |= (x >> 16);
#if __POINTER_SIZE__ == 8
    x |= (x >> 32);
#endif
    RETURN (__MKINT(x + 1));
%}
    "
     1 nextPowerOf2
     2 nextPowerOf2
     3 nextPowerOf2
     4 nextPowerOf2
     5 nextPowerOf2
     6 nextPowerOf2
     7 nextPowerOf2
     8 nextPowerOf2

     22 nextPowerOf2
     10 factorial nextPowerOf2
     20 factorial nextPowerOf2
    "
!

odd
    "return true, if the receiver is odd"

%{  /* NOCONTEXT */

    RETURN ( ((INT)self & (INT)__MASKSMALLINT(1)) ? true : false );
%}.
    ^ super odd

!

parityOdd
    "return true, if an odd number of bits are set in the receiver, false otherwise.
     (i.e. true for odd parity)
     Undefined for negative values (smalltalk does not require the machine to use 2's complement)"

%{  /* NOCONTEXT */

    // tricky, but very fast (google for it, to understand)
#if __POINTER_SIZE__ == 4
    unsigned int v = __intVal(self);

    v ^= v >> 16;
    v ^= v >> 8;
    v ^= v >> 4;
    v &= 0xf;
    RETURN ( ( (0x6996 >> v) & 1 ) ? true : false );
#endif
%}.
    ^ super parityOdd

    "
	self assert:
	 (((0 to:255) collect:[:i | i parityOdd ifTrue:1 ifFalse:0])
	    asByteArray collect:[:c | c + $0 asciiValue]) asString
	 =
	    '0110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110011010011001011010010110011010010110100110010110100101100110100110010110011010010110100110010110'

	self assert:(16r0FFFFFFF parityOdd = 16r0FFFFFFF bitCount odd).
	self assert:(16r1FFFFFFF parityOdd = 16r1FFFFFFF bitCount odd).
	self assert:(16r3FFFFFFF parityOdd = 16r3FFFFFFF bitCount odd).
	self assert:(16r7FFFFFFF parityOdd = 16r7FFFFFFF bitCount odd).
	self assert:(16rFFFFFFFF parityOdd = 16rFFFFFFFF bitCount odd).
    "

    "Modified (comment): / 09-01-2012 / 19:55:37 / cg"
!

positive
    "return true, if the receiver is not negative
     reimplemented here for speed"

%{  /* NOCONTEXT */

#if TAG_INT == 1
    /* tag bit does not change sign */
    RETURN ( ((INT)(self) >= 0) ? true : false );
#else
    RETURN ( (__intVal(self) >= 0) ? true : false );
#endif
%}.
    ^ super positive

!

sign
    "return the sign of the receiver (-1, 0 or 1).
     reimplemented here for speed"

%{  /* NOCONTEXT */

    INT val = __intVal(self);

    if (val < 0) {
	RETURN ( __mkSmallInteger(-1) );
    }
    if (val > 0) {
	RETURN ( __mkSmallInteger(1) );
    }
    RETURN ( __mkSmallInteger(0) );
%}.
    ^ super sign
!

strictlyPositive
    "return true, if the receiver is greater than zero
     reimplemented here for speed"

%{  /* NOCONTEXT */

#if TAG_INT == 1
    /* tag bit does not change sign */
    RETURN ( ((INT)(self) > 0) ? true : false );
#else
    RETURN ( (__intVal(self) > 0) ? true : false );
#endif
%}.
    ^ super strictlyPositive
! !

!SmallInteger class methodsFor:'documentation'!

version
    ^ '$Header: /cvs/stx/stx/libbasic/SmallInteger.st,v 1.213 2014-01-25 21:34:10 cg Exp $'
!

version_CVS
    ^ '$Header: /cvs/stx/stx/libbasic/SmallInteger.st,v 1.213 2014-01-25 21:34:10 cg Exp $'
! !


SmallInteger initialize!