Skip to content
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
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,6 @@ public static long decodeMachineId(long id) {
* @param id the id to decode from
*/
public static int decodeSequence(long id) {
return (int)(id & 0x0000000000000FFF);
return (int)(id & SnowflakeEncodingProvider.SEQUENCE_MASK);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,12 @@ public class SnowflakeEncodingProvider implements EncodingProvider {
*/
public static final int MAX_SEQUENCE_NUMBERS = 4096;

/**
* Number of bits needed to represent all sequence numbers
*/
public static final int SEQUENCE_BITS = 12;
public static final int SEQUENCE_MASK = ~(-1 << SEQUENCE_BITS);

/**
* Number of bits to shift the time over
*/
Expand All @@ -68,9 +74,13 @@ public SnowflakeEncodingProvider(long machineId) {
this.shiftedMachineId = ((machineId % MACHINE_CODES) << SHIFT_MACHINE_CODE_BITS);
}

/**
* Returns a Snowflake ID. Note that only the lower order 12 bits of the sequence number are
* used
*/
@Override
public byte[] encodeAsBytes(long time, int sequence) {
long v = ((time - EPOCH) << SHIFT_TIME_BITS) | shiftedMachineId | sequence;
long v = ((time - EPOCH) << SHIFT_TIME_BITS) | shiftedMachineId | (sequence & SEQUENCE_MASK);

byte[] buffer = new byte[8];
buffer[0] = (byte)(v >>> 56);
Expand Down