Git Product home page Git Product logo

ksuid's Introduction

ksuid

Maven Central Javadoc

This is a Java port of Segment's K-Sortable Globally Unique IDs.

KSUID is for K-Sortable Unique IDentifier. It's a way to generate globally unique IDs similar to RFC 4122 UUIDs, but contain a time component so they can be "roughly" sorted by time of creation. The remainder of the KSUID is randomly generated bytes.

In summary:

  • Roughly sortable by creation time;
  • Can be stored as a string of 27 chars;
  • Can be stored as an array of 20 bytes;
  • String format is encoded to base-62 (0-9A-Za-z);
  • String format is URL safe and has no hyphens.

For the story of how KSUIDs came about, see A brief history of the UUID.

Usage as cli

To use this as a command-line program on Unix-like systems, run

wget https://repo1.maven.org/maven2/com/github/ksuid/ksuid/1.1.2/ksuid-1.1.2-cli.jar
sudo mv ksuid-1.1.2-cli.jar /usr/local/bin/ksuid
sudo chmod +x /usr/local/bin/ksuid

ksuid
# prints 1HCpXwx2EK9oYluWbacgeCnFcLf

Usage as library

Add the library to maven pom.xml (or the equivalent in your build system):

<dependency>
    <groupId>com.github.ksuid</groupId>
    <artifactId>ksuid</artifactId>
    <version>1.1.2</version>
</dependency>

Then simply generate a ksuid string like this:

String ksuid = Ksuid.newKsuid().toString();
System.out.println(ksuid); // prints 1HCpXwx2EK9oYluWbacgeCnFcLf

ย 

For more complex use cases, create a KsuidGenerator with a SecureRandom and get a new Ksuid for use.

Note that KsuidGenerator is threadsafe and Ksuid is immutable (and therefore threadsafe).

// Construct a new KsuidGenerator object. Since it is threadsafe you only need one.
private static final KsuidGenerator KSUID_GENERATOR = new KsuidGenerator(new SecureRandom());

// Get a new Ksuid object.
final Ksuid ksuid = ksuidGenerator.newKsuid();

// The toString() method is the string representation of KSUID.
System.out.println("ksuid:\n" + ksuid  + "\n");

// The log string format shows some details on one line, suitable for logging.
System.out.println("ksuid.toLogString():\n" + ksuid.toLogString() + "\n");

// The inspect string format shows details.
System.out.println("ksuid.toInspectString():\n" + ksuid.toInspectString());

The output from the code block above is

ksuid:
1HCpXwx2EK9oYluWbacgeCnFcLf

ksuid.toLogString():
Ksuid[timestamp = 150215977, string = 1HCpXwx2EK9oYluWbacgeCnFcLf payload = [124, 76, 43, -110, 116, -6, \
    -91, 45, 0, -125, -127, 109, 28, 24, 28, -17], ksuidBytes = [8, -12, 29, 41, 124, 76, 43, -110, 116, \
    -6, -91, 45, 0, -125, -127, 109, 28, 24, 28, -17]]

ksuid.toInspectString():
REPRESENTATION:

  String: 1HCpXwx2EK9oYluWbacgeCnFcLf
     Raw: 08F41D297C4C2B9274FAA52D0083816D1.1.2CEF

COMPONENTS:

       Time: 2019-02-14 23:32:57 -0800 PST
  Timestamp: 150215977
    Payload: 7C4C2B9274FAA52D0083816D1.1.2CEF

Performance

A very rough performance profile for generating KSUIDs was run on a MacBook Pro with a 3.1 GHz Intel Core i7 and 16 GB 2133 MHz LPDDR3 RAM.

public static void main(final String[] args) {
    final KsuidGenerator generator = new KsuidGenerator(new SecureRandom());
    IntStream.range(0, 100).forEach(i -> generator.newKsuid()); // prime the random

    IntStream.iterate(1000, operand -> operand * 10)
             .limit(5)
             .forEach(count -> {
                 final long start = System.nanoTime();
                 IntStream.range(0, count).forEach(i -> generator.newKsuid());
                 final long duration = TimeUnit.MILLISECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS);
                 System.out.println(String.format("%,d in %,d ms. rate = %,d/ms", count, duration, count / duration));
             });
}

The output from the code block above is

1,000 in 14 ms. rate = 71/ms
10,000 in 32 ms. rate = 312/ms
100,000 in 95 ms. rate = 1,052/ms
1,000,000 in 881 ms. rate = 1,135/ms
10,000,000 in 6,665 ms. rate = 1,500/ms

License

This library is Open Source software released under the MIT license.

ksuid's People

Contributors

b-sudharshan avatar myohn-paypal avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ksuid's Issues

Support of unsigned 32 bit UTC timestamp.

It seems that the base62 encoder does not handle uint_32 timestamp properly. This Java version of ksuid only supports year 2014~2082 while the Golang version actually supportes year 2014~2150.

static String base62Encode(final byte[] bytes, final int length) {
    final int size = (int) ceil((bytes.length * BYTE_BITS) / DIGIT_BITS);
    final StringBuilder sb = new StringBuilder(size);

    // Allocate an extra zero value byte in the first position, so that the unsigned 32bit UTC 
    // timestamp value is not treated as negative value and thus being encoded as
    // "000000000000000000000000000"
    byte[] b = new byte[bytes.length+1];
    System.arraycopy(bytes, 0, b, 1, bytes.length);

    BigInteger value = new BigInteger(b);
    while (value.compareTo(ZERO) > 0) {
        final BigInteger[] quotientAndRemainder = value.divideAndRemainder(BASE);
        sb.append(BASE_62_CHARACTERS[abs(quotientAndRemainder[1].intValue())]);
        value = quotientAndRemainder[0];
    }

    while (length > 0 && sb.length() < length) {
        sb.append('0');
    }

    return sb.reverse().toString();
}

Ksuid class does not implement Serializable

Hello. First, thank you for this Java port of the Ksuid library. I have a question: is there any reason why the Ksuid class does not implement Serializable? This severely limits its usage, and other Java implementations defines it as serializable so it looks like it should be ok.

Expose KsuidGenerator#newKsuid(Instant)

It would be nice to be able to create Ksuids directly from Instants. Currently, the only option is to do:

new KsuidGenerator(new SecureRandom()).newKsuid(instant)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.