SetOfIntegerSyntax.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. /* SetOfIntegerSyntax.java --
  2. Copyright (C) 2003, 2004, 2005 Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package javax.print.attribute;
  32. import java.io.Serializable;
  33. import java.text.CharacterIterator;
  34. import java.text.StringCharacterIterator;
  35. import java.util.ArrayList;
  36. import java.util.Arrays;
  37. import java.util.Comparator;
  38. /**
  39. * <code>SetOfIntegerSyntax</code> is the abstract base class of all attribute
  40. * classes which provide a set of non-negative integers as value (e.g. the
  41. * page ranges to print) represented as single values or ranges of values.
  42. * <p>
  43. * A <code>SetOfIntegerSyntax</code> instance consists of an integer array of
  44. * ranges. Ranges may have the same lower and upper bound representing a single
  45. * integer value. Ranges with a lower bound greater than the upper bound are
  46. * null ranges and discarded. Ranges may overlap in their values. In no case
  47. * negative integers are allowed.
  48. * </p>
  49. * <p>
  50. * There are several constructors available:
  51. * <ul>
  52. * <li><code>SetOfIntegerSyntax(int member)</code><br>
  53. * Constructor for an instance with only one integer value.
  54. * </li><br>
  55. * <li><code>SetOfIntegerSyntax(int lowerBound, int upperBound)</code><br>
  56. * Constructor for an instance with one range of integer values.
  57. * </li><br>
  58. * <li><code>SetOfIntegerSyntax(int[][] members)</code><br>
  59. * Flexible constructor for an instance with several single integer values
  60. * and/or several ranges of integer values. The allowed array form is an
  61. * array of integer arrays of length one or two. Examples are:
  62. * <code>int[0][]</code> for empty set of integers, <code>int[][] {{1}}</code>
  63. * , <code>int[][] {{1,5}}</code>, <code>int[][] {{1,5},{7,9}}</code>,
  64. * <code>int[][] {{3,7},{19}}</code>.
  65. * </li><br>
  66. * <li><code>SetOfIntegerSyntax(String s)</code><br>
  67. * Flexible constructor for an instance with several single integer values
  68. * and/or several ranges of integer values. The allowed String instance have
  69. * to be a String with comma separated ranges of integer values or single
  70. * values. Ranges are represented by two integer with a hypen (-) or colon (:)
  71. * between the lower and upper bound value. Whitespace characters are ignored.
  72. * Examples are: <code>""</code> for an empty set of integers,
  73. * <code>"1"</code>, <code>"1-5"</code>, <code>"1-5,7-9"</code>,
  74. * <code>"3-7,19"</code> and <code>"1:2,4"</code>.
  75. * </li>
  76. * </ul>
  77. * </p>
  78. * <p>
  79. * <b>Internal storage:</b><br>
  80. * The set of integers are stored internally in a normalized array form.
  81. * In the normalized array form the set of integer ranges are represented
  82. * in as few ranges as possible and overlapping ranges are merged. The ranges
  83. * are always represented as an integer array of length two with ranges
  84. * stored in {lower bound, upper bound} form. The ranges are stored in
  85. * ascending order, without any null ranges.
  86. * </p>
  87. * @author Michael Koch (konqueror@gmx.de)
  88. */
  89. public abstract class SetOfIntegerSyntax
  90. implements Cloneable, Serializable
  91. {
  92. private static final long serialVersionUID = 3666874174847632203L;
  93. private int[][] members;
  94. private static int[][] normalize(int[][] values, int size)
  95. {
  96. // Sort into increasing order. First the first index is
  97. // compared, then the second.
  98. Arrays.sort(values, 0, size, new Comparator()
  99. {
  100. public int compare(Object o1, Object o2)
  101. {
  102. int[] v1 = (int[]) o1;
  103. int[] v2 = (int[]) o2;
  104. if (v1[0] == v2[0])
  105. return v1[1] - v2[1];
  106. return v1[0] - v2[0];
  107. }
  108. });
  109. // Now coalesce overlapping ranges.
  110. int outIndex = 0;
  111. for (int i = 0; i < size; ++i)
  112. {
  113. // Note that we compare with values[i][1]+1, since
  114. // we can coalesce {0,1} with {2,x}.
  115. int save = i;
  116. while (i + 1 < size && values[i + 1][0] <= values[i][1] + 1)
  117. {
  118. values[i][1] = Math.max(values[i][1], values[i + 1][1]);
  119. ++i;
  120. }
  121. values[outIndex++] = values[save];
  122. }
  123. int[][] result = new int[outIndex][];
  124. System.arraycopy(values, 0, result, 0, outIndex);
  125. return result;
  126. }
  127. /**
  128. * Creates a <code>SetOfIntegerSyntax</code> object.
  129. *
  130. * @param member the member value
  131. *
  132. * @exception IllegalArgumentException if member is &lt; 0
  133. */
  134. protected SetOfIntegerSyntax(int member)
  135. {
  136. if (member < 0)
  137. throw new IllegalArgumentException("member may not be less than 0");
  138. this.members = new int[][]{{member, member}};
  139. }
  140. /**
  141. * Creates a <code>SetOfIntegerSyntax</code> object.
  142. *
  143. * @param members the members to use in this set. If
  144. * <code>null</code> an empty set is created.
  145. *
  146. * @exception IllegalArgumentException if any element is invalid
  147. * @exception NullPointerException if any element of members is null
  148. */
  149. protected SetOfIntegerSyntax(int[][] members)
  150. {
  151. int[][] newMembers;
  152. int outIndex = 0;
  153. if (members == null)
  154. newMembers = new int[0][];
  155. else
  156. {
  157. newMembers = new int[members.length][];
  158. for (int index = 0; index < members.length; index++)
  159. {
  160. int lower;
  161. int upper;
  162. if (members[index].length == 1)
  163. {
  164. lower = members[index][0];
  165. upper = members[index][0];
  166. }
  167. else if (members[index].length == 2)
  168. {
  169. lower = members[index][0];
  170. upper = members[index][1];
  171. }
  172. else
  173. throw new IllegalArgumentException("invalid member element");
  174. // We only want to reject non-null ranges where lower<0.
  175. if (lower <= upper && lower < 0)
  176. throw new IllegalArgumentException("invalid member element");
  177. if (lower <= upper)
  178. {
  179. int[] range = new int[2];
  180. range[0] = lower;
  181. range[1] = upper;
  182. newMembers[outIndex++] = range;
  183. }
  184. }
  185. }
  186. this.members = normalize(newMembers, outIndex);
  187. }
  188. private boolean skipWhitespace(StringCharacterIterator i)
  189. {
  190. while (Character.isWhitespace(i.current()))
  191. i.next();
  192. return i.current() == CharacterIterator.DONE;
  193. }
  194. private boolean skipNumber(StringCharacterIterator i)
  195. {
  196. boolean readAny = false;
  197. while (Character.isDigit(i.current()))
  198. {
  199. readAny = true;
  200. i.next();
  201. }
  202. return readAny;
  203. }
  204. /**
  205. * Creates a <code>SetOfIntegerSyntax</code> object.
  206. *
  207. * @param s the members to use in this set in string form. If
  208. * <code>null</code> an empty set is created.
  209. *
  210. * @exception IllegalArgumentException if any element is invalid
  211. */
  212. protected SetOfIntegerSyntax(String s)
  213. {
  214. if (s == null)
  215. this.members = normalize(new int[0][], 0);
  216. else
  217. {
  218. ArrayList vals = new ArrayList();
  219. StringCharacterIterator it = new StringCharacterIterator(s);
  220. while (true)
  221. {
  222. // Skip whitespace.
  223. if (skipWhitespace(it))
  224. break;
  225. // Parse integer.
  226. int index = it.getIndex();
  227. if (! skipNumber(it))
  228. throw new IllegalArgumentException();
  229. int[] item = new int[2];
  230. item[0] = Integer.parseInt(s.substring(index, it.getIndex()));
  231. if (! skipWhitespace(it))
  232. {
  233. char c = it.current();
  234. if (c == ':' || c == '-')
  235. {
  236. it.next();
  237. if (skipWhitespace(it))
  238. throw new IllegalArgumentException();
  239. index = it.getIndex();
  240. if (! skipNumber(it))
  241. throw new IllegalArgumentException();
  242. item[1] = Integer.parseInt(s.substring(index, it.getIndex()));
  243. }
  244. else
  245. item[1] = item[0];
  246. }
  247. else
  248. item[1] = item[0];
  249. if (item[0] <= item[1])
  250. vals.add(item);
  251. if (skipWhitespace(it))
  252. break;
  253. if (it.current() != ',')
  254. throw new IllegalArgumentException();
  255. it.next();
  256. }
  257. members = normalize((int[][]) vals.toArray(new int[0][]), vals.size());
  258. }
  259. }
  260. /**
  261. * Creates a <code>SetOfIntegerSyntax</code> object.
  262. *
  263. * @param lowerBound the lower bound value
  264. * @param upperBound the upper bound value
  265. *
  266. * @exception IllegalArgumentException if lowerBound &lt;= upperbound
  267. * and lowerBound &lt; 0
  268. */
  269. protected SetOfIntegerSyntax(int lowerBound, int upperBound)
  270. {
  271. // We only want to reject non-null ranges where lower<0.
  272. if (lowerBound <= upperBound
  273. && lowerBound < 0)
  274. throw new IllegalArgumentException();
  275. members = (lowerBound <= upperBound ? new int[][]{{lowerBound, upperBound}}
  276. : new int[0][]);
  277. }
  278. /**
  279. * Checks if this set contains the given value.
  280. *
  281. * @param value the value to test for
  282. *
  283. * @return true if this set contains value, false otherwise
  284. */
  285. public boolean contains(int value)
  286. {
  287. // This only works on a normalized member array.
  288. for (int index = 0; index < members.length; index++)
  289. {
  290. if (value < members[index][0])
  291. return false;
  292. else if (value <= members[index][1])
  293. return true;
  294. }
  295. return false;
  296. }
  297. /**
  298. * Checks if this set contains the given value.
  299. *
  300. * @param value the value to test for
  301. *
  302. * @return true if this set contains value, false otherwise
  303. */
  304. public boolean contains(IntegerSyntax value)
  305. {
  306. return contains(value.getValue());
  307. }
  308. /**
  309. * Tests if the given object is equal to this object.
  310. *
  311. * @param obj the object to test
  312. *
  313. * @return true if both objects are equal, false otherwise.
  314. */
  315. public boolean equals(Object obj)
  316. {
  317. if (! (obj instanceof SetOfIntegerSyntax))
  318. return false;
  319. SetOfIntegerSyntax other = (SetOfIntegerSyntax) obj;
  320. if (other.members.length != members.length)
  321. return false;
  322. for (int i = 0; i < members.length; ++i)
  323. {
  324. if (members[i][0] != other.members[i][0]
  325. || members[i][1] != other.members[i][1])
  326. return false;
  327. }
  328. return true;
  329. }
  330. /**
  331. * Returns an array describing the members included in this set.
  332. *
  333. * @return The members in normalized array form.
  334. */
  335. public int[][] getMembers()
  336. {
  337. return (int[][]) members.clone();
  338. }
  339. /**
  340. * Returns the hashcode for this object.
  341. *
  342. * @return The hashcode.
  343. */
  344. public int hashCode()
  345. {
  346. int result = 0;
  347. for (int i = 0; i < members.length; ++i)
  348. result += members[i][0] + members[i][1];
  349. return result;
  350. }
  351. /**
  352. * Returns the smallest value that is greater than x which is in this set.
  353. *
  354. * @param x an integer value
  355. *
  356. * @return The next smallest integer value, or <code>-1</code> if there
  357. * is no greater integer in the set.
  358. */
  359. public int next(int x)
  360. {
  361. for (int i = 0; i < members.length; ++i)
  362. {
  363. if (x >= members[i][1])
  364. continue;
  365. if (x < members[i][0])
  366. return members[i][0];
  367. // X is in this range.
  368. return x + 1;
  369. }
  370. return -1;
  371. }
  372. /**
  373. * Returns the string representation for this object.
  374. * The value is a zero length string for an empty set, or a comma seperated
  375. * list of ranges and single values in the form <code>"1-2,5-7,10"</code>.
  376. *
  377. * @return The string representation.
  378. */
  379. public String toString()
  380. {
  381. StringBuilder sb = new StringBuilder();
  382. for (int i = 0; i < members.length; ++i)
  383. {
  384. if (i > 0)
  385. sb.append(',');
  386. sb.append(members[i][0]);
  387. if (members[i][0] != members[i][1])
  388. {
  389. sb.append('-');
  390. sb.append(members[i][1]);
  391. }
  392. }
  393. return sb.toString();
  394. }
  395. }