public inbox for mauve-patches@sourceware.org
 help / color / mirror / Atom feed
* UUID tests.
@ 2006-07-16  4:30 Sven de Marothy
  2006-07-16  4:31 ` UUID tests. oops Sven de Marothy
  0 siblings, 1 reply; 2+ messages in thread
From: Sven de Marothy @ 2006-07-16  4:30 UTC (permalink / raw)
  To: mauve-patches

[-- Attachment #1: Type: text/plain, Size: 97 bytes --]

I commited a java.util.UUID impl.

Here's a full set of tests (AFAIK), we pass them all.

/Sven


[-- Attachment #2: UUID.java --]
[-- Type: text/x-java, Size: 11198 bytes --]

/* UUID.java -- Class that represents a UUID object.
   Copyright (C) 2006  Free Software Foundation, Inc.

This file is part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */


package java.util;

import java.io.Serializable;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * This class represents a 128-bit UUID value.
 * 
 * There are several types of UUID, and while this class can be used to store
 * them, only the Leach-Salz (variant 2) UUID specified in RFC-4122 will 
 * give meaningful results from the method calls.
 * See: http://tools.ietf.org/html/4122 for the details
 *
 * The format of a Leach-Salz (variant 2) time-based (version 1) UUID 
 * is as follows:
 * time_low - upper 32 bits of the most significant 64 bits,
 *            this is the least-significant part of the timestamp.
 *
 * time_mid - bits 16-31 of the most significant 64 bits,
 *            this is the middle portion of the timestamp. 
 *
 * version  - bits 8-15 of the most significant 64 bits. 
 *
 * time_hi  - bits 0-7 of the most significant 64 bits,
 *            the most significant portion of the timestamp.
 *
 * clock_and_reserved  - bits 48-63 of the least significant 64 bits.
 *                       a variable number of bits hold the variant 
 *                       (see the spec)
 * 
 * node identifier     - bits 0-47 of the least signficant 64 bits.
 *
 * These fields are valid only for version 1, in the remaining versions,
 * only the version and variant fields are set, all others are used for data.
 *
 * @since 1.5
 * @author Sven de Marothy
 */
public final class UUID extends Object implements Serializable, Comparable
{
  private static final long serialVersionUID = -4856846361193249489L;

  /**
   * Serialized field - most significant 64 bits.
   */
  private long mostSigBits;

  /**
   * Serialized field - least significant 64 bits.
   */
  private long leastSigBits;

  /**
   * Random-number generator.
   */
  private static transient Random r = new Random();

  /**
   * Constructs a new UUID.
   *
   * @since 1.5
   */
  public UUID(long mostSigBits, long leastSigBits)
  {
    this.mostSigBits = mostSigBits;
    this.leastSigBits = leastSigBits;
  }
 
  /**
   * Returns the clock-sequence value of this UUID.
   * This field only exists in a time-based (version 1) UUID.
   *
   * @throws UnsupportedOperationException if the UUID type is not 1.
   * @returns an int containing the clock-sequence value.
   */
  public int clockSequence()
  {
    if( version() != 1 )
      throw new UnsupportedOperationException("Not a type 1 UUID");
    return (int)((leastSigBits & 0x3FFF000000000000L) >> 48);
  }

  /**
   * Compare this UUID to another.
   * The comparison is performed as between two 128-bit integers.
   *
   * @return -1 if this < val, 0 if they are equal, 1 if this > val.
   */
  public int compareTo(Object val)
  {
    UUID o = (UUID)val; // genericizeme!
    if( mostSigBits < o.mostSigBits )
      return -1;
    if( mostSigBits > o.mostSigBits )
      return 1;
    if( leastSigBits < o.leastSigBits )
      return -1;
    if( leastSigBits > o.mostSigBits )
      return 1;
    return 0;
  }

  /**
   * Compare a (UUID) object to this one
   */
  public boolean equals(Object obj)
  {
    if( !(obj instanceof UUID ) )
      return false;
    return ( ((UUID)obj).mostSigBits == mostSigBits && 
	     ((UUID)obj).leastSigBits == leastSigBits );
  }

  /**
   * Creates a UUID object from a Sting representation.
   *
   * For the format of the string,
   * @see #toString()
   *
   * @return a new UUID object.
   */
  public static UUID fromString(String name)
  {
    StringTokenizer st = new StringTokenizer( name.trim(), "-" );
    if( st.countTokens() < 5 )
      throw new IllegalArgumentException( "Incorrect UUID string"+
					  " representation:"+name );

    long msb = (Long.parseLong(st.nextToken(), 16) << 32); // time low
    msb |= (Long.parseLong(st.nextToken(), 16) << 16); // time mid
    msb |= Long.parseLong(st.nextToken(), 16); // time high

    long lsb = (Long.parseLong(st.nextToken(), 16) << 48); // clock
    lsb |= Long.parseLong(st.nextToken(), 16); // node

    return new UUID(msb, lsb);
  }

  /**
   * Returns a String representation of the UUID.
   *
   * The format of the standard string representation (given in RFC4122) is:
   *
   * time-low "-" time-mid "-"
   * time-high-and-version "-"
   * clock-seq-and-reserved
   * clock-seq-low "-" node
   *
   * Where each field is represented as a hex string.
   *
   * @return the String representation.
   */
  public String toString()
  {
    return // time-low first
      padHex( (( mostSigBits & 0xFFFFFFFF00000000L) >> 32) & 0xFFFFFFFFL, 8)
      + "-" + // then time-mid
      padHex( (( mostSigBits & 0xFFFF0000L ) >> 16), 4 ) 
      + "-" + // time-high
      padHex( ( mostSigBits & 0x0000000000000000FFFFL ), 4 ) 
      + "-" + // clock (note - no reason to separate high and low here)
      padHex( (((leastSigBits & 0xFFFF000000000000L) >> 48) & 0xFFFF), 4 ) 
      + "-" + // finally the node value.
      padHex(leastSigBits & 0xFFFFFFFFFFFFL, 12); 
  }

  /**
   * Returns the least significant 64 bits of the UUID as a <code>long</code>.
   */ 
  public long getLeastSignificantBits()
  {
    return leastSigBits;
  }

  /**
   * Returns the most significant 64 bits of the UUID as a <code>long</code>.
   */ 
  public long getMostSignificantBits()
  {
    return mostSigBits;
  }

  /**
   * Returns a hash of this UUID.
   */
  public int hashCode()
  {
    int l1 = (int)(leastSigBits & 0xFFFFFFFFL);
    int l2 = (int)((leastSigBits & 0xFFFFFFFF00000000L) >> 32);
    int m1 = (int)(mostSigBits & 0xFFFFFFFFL);
    int m2 = (int)((mostSigBits & 0xFFFFFFFF00000000L) >> 32);

    return (l1 ^ l2) ^ (m1 ^ m2);
  }

  /**
   * Creates a UUID version 3 object (name based with MD5 hashing)
   * from a series of bytes representing a name.
   */
  public static UUID nameUUIDFromBytes(byte[] name)
  {    
    long msb, lsb;
    byte[] hash;

    try
      {
	MessageDigest md5 = MessageDigest.getInstance("MD5");
	hash = md5.digest( name );
      } 
    catch (NoSuchAlgorithmException e) 
      {
	throw new UnsupportedOperationException("No MD5 algorithm available.");
      }
	
    msb = ((hash[0] & 0xFFL) << 56) | ((hash[1] & 0xFFL) << 48) |
      ((hash[2] & 0xFFL) << 40) | ((hash[3] & 0xFFL) << 32) |
      ((hash[4] & 0xFFL) << 24) | ((hash[5] & 0xFFL) << 16) |
      ((hash[6] & 0xFFL) << 8) | (hash[7] & 0xFFL);

    lsb = ((hash[8] & 0xFFL) << 56) | ((hash[9] & 0xFFL) << 48) |
      ((hash[10] & 0xFFL) << 40) | ((hash[11] & 0xFFL) << 32) |
      ((hash[12] & 0xFFL) << 24) | ((hash[13] & 0xFFL) << 16) |
      ((hash[14] & 0xFFL) << 8) | (hash[15] & 0xFFL);

    lsb &= 0x3FFFFFFFFFFFFFFFL; 
    lsb |= 0x8000000000000000L; // set top two bits to variant 2

    msb &= 0xFFFFFFFFFFFF0FFFL; 
    msb |= 0x3000; // Version 3; 

    return new UUID(msb, lsb);
  }

  /**
   * Returns the 48-bit node value in a long. 
   * This field only exists in a time-based (version 1) UUID.
   *
   * @throws UnsupportedOperationException if the UUID type is not 1.
   * @returns a long with the node value in the lower 48 bits.
   */
  public long node() 
  {
    if( version() != 1 )
      throw new UnsupportedOperationException("Not a type 1 UUID");
    return (leastSigBits & 0xFFFFFFFFFFFFL);
  }

  /**
   * Returns the 60-bit timestamp value of the UUID in a long. 
   * This field only exists in a time-based (version 1) UUID.
   *
   * @throws UnsupportedOperationException if the UUID type is not 1.
   * @returns a long with the timestamp value.
   */
  public long timestamp()
  {
    if( version() != 1 )
      throw new UnsupportedOperationException("Not a type 1 UUID");
    long time = (( mostSigBits & 0xFFFFFFFF00000000L) >> 32);
    time |= (( mostSigBits & 0xFFFF0000L ) << 16);
    long time_hi = ( mostSigBits & 0xFFFL );
    time |= (time_hi << 48);
    return time;
  }

  /**
   * Generate a Leach-Salz (Variant 2) randomly generated (version 4)
   * UUID.
   *
   */
  public static UUID randomUUID()
  {  
    long lsb = r.nextLong(); 
    long msb = r.nextLong();

    lsb &= 0x3FFFFFFFFFFFFFFFL; 
    lsb |= 0x8000000000000000L; // set top two bits to variant 2

    msb &= 0xFFFFFFFFFFFF0FFFL; 
    msb |= 0x4000; // Version 4; 

    return new UUID( msb, lsb );
  }

  /**
   * Returns a hex String from l, padded to n spaces.
   */
  private String padHex( long l, int n )
  {
    String s = Long.toHexString( l );
    while( s.length() < n )
      s = "0" + s;
    return s;
  }

  /**
   * Returns the variant of the UUID
   *
   * This may be:
   * 0 = Reserved for NCS backwards-compatibility
   * 2 = Leach-Salz (supports the other methods in this class)
   * 6 = Reserved for Microsoft backwards-compatibility
   * 7 = (reserved for future use)
   */
  public int variant()
  {
    // Get the top 3 bits (not all may be part of the variant)
    int v = (int)((leastSigBits & 0xE000000000000000L) >> 61);
    if( (v & 0x04) == 0 ) // msb of the variant is 0
      return 0;
    if( (v & 0x02) == 0 ) // variant is 0 1 (Leach-Salz)
      return 2;
    return v; // 6 or 7 
  }

  /**
   * Returns the version # of the UUID.
   *
   * Valid version numbers for a variant 2 UUID are:
   * 1 = Time based UUID
   * 2 = DCE security UUID
   * 3 = Name-based UUID using MD5 hashing
   * 4 = Randomly generated UUID
   * 5 = Name-based UUID using SHA-1 hashing
   *
   * @return the version number
   */
  public int version()
  {
    return (int)((mostSigBits & 0xF000L) >> 12);
  }
}

^ permalink raw reply	[flat|nested] 2+ messages in thread

* Re: UUID tests. oops
  2006-07-16  4:30 UUID tests Sven de Marothy
@ 2006-07-16  4:31 ` Sven de Marothy
  0 siblings, 0 replies; 2+ messages in thread
From: Sven de Marothy @ 2006-07-16  4:31 UTC (permalink / raw)
  To: mauve-patches

[-- Attachment #1: Type: text/plain, Size: 317 bytes --]

Whoops, my brain wasn't with my, I attached the impl and not the tests.

Here are the tests. They go in the java.util.UUID package as expected.

/Sven

On Sun, 2006-07-16 at 06:29 +0200, Sven de Marothy wrote:
> I commited a java.util.UUID impl.
> 
> Here's a full set of tests (AFAIK), we pass them all.
> 
> /Sven


[-- Attachment #2: TestAll.java --]
[-- Type: text/x-java, Size: 8168 bytes --]

/* TestAll.java -- Tests for java.util.UUID
   Copyright (C) 2006 Sven de Marothy
This file is part of Mauve.

Mauve is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

Mauve is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with Mauve; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

*/

// Tags: JDK1.5

package gnu.testlet.java.util.UUID;

import gnu.testlet.TestHarness;
import gnu.testlet.Testlet;
import java.util.UUID;

public class TestAll implements Testlet
{
  public void test(TestHarness harness)
  {    
    harness.checkPoint("equals()");
    testEquals( harness );
    harness.checkPoint("randomUUID()");
    testRandom( harness );
    harness.checkPoint("time fields");
    testTime( harness );
    harness.checkPoint("toString()");
    testToString( harness );
    harness.checkPoint("hashCode()");
    testHash( harness );
    harness.checkPoint("compareTo()");
    testCompare( harness );
    harness.checkPoint("nameUUIDFromBytes()");
    testNameFromBytes( harness );
    harness.checkPoint("fromString()");
    testFromString( harness );
  }

  /**
   * Test data, some valid timestamp UUIDs
   */
  private static final UUID[] ids = new UUID[]
  {
    new UUID(819576242563977691L, -6026651929721136538L),
    new UUID(2832154967796617691L, -6026651929721136538L),
    new UUID(3408883180598464987L, -6026651929721136538L),
    new UUID(3802173340188152283L, -6026651929721136538L)
  };

  /** Some random UUIDs */
  private static final UUID[] randomIds = new UUID[]
  {
    new UUID( -3712700652812154966L, -6598749860495561479L ),
    new UUID( 664552433621420518L, -6414775468900364460L ),
    new UUID( -5464341501079829899L, -5598482408525562595L ),
    new UUID( -6237697930964942150L, -6792975957340980865L ),
    new UUID( 1115444745961556609L, -8924788308993396799L ),
    new UUID( 8935737015972545600L, -7709166330108105025L ),
    new UUID( -1731090450474971506L, -8180066663887629633L ),
    new UUID( -4352314495419070300L, -6102009369002353257L ),
    new UUID( -2372952748710147740L, -7309989210815328856L ),
    new UUID( -7640168945999331050L, -9131205566142177277L )
  };

  /** correct string representations of the respective ids */
  private static String[] strs = new String[]
  {
    "0b5fb840-1460-11db-ac5d-0800200c9a66",
    "274dd5f0-1460-11db-ac5d-0800200c9a66",
    "2f4ec931-1460-11db-ac5d-0800200c9a66",
    "34c40882-1460-11db-ac5d-0800200c9a66" 
  };

  private static String[] randomStrs = new String[]
  {
    "cc79d66d-4fc5-47aa-a46c-87f6ab80ecf9",
    "0938f6ea-dca0-49e6-a6fa-23b2ae4dcf54",
    "b42ac25b-28b6-4275-b24e-31e9568f7d1d",
    "a96f3ec7-d0a5-42ba-a1ba-805b86ebf97f",
    "0f7adb16-299d-4a81-8424-c8518ae3afc1",
    "7c021d78-f35a-4440-9503-8a1153812ebf",
    "e7f9ee68-315e-4e8e-8e7a-90b583f692bf",
    "c3997906-a5c3-48a4-ab51-4ecf08825d97",
    "df11940c-2858-4964-9a8d-b38af16a0da8",
    "95f8aad2-adbd-4116-8147-70eab306a003"
  };

  private void testNameFromBytes(TestHarness harness)
  {
    UUID id1, id2;
    id1 = new UUID(8833946387751055799L, -7161481369492758254L);
    id2 = UUID.nameUUIDFromBytes( new byte[]{(byte)80, (byte)43 });
    harness.check(id1.equals(id2));

    id1 = new UUID(5637592221686249917L, -5921171958455577142L);
    id2 = UUID.nameUUIDFromBytes( new byte[]{ (byte)114, (byte)45 });
    harness.check(id1.equals(id2));

    id1 = new UUID(-4355869889751467654L, -7258896509850702779L);
    id2 = UUID.nameUUIDFromBytes( new byte[]{(byte)36, (byte)32, (byte)172, 
					     (byte)170, (byte)254, (byte)224});
    harness.check(id1.equals(id2));

    id1 = new UUID(-5236193865575288109L, -8631150049002629651L);
    id2 = UUID.nameUUIDFromBytes( new byte[]{(byte)79, (byte)195, (byte)193, 
					     (byte)12 });
    harness.check(id1.equals(id2));

    id1 = new UUID(6892210306406430384L, -8874384750029244307L);
    id2 = UUID.nameUUIDFromBytes( new byte[]{(byte)159, (byte)194, (byte)145,
					     (byte)7, (byte)79, (byte)81,
					     (byte)95 });
    harness.check(id1.equals(id2));

    id1 = new UUID(-1760792916171804329L, -7690807811470976644L);
    id2 = UUID.nameUUIDFromBytes( new byte[]{(byte)44, (byte)67, (byte)23,
					     (byte)186, (byte)139, (byte)59,
					     (byte)191, (byte)77, (byte)20 });
    harness.check(id1.equals(id2));

    id1 = new UUID(-8248928743552566013L, -8885233673248765009L);
    id2 = UUID.nameUUIDFromBytes( new byte[]{(byte)132, (byte)150, (byte)203,
					     (byte)54, (byte)68, (byte)31,
					     (byte)48, (byte)208 });
    harness.check(id1.equals(id2));

    id1 = new UUID(-3367149413545070022L, -6453356609274991779L);
    id2 = UUID.nameUUIDFromBytes( new byte[]{
				    (byte)63 });
    harness.check(id1.equals(id2));

    id1 = new UUID(-1846445036491163506L, -6140770342100802383L);
    id2 = UUID.nameUUIDFromBytes( new byte[]{(byte)216, (byte)9, (byte)56,
					     (byte)238, (byte)224, (byte)237,
					     (byte)253 });
    harness.check(id1.equals(id2));

    id1 = new UUID(-7426333540612096407L, -9029142625441791623L);
    id2 = UUID.nameUUIDFromBytes( new byte[]{(byte)86, (byte)131, 
					     (byte)201 });
    harness.check(id1.equals(id2));

    id1 = new UUID(-3162216497309273596L, -6232971331865394562L);
    id2 = UUID.nameUUIDFromBytes( new byte[]{ });
    harness.check(id1.equals(id2));
  }

  private void testFromString(TestHarness harness)
  {
    for(int i = 0; i < ids.length; i++ )
      harness.check( ids[i].equals( UUID.fromString( strs[i] ) ) );
    for(int i = 0; i < randomIds.length; i++)
      harness.check( randomIds[i].equals
		     (UUID.fromString( randomStrs[i] ) ) );
  }
  
  private void testToString(TestHarness harness)
  {

    for(int i = 0; i < ids.length; i++)
      harness.check(ids[i].toString().equals(strs[i]));
    for(int i = 0; i < randomIds.length; i++)
      harness.check(randomIds[i].toString().equals(randomStrs[i]));
  }
  
  private void testHash(TestHarness harness)
  {
    int[] hashes = new int[]
      {
	-1821492227,
	-1082370483,
	-1216394612,
	-1393194177
      };
    
    for(int i = 0; i < ids.length; i++)
      harness.check(ids[i].hashCode(), hashes[i]);
  }
  
  private void testCompare(TestHarness harness)
  {
    for(int i = 0; i < ids.length; i++)
      {
	UUID id = new UUID(ids[i].getMostSignificantBits(),
			   ids[i].getLeastSignificantBits());
	for(int j = 0; j < ids.length; j++)
	  {
	    int c1 = id.compareTo(ids[j]);
	    int c2; 
	    if( i < j ) c2 = -1;
	    else if( i > j) c2 = 1;
	    else c2 = 0;
	    harness.check(c1, c2);
	  }
      }
  }
  
  private void testRandom(TestHarness harness)
  {
    UUID id = UUID.randomUUID();
    harness.check(id.variant(), 2);
    harness.check(id.version(), 4);
  }

  /**
   * Test variant, version, timestamp, clocksequence, node
   */
  private void testTime(TestHarness harness)
  {
    long[] vals = new long[]
      {
	2, 1, 133723016677800000L, 11357, 8796630719078L,
	2, 1, 133723017146390000L, 11357, 8796630719078L,
	2, 1, 133723017280670001L, 11357, 8796630719078L,
	2, 1, 133723017372240002L, 11357, 8796630719078L
      };

    for(int i = 0; i < ids.length; i++)
      {
	harness.check(ids[i].variant(), vals[ i * 5 ]);
	harness.check(ids[i].version(), vals[ i * 5 + 1]);
	harness.check(ids[i].timestamp(), vals[ i * 5 + 2]);
	harness.check(ids[i].clockSequence(), vals[ i * 5 + 3]);
	harness.check(ids[i].node(), vals[ i * 5 + 4]);
      }
  }

  private void testEquals(TestHarness harness)
  {
    for(int i = 0; i < ids.length; i++)
      {
	UUID id = new UUID(ids[i].getMostSignificantBits(),
			   ids[i].getLeastSignificantBits());
	for(int j = 0; j < ids.length; j++)
	  harness.check((id.equals(ids[j]) == (i == j)));
      }
  }
}





^ permalink raw reply	[flat|nested] 2+ messages in thread

end of thread, other threads:[~2006-07-16  4:31 UTC | newest]

Thread overview: 2+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2006-07-16  4:30 UUID tests Sven de Marothy
2006-07-16  4:31 ` UUID tests. oops Sven de Marothy

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).