c65c5da32aa0aa2f0c07d5307e41390de15cac11
[controller.git] / third-party / openflowj / src / test / java / org / openflow / util / UnsignedTest.java
1
2 /*
3  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
4  *
5  * This program and the accompanying materials are made available under the
6  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
7  * and is available at http://www.eclipse.org/legal/epl-v10.html
8  */
9
10 package org.openflow.util;
11
12 import java.math.BigInteger;
13 import java.nio.ByteBuffer;
14
15 import junit.framework.TestCase;
16
17 public class UnsignedTest extends TestCase {
18     public static String ULONG_MAX = "18446744073709551615";
19
20   /**
21    * Tests that we correctly extract an unsigned long into a BigInteger
22    * @throws Exception
23    */
24   public void testGetUnsignedLong() throws Exception {
25     ByteBuffer bb = ByteBuffer.allocate(8);
26     bb.put((byte)0xff).put((byte)0xff).put((byte)0xff).put((byte)0xff);
27     bb.put((byte)0xff).put((byte)0xff).put((byte)0xff).put((byte)0xff);
28     bb.position(0);
29     bb.limit(8);
30     BigInteger bi = Unsigned.getUnsignedLong(bb);
31     BigInteger uLongMax = new BigInteger(ULONG_MAX);
32     for (int i = 0; i < uLongMax.bitCount(); ++i) {
33         TestCase.assertTrue("Bit: " + i + " should be: " + uLongMax.testBit(i),
34                 uLongMax.testBit(i) == bi.testBit(i));
35     }
36     TestCase.assertEquals(ULONG_MAX, bi.toString());
37
38     bb = ByteBuffer.allocate(10);
39     bb.put((byte)0x00);
40     bb.put((byte)0xff).put((byte)0xff).put((byte)0xff).put((byte)0xff);
41     bb.put((byte)0xff).put((byte)0xff).put((byte)0xff).put((byte)0xff);
42     bb.put((byte)0x00);
43     bb.position(0);
44     bb.limit(10);
45     bi = Unsigned.getUnsignedLong(bb, 1);
46     uLongMax = new BigInteger(ULONG_MAX);
47     for (int i = 0; i < uLongMax.bitCount(); ++i) {
48         TestCase.assertTrue("Bit: " + i + " should be: " + uLongMax.testBit(i),
49                 uLongMax.testBit(i) == bi.testBit(i));
50     }
51     TestCase.assertEquals(ULONG_MAX, bi.toString());
52   }
53
54   /**
55    * Tests that we correctly put an unsigned long into a ByteBuffer
56    * @throws Exception
57    */
58   public void testPutUnsignedLong() throws Exception {
59     ByteBuffer bb = ByteBuffer.allocate(8);
60     BigInteger uLongMax = new BigInteger(ULONG_MAX);
61     Unsigned.putUnsignedLong(bb, uLongMax);
62     for (int i = 0; i < 8; ++i) {
63         TestCase.assertTrue("Byte: " + i + " should be 0xff, was: " + bb.get(i),
64                 (bb.get(i) & (short)0xff) == 0xff);
65     }
66
67     bb = ByteBuffer.allocate(10);
68     Unsigned.putUnsignedLong(bb, uLongMax, 1);
69     int offset = 1;
70     for (int i = 0; i < 8; ++i) {
71         TestCase.assertTrue("Byte: " + i + " should be 0xff, was: " +
72                 bb.get(offset+i), (bb.get(offset+i) & (short)0xff) == 0xff);
73     }
74   }
75 }