Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

56
LINES

< > BotCompany Repo | #1010607 // Symbol test (symbols are strings comparable with ==) [v2, OK]

JavaX source code (desktop) [tags: use-pretranspiled] - run with: x30.jar

Download Jar. Libraryless. Click here for Pure Java version (662L/5K).

1  
!7
2  
3  
sclass Symbol {
4  
  S text;
5  
  
6  
  *() {}
7  
  *(S *text, bool dummy) {} // weird signature to prevent accidental calling
8  
  
9  
  public int hashCode() { ret main.hashCode(text); }
10  
  toString { ret text; }
11  
  public bool equals(O o) {
12  
    ret this == o;
13  
  }
14  
}
15  
16  
sclass SymbolTester {
17  
  S text;
18  
  
19  
  *() {}
20  
  *(S *text) {}
21  
  
22  
  public int hashCode() { ret main.hashCode(text); }
23  
  public bool equals(O o) {
24  
    ret o instanceof Symbol && eq(text, o/Symbol.text);
25  
  }
26  
}
27  
28  
static new WeakHashMap<Symbol, Bool> symbolMap;
29  
30  
static Symbol symbol(S s) {
31  
  if (s == null) null;
32  
  synchronized(symbolMap) {
33  
    // This is a trick that works because of how WeakHashMap compares keys.
34  
    SymbolTester test = new(s);
35  
    //WeakHashMap2.Entry<Symbol, Bool> e = symbolMap.getEntry(test);
36  
    //Symbol sym = e == null ? null : e.get();
37  
    O e = call(symbolMap, 'getEntry, test);
38  
    Symbol sym = e == null ? null : ((WeakReference<Symbol>) e).get();
39  
    if (sym == null)
40  
      symbolMap.put(sym = Symbol(s, false), Bool.TRUE);
41  
    ret sym;
42  
  }
43  
}
44  
45  
p {
46  
  S s1 = "a", s2 = lower("A");
47  
  assertNotIdentical(s1, s2); // Now more clearly showing the improvement
48  
  Symbol a = symbol(s1);
49  
  Symbol a2 = symbol(s2);
50  
  assertEquals("a", str(a));
51  
  assertEquals("a", str(a2));
52  
  assertIdentical(a, a2);
53  
  Symbol b = symbol("b");
54  
  assertEquals("b", str(b));
55  
  print("OK");
56  
}

Author comment

Began life as a copy of #1010604

download  show line numbers  debug dex  old transpilations   

Travelled to 13 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1010607
Snippet name: Symbol test (symbols are strings comparable with ==) [v2, OK]
Eternal ID of this version: #1010607/9
Text MD5: 9166f43b825a9cac66b1694f3141b769
Transpilation MD5: 39bb85749a16edf9d12a3b7e180553cd
Author: stefan
Category: javax
Type: JavaX source code (desktop)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2017-09-23 19:47:35
Source code size: 1396 bytes / 56 lines
Pitched / IR pitched: No / No
Views / Downloads: 365 / 791
Version history: 8 change(s)
Referenced in: [show references]