1 | /* |
2 | * Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0, |
3 | * and the EPL 1.0 (http://h2database.com/html/license.html). |
4 | * Initial Developer: H2 Group |
5 | */ |
6 | package org.h2.value; |
7 | |
8 | import org.h2.engine.SysProperties; |
9 | import org.h2.util.StringUtils; |
10 | |
11 | /** |
12 | * Implementation of the VARCHAR_IGNORECASE data type. |
13 | */ |
14 | public class ValueStringIgnoreCase extends ValueString { |
15 | |
16 | private static final ValueStringIgnoreCase EMPTY = |
17 | new ValueStringIgnoreCase(""); |
18 | private int hash; |
19 | |
20 | protected ValueStringIgnoreCase(String value) { |
21 | super(value); |
22 | } |
23 | |
24 | @Override |
25 | public int getType() { |
26 | return Value.STRING_IGNORECASE; |
27 | } |
28 | |
29 | @Override |
30 | protected int compareSecure(Value o, CompareMode mode) { |
31 | ValueStringIgnoreCase v = (ValueStringIgnoreCase) o; |
32 | return mode.compareString(value, v.value, true); |
33 | } |
34 | |
35 | @Override |
36 | public boolean equals(Object other) { |
37 | return other instanceof ValueString |
38 | && value.equalsIgnoreCase(((ValueString) other).value); |
39 | } |
40 | |
41 | @Override |
42 | public int hashCode() { |
43 | if (hash == 0) { |
44 | // this is locale sensitive |
45 | hash = value.toUpperCase().hashCode(); |
46 | } |
47 | return hash; |
48 | } |
49 | |
50 | @Override |
51 | public String getSQL() { |
52 | return "CAST(" + StringUtils.quoteStringSQL(value) + " AS VARCHAR_IGNORECASE)"; |
53 | } |
54 | |
55 | /** |
56 | * Get or create a case insensitive string value for the given string. |
57 | * The value will have the same case as the passed string. |
58 | * |
59 | * @param s the string |
60 | * @return the value |
61 | */ |
62 | public static ValueStringIgnoreCase get(String s) { |
63 | if (s.length() == 0) { |
64 | return EMPTY; |
65 | } |
66 | ValueStringIgnoreCase obj = new ValueStringIgnoreCase(StringUtils.cache(s)); |
67 | if (s.length() > SysProperties.OBJECT_CACHE_MAX_PER_ELEMENT_SIZE) { |
68 | return obj; |
69 | } |
70 | ValueStringIgnoreCase cache = (ValueStringIgnoreCase) Value.cache(obj); |
71 | // the cached object could have the wrong case |
72 | // (it would still be 'equal', but we don't like to store it) |
73 | if (cache.value.equals(s)) { |
74 | return cache; |
75 | } |
76 | return obj; |
77 | } |
78 | |
79 | @Override |
80 | protected ValueString getNew(String s) { |
81 | return ValueStringIgnoreCase.get(s); |
82 | } |
83 | |
84 | } |