1 package org.jscsi.target.util;
2
3 /**
4 * A class for serial number arithmetics, as defined in <code>[RFC 1982]</code>, with <code>SERIAL_BITS = 32</code>.
5 * <p>
6 * Unlike the original algorithm, this implementation is based on unsigned subtraction, resolving the issue of undefined
7 * comparisons, however introducing one additional oddity - each member of a pair of serial numbers with a wrapped
8 * distance of <code>2^(SERIAL_BITS - 1)</code> will be considered less than (and greater than) the other one.
9 *
10 * @author Andreas Ergenzinger
11 */
12 public final class SerialArithmeticNumber {
13
14 /**
15 * The signed integer representation of the serial arithmetic number.
16 */
17 private int value;
18
19 /**
20 * Creates a new {@link SerialArithmeticNumber} with a starting {@link #value} of zero.
21 */
22 public SerialArithmeticNumber () {
23 this(0);
24 }
25
26 /**
27 * Creates a new {@link SerialArithmeticNumber} with the specified starting {@link #value}.
28 *
29 * @param value the initial {@link #value}
30 */
31 public SerialArithmeticNumber (final int value) {
32 this.value = value;
33 }
34
35 /**
36 * Increments the {@link SerialArithmeticNumber}'s {@link #value} by one.
37 */
38 public void increment () {
39 ++value;
40 }
41
42 /**
43 * Returns <code>true</code> if the parameter matches the {@link #value} and <code>false</code> if it does not.
44 *
45 * @param serialArithmeticNumber the serial arithmetic number to match
46 * @return <code>true</code> if the parameter matches the {@link #value} and <code>false</code> if it does not
47 */
48 public boolean equals (final int serialArithmeticNumber) {
49 return value == serialArithmeticNumber;
50 }
51
52 /**
53 * Returns <code>true</code> if the parameter is less than the {@link #value} in serial number arithmetics and
54 * <code>false</code> if it is not.
55 *
56 * @param serialArithmeticNumber the serial arithmetic number to match
57 * @return <code>true</code> if the parameter is less than the {@link #value} in serial number arithmetics and
58 * <code>false</code> if it is not
59 */
60 public boolean lessThan (final int serialArithmeticNumber) {
61 if (value - serialArithmeticNumber < 0) return true;
62 return false;
63 }
64
65 /**
66 * Returns <code>true</code> if the parameter is greater than the {@link #value} in serial number arithmetics and
67 * <code>false</code> if it is not.
68 *
69 * @param serialArithmeticNumber the serial arithmetic number to match
70 * @return <code>true</code> if the parameter is greater than the {@link #value} in serial number arithmetics and
71 * <code>false</code> if it is not
72 */
73 public boolean greaterThan (final int serialArithmeticNumber) {
74 if (serialArithmeticNumber - value < 0) return true;
75 return false;
76 }
77
78 /**
79 * Returns the {@link SerialArithmeticNumber}'s {@link #value}.
80 *
81 * @return the {@link #value}
82 */
83 public int getValue () {
84 return value;
85 }
86 }