CharVector.java 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright (c) 2001, 2004 Per M.A. Bothner and Brainfood Inc.
  2. // This is free software; for terms and warranty disclaimer see ./COPYING.
  3. package gnu.lists;
  4. import gnu.text.Char;
  5. import java.io.*;
  6. import gnu.text.Char;
  7. /** Simple adjustable-length vector whose elements are 16-bit chars.
  8. * Meant to be used as a wrapper for char arrays, so does not
  9. * implement CharSequence.
  10. * @author Per Bothner
  11. */
  12. public class CharVector extends AbstractCharVector<Character>
  13. {
  14. /** Create an CharVector from a char[].
  15. * Note that this contructor does *not* copy the argument. */
  16. public CharVector(char[] values) {
  17. data = values;
  18. }
  19. public final Character getRaw(int index) {
  20. return data[index];
  21. }
  22. @Override
  23. public final void setRaw(int index, Character value) {
  24. data[index] = value.charValue();
  25. }
  26. public static CharVector castOrNull(Object obj) {
  27. if (obj instanceof char[])
  28. return new CharVector((char[]) obj);
  29. if (obj instanceof CharVector)
  30. return (CharVector) obj;
  31. if (obj instanceof CharSequence) {
  32. char[] chars = obj instanceof FString ? ((FString) obj).toCharArray()
  33. : obj.toString().toCharArray();
  34. return new CharVector(chars);
  35. }
  36. return null;
  37. }
  38. public static CharVector cast(Object value) {
  39. CharVector vec = castOrNull(value);
  40. if (vec == null) {
  41. String msg;
  42. if (value == null)
  43. msg = "cannot convert null to CharVector";
  44. else
  45. msg = "cannot convert a "+value.getClass().getName()+" to CharVector";
  46. throw new ClassCastException(msg);
  47. }
  48. return vec;
  49. }
  50. public boolean equals(Object obj) {
  51. return obj instanceof CharVector && equals(this, (CharVector) obj);
  52. }
  53. @Override
  54. protected CharVector newInstance(int newLength) {
  55. return new CharVector(newLength < 0 ? data : new char[newLength]);
  56. }
  57. public int getElementKind() { return CHAR_VALUE; }
  58. public String getTag() { return "c16"; }
  59. }