Skip to content

Commit

Permalink
Crypto: More efficient enum lookup by code
Browse files Browse the repository at this point in the history
  • Loading branch information
zzzi2p committed Jan 29, 2024
1 parent 8da5e01 commit 2482b1d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 12 deletions.
17 changes: 11 additions & 6 deletions core/java/src/net/i2p/crypto/EncType.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@

import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidParameterSpecException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import static net.i2p.crypto.x25519.spec.X25519Spec.X25519_SPEC;
import net.i2p.data.Hash;
Expand Down Expand Up @@ -156,18 +154,25 @@ public static boolean isAvailable(String stype) {
return type.isAvailable();
}

private static final Map<Integer, EncType> BY_CODE = new HashMap<Integer, EncType>();
private static final EncType[] BY_CODE;

static {
for (EncType type : EncType.values()) {
if (BY_CODE.put(Integer.valueOf(type.getCode()), type) != null)
EncType[] values = values();
int max = values[values.length - 1].getCode();
BY_CODE = new EncType[max + 1];
for (EncType type : values) {
int i = type.getCode();
if (BY_CODE[i] != null)
throw new IllegalStateException("Duplicate EncType code");
BY_CODE[i] = type;
}
}

/** @return null if not supported */
public static EncType getByCode(int code) {
return BY_CODE.get(Integer.valueOf(code));
if (code < 0 || code >= BY_CODE.length)
return null;
return BY_CODE[code];
}

/**
Expand Down
17 changes: 11 additions & 6 deletions core/java/src/net/i2p/crypto/SigType.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@
import java.security.Signature;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidParameterSpecException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import net.i2p.crypto.eddsa.spec.EdDSANamedCurveTable;
import net.i2p.data.Hash;
Expand Down Expand Up @@ -277,18 +275,25 @@ public static boolean isAvailable(String stype) {
return type.isAvailable();
}

private static final Map<Integer, SigType> BY_CODE = new HashMap<Integer, SigType>();
private static final SigType[] BY_CODE;

static {
for (SigType type : SigType.values()) {
if (BY_CODE.put(Integer.valueOf(type.getCode()), type) != null)
SigType[] values = values();
int max = values[values.length - 1].getCode();
BY_CODE = new SigType[max + 1];
for (SigType type : values) {
int i = type.getCode();
if (BY_CODE[i] != null)
throw new IllegalStateException("Duplicate SigType code");
BY_CODE[i] = type;
}
}

/** @return null if not supported */
public static SigType getByCode(int code) {
return BY_CODE.get(Integer.valueOf(code));
if (code < 0 || code >= BY_CODE.length)
return null;
return BY_CODE[code];
}

/**
Expand Down

0 comments on commit 2482b1d

Please sign in to comment.