PageRenderTime 21ms CodeModel.GetById 12ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 0ms

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