# ids

#### Rich FitzJohn

#### 2017-05-30

The `ids` package provides randomly generated ids in a number of different forms with different readability and sizes.

## Random bytes

The `random_id` function generates random identifiers by generating `bytes` random bytes and converting to hexadecimal (so each byte becomes a pair of characters). Rather than use R’s random number stream we use the `openssl` package here.

    ids::random_id()

    ## [1] "9aa4d8e7fd4fd2d2007c907f2f43262f"

All `ids` functions take `n` as the first argument to be the number of identifiers generated:

    ids::random_id(5)

    ## [1] "c9ef83cddb1c01acdd5c4ca1c6f80d65" "ce43343eebc5cd985b60feb2c7d7cb32"
    ## [3] "14d2e59fe7af4a6771de5d40c4859460" "03146fbcc3b7c5b1a3a5bf579187a313"
    ## [5] "0ef43dce811ecba10daeb85a1212b858"

The default here is 16 bytes, each of which has 256 values (so 256^16 = 2^128 = 3.4e38 combinations). You can make these larger or smaller with the `bytes` argument:

    ids::random_id(5, 8)

    ## [1] "a2a3873e4d4eb769" "17ef56682957f105" "6ba5316397c06b45"
    ## [4] "702caf1aaf2a1b13" "e155a0e71e524e69"

If `NULL` is provided as `n`, then a generating function is returned (all ids functions do this):

    f <- ids::random_id(NULL, 8)
    f

    ## function (n = 1)
    ## {
    ##     random_id(n, bytes, use_openssl)
    ## }
    ## <environment: 0x2c0def0>

This function sets all arguments except for `n`

    f()

    ## [1] "a54ebe0cea6d08fd"

    f(4)

    ## [1] "bc03e2e830276c4f" "a194b7d74d635a5f" "c5b40b60c0fbd303"
    ## [4] "887cd4842022e54a"

## UUIDs

The above look a lot like UUIDs but they are not actually UUIDs. The `uuid` package provides real UUIDs generated with libuuid, and the `ids::uuid` function provides an interface to that:

    ids::uuid()

    ## [1] "34820d25-2632-4200-b0e5-78cf930911fe"

As above, generate more than one UUID:

    ids::uuid(4)

    ## [1] "dbf9c608-24e3-4dcd-b358-43f0a31ebea2"
    ## [2] "fe92be0e-add9-443b-a83e-160d2c6988ec"
    ## [3] "04235c12-0da1-4bb2-9158-b518aae17c88"
    ## [4] "ef58c280-6155-4e20-b7c9-e26d01c78a7b"

Generate time-based UUIDs:

    ids::uuid(4, use_time = TRUE)

    ## [1] "24fc48f4-454b-11e7-8967-5065f32b99c0"
    ## [2] "24fc4962-454b-11e7-8967-5065f32b99c0"
    ## [3] "24fc49b2-454b-11e7-8967-5065f32b99c0"
    ## [4] "24fc49f8-454b-11e7-8967-5065f32b99c0"

and optionally drop the hyphens:

    ids::uuid(5, drop_hyphens = TRUE)

    ## [1] "64f8abb9462949afb6feaf1c3598ca17" "4d2ae53b4c6a4b60b5e193355205a76f"
    ## [3] "2f78096c87df4b11ac3562733bd292c5" "cf0159ebaa66456aa3d9f3b4ee1254b1"
    ## [5] "34c2390f6abe4f2a8f2c1e08db458a1f"

## Adjective animal

Generate (somewhat) human readable identifiers by combining one or more adjectives with an animal name.

    ids::adjective_animal()

    ## [1] "displeasing_fritillarybutterfly"

The list of adjectives and animals comes from gfycat.com, via https://github.com/a-type/adjective-adjective-animal

Generate more than one identifier:

    ids::adjective_animal(4)

    ## [1] "nitpicking_whiteeye"      "undivined_nene"
    ## [3] "crazy_mockingbird"        "uncongested_amurstarfish"

Use more than one adjective for very long idenfiers

    ids::adjective_animal(4, 3)

    ## [1] "crooked_serpentine_fungoid_nabarlek"
    ## [2] "conservable_kimberlite_sightly_axisdeer"
    ## [3] "psychopharmacological_releasable_unquenchable_cricket"
    ## [4] "gastric_worldlywise_cumbersome_gar"

There are 1748 animal names and 8946 adjectives so each one you add increases the idenfier space by a factor of 8946. So for 1, 2, and 3 adjectives there are about 15.6 million, 140 billion and 1250 trillion possible combinations.

This is a much smaller space than the random identifiers above, but these are more readable and memorable.

Note that here, the random nunbers are coming from R’s random number stream so are affected by `set.seed()`.

Because some of the animal and adjective names are very long (e.g. a quasiextraterritorial hexakosioihexekontahexaphobic queenalexandrasbirdwingbutterfly), in order to generate more readable/memorable identifiers it may be useful to restrict the length. Pass `max_len` in to do this.

    ids::adjective_animal(4, max_len = 6)

    ## [1] "adored_kawala" "gassy_morpho"  "tame_kiwi"     "flinty_cony"

A vector of length 2 here can be used to apply to the adjectives and animal respectively:

    ids::adjective_animal(20, max_len = c(5, Inf))

    ##  [1] "sour_anhinga"             "phony_armyant"
    ##  [3] "slimy_dwarfrabbit"        "brisk_insect"
    ##  [5] "right_neonbluehermitcrab" "heavy_godwit"
    ##  [7] "sooty_urutu"              "other_doctorfish"
    ##  [9] "silt_herculesbeetle"      "manic_emperorshrimp"
    ## [11] "loved_mynah"              "skarn_cormorant"
    ## [13] "alive_howlermonkey"       "kooky_raptors"
    ## [15] "rocky_appaloosa"          "pudgy_tayra"
    ## [17] "kooky_estuarinecrocodile" "swift_sphinx"
    ## [19] "icky_fattaileddunnart"    "dry_englishpointer"

Note that this decreases the pool size and so increases the chance of collisions.

In addition to snake_case, the default, the punctuation between words can be changed to:

kebab-case:

    ids::adjective_animal(1, 2, style = "kebab")

    ## [1] "intact-unauthorized-swallowtailbutterfly"

dot.case:

    ids::adjective_animal(1, 2, style = "dot")

    ## [1] "germinable.sighted.wrasse"

camel-case:

    ids::adjective_animal(1, 2, style = "camel")

    ## [1] "holographicRefillableGiantschnauzer"

PascalCase:

    ids::adjective_animal(1, 2, style = "pascal")

    ## [1] "EvadibleSelfhonouredBufflehead"

CONSTANT_CASE (aka SHOUTY_CASE)

    ids::adjective_animal(1, 2, style = "constant")

    ## [1] "RED_CENTAURIAN_COCKERSPANIEL"

or with spaces, lower case:

    ids::adjective_animal(1, 2, style = "lower")

    ## [1] "civic depressed amoeba"

UPPER CASE

    ids::adjective_animal(1, 2, style = "upper")

    ## [1] "PHANTASMAGORIAL TRICHOPHOBIA RINGTAILEDLEMUR"

Sentence case

    ids::adjective_animal(1, 2, style = "sentence")

    ## [1] "Sorcerous imaginative goldfinch"

Title Case

    ids::adjective_animal(1, 2, style = "title")

    ## [1] "Starchy Omnivorous Nandine"

Again, pass `n = NULL` here to create a generating function:

    aa3 <- ids::adjective_animal(NULL, 3, style = "kebab", max_len = c(6, 8))

…which can be used to generate ids on demand.

    aa3()

    ## [1] "former-dry-yester-noctule"

    aa3(4)

    ## [1] "curt-murky-harsh-blobfish"  "catty-wintry-chuffy-isopod"
    ## [3] "jaded-rustic-adored-nymph"  "upper-freaky-rival-yucker"

## Random sentences

The `sentence` function creates a sentence style identifier. This uses the approach described by Asana on their blog. This approach encodes 32 bits of information (so 2^32 ~= 4 billion possibilities) and in theory can be remapped to an integer if you really wanted to.

    ids::sentence()

    ## [1] "17_flippant_chipmunks_striding_jubilantly"

As with `adjective_animal`, the case can be changed:

    ids::sentence(2, "dot")

    ## [1] "18.colossal.moles.bursting.unabashedly"
    ## [2] "8.groovy.beavers.slurping.obnoxiously"

If you would rather past tense for the verbs, then pass `past = TRUE`:

    ids::sentence(4, past = TRUE)

    ## [1] "19_jolly_porcupines_clamored_gently"
    ## [2] "18_groovy_impalas_twisted_jubilantly"
    ## [3] "33_cool_chipmunks_skipped_loftily"
    ## [4] "18_cuddly_pumas_sang_courageously"

## proquints

“proquints” are an identifier that tries to be information dense but still human readable and (somewhat) pronounceable; “proquint” stands for PRO-nouncable QUINT-uplets. They are introduced in https://arxiv.org/html/0901.4016

`ids` can generate proquints:

    ids::proquint(10)

    ##  [1] "mivij-dataj" "hisir-ginug" "hogom-vihoh" "lamus-sivot" "vajub-kolaf"
    ##  [6] "dadij-jilof" "rojak-jinot" "pajof-tisuf" "tosor-kibub" "kajom-vihur"

By default it generates two-word proquints but that can be changed:

    ids::proquint(5, 1)

    ## [1] "pigud" "rukul" "noruj" "visub" "hosud"

    ids::proquint(2, 4)

    ## [1] "gaguk-varov-magip-vafak" "gadov-samig-rojum-zakil"

Proquints are formed by alternating consonant/vowel/consonant/vowel/consonant using a subset of both (16 consonants and 4 vowels). This yields 2^16 (65,536) possibilities per word. Words are always lower case and always separated by a hyphen. So with 4 words there are 2^64 combinations in 23 characters.

Proquints are also useful in that they can be tranlated with integers. The proquint `kapop` has integer value 25258

    ids::proquint_to_int("kapop")

    ## [1] 25258

    ids::int_to_proquint(25258)

    ## [1] "kapop"

This makes proquints suitable for creating human-pronouncable identifers out of things like ip addresses, integer primary keys, etc.

The function `ids::int_to_proquint_word` will translate between proquint words and integers (and are vectorised)

    w <- ids::int_to_proquint_word(sample(2^16, 10) - 1L)
    w

    ##  [1] "mubuf" "rimuh" "kavav" "dolif" "vujiz" "hofab" "nisos" "dubuz"
    ##  [9] "tisoh" "jajog"

and `ids::proquint_word_to_int` does the reverse

    ids::proquint_word_to_int(w)

    ##  [1] 35890 46644 25486  6610 60767 18560 38700  7231 55076 20835

whille `ids::proquint_to_int` and `ids::int_to_proquint` allows translation of multi-word proquints. Overflow is a real possibility; the maximum integer representable is only about `r human_no(.Machine$integer.max)` and the maximum floating point number of accuracy of 1 is about 9010 trillion – these are big numbers but fairly small proquints:

    ids::int_to_proquint(.Machine$integer.max - 1)

    ## [1] "luzuz-zuzuv"

    ids::int_to_proquint(2 / .Machine$double.eps)

    ## [1] "babob-babab-babab-babab"

But if you had a 6 word proquint this would not work!

    p <- ids::proquint(1, 6)

Too big for an integer:

    ids::proquint_to_int(p)

    ## Error in proquint_combine(idx, len, as): Numeric overflow: cannot represent proquint as numeric

And too big for an numeric number:

    ids::proquint_to_int(p, as = "numeric")

    ## Error in proquint_combine(idx, len, as): Numeric overflow: cannot represent proquint as numeric

To allow this, we use `openssl`’s `bignum` support:

    ids::proquint_to_int(p, as = "bignum")

    ## [[1]]
    ## [b] 62023053643412691785669488225

This returns a list with one bignum (this is required to allow vectorisation).

## Roll your own identifiers

The `ids` functions can build identifiers in the style of `adjective_animal` or `sentence`. It takes as input a list of strings. This works particularly well with the `rcorpora` package which includes lists of strings.

Here is a list of Pokemon names:

    pokemon <- tolower(rcorpora::corpora("games/pokemon")$pokemon$name)
    length(pokemon)

    ## [1] 663

…and here is a list of adjectives

    adjectives <- tolower(rcorpora::corpora("words/adjs")$adjs)
    length(adjectives)

    ## [1] 962

So we have a total pool size of about 638 thousand, which is not huge, but it is at least topical.

To generate one identifier:

    ids::ids(1, adjectives, pokemon)

    ## [1] "long-suffering_beldum"

All the style-changing code is available:

    ids::ids(10, adjectives, pokemon, style = "dot")

    ##  [1] "canonical.deino"     "eaten.deino"         "remorseless.mantine"
    ##  [4] "veritable.togepi"    "blue-collar.weezing" "seated.heracross"
    ##  [7] "useless.barboach"    "spineless.cubchoo"   "fading.barboach"
    ## [10] "pitching.lanturn"

Better would be to wrap this so that the constants are not passed around the whole time:

    adjective_pokemon <- function(n = 1, style = "snake") {
      pokemon <- tolower(rcorpora::corpora("games/pokemon")$pokemon$name)
      adjectives <- tolower(rcorpora::corpora("words/adjs")$adjs)
      ids::ids(n, adjectives, pokemon, style = style)
    }

    adjective_pokemon(10, "kebab")

    ##  [1] "ancestral-gorebyss"    "hopeless-shroomish"
    ##  [3] "suspended-delcatty"    "fractional-pineco"
    ##  [5] "cardinal-rayquaza"     "goalless-eelektross"
    ##  [7] "peevish-onix"          "gypsy-taillow"
    ##  [9] "progressive-kabuto"    "progressive-shroomish"

As a second example we can use the word lists in rcorpora to generate identifiers in the form `<mood>_<scientist>`, like “melancholic_darwin”. These are similar to the names of docker containers.

First the lists of names themselves:

    moods <- tolower(rcorpora::corpora("humans/moods")$moods)
    scientists <- tolower(rcorpora::corpora("humans/scientists")$scientists)

Moods include:

    sample(moods, 10)

    ##  [1] "comfortable" "inquisitive" "vacant"      "satiric"     "unknown"
    ##  [6] "insulted"    "noticed"     "involved"    "censored"    "distant"

The scientists names contain spaces which is not going to work for us because `ids` won’t correctly translate all internal spaces to the requested style.

    sample(scientists, 10)

    ##  [1] "james dwight dana"
    ##  [2] "georges-louis leclerc, comte de buffon"
    ##  [3] "ukichiro nakaya"
    ##  [4] "jane marcet"
    ##  [5] "francis bacon"
    ##  [6] "eratosthenes"
    ##  [7] "pierre de fermat"
    ##  [8] "mary anning"
    ##  [9] "brahmagupta"
    ## [10] "alfred binet"

To hack around this we’ll just take the last name from the list and remove all hyphens:

    scientists <- vapply(strsplit(sub("(-|jr\\.$)", "", scientists), " "),
                         tail, character(1), 1)

Which gives strings that are just letters (though there are a few non-ASCII characters here that may cause problems because string handling is just a big pile of awful)

    sample(scientists, 10)

    ##  [1] "dirac"      "foucault"   "bosch"      "binet"      "archimedes"
    ##  [6] "cori"       "raman"      "mayr"       "lyell"      "hubble"

With the word lists, create an identifier:

    ids::ids(1, moods, scientists)

    ## [1] "deceived_pavlov"

Or pass `NULL` for `n` and create a function:

    sci_id <- ids::ids(NULL, moods, scientists, style = "kebab")

which takes just the number of identifiers to generate as an argument

    sci_id(10)

    ##  [1] "self-assured-bohm"      "aloof-fossey"
    ##  [3] "listless-skinner"       "thankful-hopkins"
    ##  [5] "gullible-hopkins"       "ashamed-watson"
    ##  [7] "complacent-curie"       "fine-leeuwenhoek"
    ##  [9] "content-sommerfeld"     "comfortable-brongniart"