1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.handler.codec.quic;
17
18 import org.jetbrains.annotations.NotNull;
19 import org.jetbrains.annotations.Nullable;
20
21 import java.nio.ByteBuffer;
22 import java.security.SecureRandom;
23 import java.util.HashMap;
24 import java.util.Map;
25 import java.util.Objects;
26
27
28
29
30
31 final class ConnectionIdChannelMap {
32 private static final SecureRandom random = new SecureRandom();
33
34 private final Map<ConnectionIdKey, QuicheQuicChannel> channelMap = new HashMap<>();
35 private final SipHash sipHash;
36
37 ConnectionIdChannelMap() {
38 byte[] seed = new byte[SipHash.SEED_LENGTH];
39 random.nextBytes(seed);
40
41 sipHash = new SipHash(1, 3, seed);
42 }
43
44 private ConnectionIdKey key(ByteBuffer cid) {
45 long hash = sipHash.macHash(cid);
46 return new ConnectionIdKey(hash, cid);
47 }
48
49 @Nullable
50 QuicheQuicChannel put(ByteBuffer cid, QuicheQuicChannel channel) {
51 return channelMap.put(key(cid), channel);
52 }
53
54 @Nullable
55 QuicheQuicChannel remove(ByteBuffer cid) {
56 return channelMap.remove(key(cid));
57 }
58
59 @Nullable
60 QuicheQuicChannel get(ByteBuffer cid) {
61 return channelMap.get(key(cid));
62 }
63
64 void clear() {
65 channelMap.clear();
66 }
67
68 private static final class ConnectionIdKey implements Comparable<ConnectionIdKey> {
69 private final long hash;
70 private final ByteBuffer key;
71
72 ConnectionIdKey(long hash, ByteBuffer key) {
73 this.hash = hash;
74 this.key = key;
75 }
76
77 @Override
78 public boolean equals(Object o) {
79 if (this == o) {
80 return true;
81 }
82 if (o == null || getClass() != o.getClass()) {
83 return false;
84 }
85 ConnectionIdKey that = (ConnectionIdKey) o;
86 return hash == that.hash && Objects.equals(key, that.key);
87 }
88
89 @Override
90 public int hashCode() {
91 return (int) hash;
92 }
93
94 @Override
95 public int compareTo(@NotNull ConnectionIdChannelMap.ConnectionIdKey o) {
96 int result = Long.compare(hash, o.hash);
97 return result != 0 ? result : key.compareTo(o.key);
98 }
99 }
100 }