Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add configurable hash mod base #75

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>
Expand Down
15 changes: 13 additions & 2 deletions src/main/java/org/hashids/Hashids.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,14 @@ public class Hashids {
private static final int MIN_ALPHABET_LENGTH = 16;
private static final double SEP_DIV = 3.5;
private static final int GUARD_DIV = 12;
private static final int DEFAULT_HASH_MOD_BASE = 100;

private final String salt;
private final int minHashLength;
private final String alphabet;
private final String seps;
private final String guards;
private final int hashModBase;

public Hashids() {
this(DEFAULT_SALT);
Expand All @@ -47,12 +49,21 @@ public Hashids(String salt) {
}

public Hashids(String salt, int minHashLength) {
this(salt, minHashLength, DEFAULT_ALPHABET);
this(salt, minHashLength, DEFAULT_ALPHABET, DEFAULT_HASH_MOD_BASE);
}

public Hashids(String salt, int minHashLength, int hashModBase) {
this(salt, minHashLength, DEFAULT_ALPHABET, hashModBase);
}

public Hashids(String salt, int minHashLength, String alphabet) {
this(salt, minHashLength, alphabet, DEFAULT_HASH_MOD_BASE);
}

public Hashids(String salt, int minHashLength, String alphabet, int hashModBase) {
this.salt = salt != null ? salt : DEFAULT_SALT;
this.minHashLength = minHashLength > 0 ? minHashLength : DEFAULT_MIN_HASH_LENGTH;
this.hashModBase = hashModBase != 0? hashModBase : DEFAULT_HASH_MOD_BASE;

final StringBuilder uniqueAlphabet = new StringBuilder();
for (int i = 0; i < alphabet.length(); i++) {
Expand Down Expand Up @@ -226,7 +237,7 @@ public static int checkedCast(long value) {
private String _encode(long... numbers) {
long numberHashInt = 0;
for (int i = 0; i < numbers.length; i++) {
numberHashInt += (numbers[i] % (i + 100));
numberHashInt += (numbers[i] % (i + hashModBase));
}
String alphabet = this.alphabet;
final char ret = alphabet.charAt((int) (numberHashInt % alphabet.length()));
Expand Down