/src/kilim/http/KeyValues.java

http://github.com/kilim/kilim · Java · 75 lines · 49 code · 8 blank · 18 comment · 11 complexity · 0b7437293ce4a828ad35d5a5164a0447 MD5 · raw file

  1. /* Copyright (c) 2006, Sriram Srinivasan
  2. *
  3. * You may distribute this software under the terms of the license
  4. * specified in the file "License"
  5. */
  6. package kilim.http;
  7. /**
  8. * A low overhead map to avoid creating too many objects (Entry objects and iterators etc)
  9. */
  10. public class KeyValues {
  11. public String[] keys;
  12. public String[] values;
  13. public int count;
  14. public KeyValues() {this(5);}
  15. public KeyValues(int size) {
  16. keys = new String[size];
  17. values = new String[size];
  18. }
  19. /**
  20. * @param key
  21. * @return value for the given key.
  22. */
  23. public String get(String key) {
  24. int i = indexOf(key);
  25. return i == -1 ? "" : values[i];
  26. }
  27. public int indexOf(String key) {
  28. int len = count;
  29. for (int i = 0; i < len; i++) {
  30. if (keys[i].equals(key)) {
  31. return i;
  32. }
  33. }
  34. return -1;
  35. }
  36. /**
  37. * add/replace key value pair.
  38. * @param key
  39. * @param value
  40. * @return old value
  41. */
  42. public void put(String key, String value) {
  43. int i = indexOf(key);
  44. if (i == -1) {
  45. if (count == keys.length) {
  46. keys = (String[]) Utils.growArray(keys, count * 2);
  47. values = (String[]) Utils.growArray(values, count * 2);
  48. }
  49. keys[count] = key;
  50. values[count] = value;
  51. count++;
  52. } else {
  53. values[i] = value;
  54. }
  55. }
  56. @Override
  57. public String toString() {
  58. StringBuilder sb = new StringBuilder();
  59. sb.append('[');
  60. for (int i = 0; i < count; i++) {
  61. if (i != 0) sb.append(", ");
  62. sb.append(keys[i]).append(':').append(values[i]);
  63. }
  64. sb.append(']');
  65. return sb.toString();
  66. }
  67. }