1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
use std::{error, fmt, result, str};

use crate::{builder::HarshBuilder, shuffle};

type Result<T, E = Error> = result::Result<T, E>;

#[derive(Clone, Debug)]
pub enum Error {
    Hex,
    Decode(DecodeError),
}

#[derive(Clone, Debug)]
pub enum DecodeError {
    Value,
    Hash,
}

impl fmt::Display for DecodeError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            DecodeError::Value => f.write_str("Found bad value"),
            DecodeError::Hash => f.write_str("Malformed hashid"),
        }
    }
}

impl error::Error for DecodeError {}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Error::Hex => f.write_str("Failed to decode hex value"),
            Error::Decode(e) => match e {
                DecodeError::Value => f.write_str("Found bad value"),
                DecodeError::Hash => f.write_str("Malformed hashid"),
            },
        }
    }
}

impl error::Error for Error {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match self {
            Error::Hex => None,
            Error::Decode(ref e) => Some(e),
        }
    }
}

/// A hashids-compatible hasher.
///
/// It's probably not a great idea to use the default, because in that case
/// your values will be entirely trivial to decode. On the other hand, this is
/// not intended to be cryptographically-secure, so go nuts!
#[derive(Clone, Debug)]
pub struct Harsh {
    alphabet: Box<[u8]>,
    guards: Box<[u8]>,
    hash_length: usize,
    salt: Box<[u8]>,
    separators: Box<[u8]>,
}

impl Harsh {
    /// Create a default instance of Harsh.
    pub fn new() -> Self {
        HarshBuilder::new()
            .build()
            .expect("Default options should not fail")
    }

    /// Build a new instance of Harsh.
    pub fn builder() -> HarshBuilder {
        HarshBuilder::new()
    }

    pub(crate) fn initialize(
        alphabet: Box<[u8]>,
        guards: Box<[u8]>,
        hash_length: usize,
        salt: Box<[u8]>,
        separators: Box<[u8]>,
    ) -> Self {
        Harsh {
            alphabet,
            guards,
            hash_length,
            salt,
            separators,
        }
    }

    /// Encodes a slice of `u64` values into a single hashid.
    pub fn encode(&self, values: &[u64]) -> String {
        if values.is_empty() {
            return String::new();
        }

        let nhash = create_nhash(values);

        let mut alphabet = self.alphabet.clone();
        let mut buffer = String::new();

        let idx = (nhash % alphabet.len() as u64) as usize;
        let lottery = alphabet[idx];
        buffer.push(lottery as char);

        for (idx, &value) in values.iter().enumerate() {
            let mut value = value;
            let mut temp = Vec::with_capacity(self.salt.len() + alphabet.len() + 1);
            temp.push(lottery);
            temp.extend_from_slice(&self.salt);
            temp.extend_from_slice(&alphabet);

            let alphabet_len = alphabet.len();
            shuffle(&mut alphabet, &temp[..alphabet_len]);

            let last = hash(value, &alphabet);
            buffer.push_str(&last);

            if idx + 1 < values.len() {
                value %= (last.bytes().next().unwrap_or(0) as usize + idx) as u64;
                buffer
                    .push(self.separators[(value % self.separators.len() as u64) as usize] as char);
            }
        }

        if buffer.len() < self.hash_length {
            let guard_index = (nhash as usize
                + buffer.bytes().next().expect("hellfire and damnation") as usize)
                % self.guards.len();
            let guard = self.guards[guard_index];
            buffer.insert(0, guard as char);

            if buffer.len() < self.hash_length {
                let guard_index = (nhash as usize
                    + buffer.as_bytes()[2] as usize)
                    % self.guards.len();
                let guard = self.guards[guard_index];
                buffer.push(guard as char);
            }
        }

        let half_length = alphabet.len() / 2;
        while buffer.len() < self.hash_length {
            {
                let alphabet_copy = alphabet.clone();
                shuffle(&mut alphabet, &alphabet_copy);
            }

            let (left, right) = alphabet.split_at(half_length);
            buffer = format!(
                "{}{}{}",
                String::from_utf8_lossy(right),
                buffer,
                String::from_utf8_lossy(left)
            );

            let excess = buffer.len() as i32 - self.hash_length as i32;
            if excess > 0 {
                let marker = excess as usize / 2;
                buffer = buffer[marker..marker + self.hash_length].to_owned();
            }
        }

        buffer
    }

    /// Decodes a single hashid into a slice of `u64` values.
    pub fn decode<T: AsRef<str>>(&self, input: T) -> Result<Vec<u64>> {
        let mut value = input.as_ref().as_bytes();

        if let Some(guard_idx) = value.iter().position(|u| self.guards.contains(u)) {
            value = &value[(guard_idx + 1)..];
        }

        if let Some(guard_idx) = value.iter().rposition(|u| self.guards.contains(u)) {
            value = &value[..guard_idx];
        }

        if value.len() < 2 {
            return Err(Error::Decode(DecodeError::Hash));
        }

        let mut alphabet = self.alphabet.clone();

        let lottery = value[0];
        let value = &value[1..];
        let segments = value.split(|u| self.separators.contains(u));

        let result: Option<Vec<_>> = segments
            .into_iter()
            .map(|segment| {
                let mut buffer = Vec::with_capacity(self.salt.len() + alphabet.len() + 1);
                buffer.push(lottery);
                buffer.extend_from_slice(&self.salt);
                buffer.extend_from_slice(&alphabet);

                let alphabet_len = alphabet.len();
                shuffle(&mut alphabet, &buffer[..alphabet_len]);
                unhash(segment, &alphabet)
            })
            .collect();

        match result {
            None => Err(Error::Decode(DecodeError::Value)),
            Some(result) => {
                if self.encode(&result) == input.as_ref() {
                    Ok(result)
                } else {
                    Err(Error::Decode(DecodeError::Hash))
                }
            }
        }
    }

    /// Encodes a hex string into a hashid.
    pub fn encode_hex(&self, hex: &str) -> Result<String> {
        let values: Option<Vec<_>> = hex
            .as_bytes()
            .chunks(12)
            .map(|chunk| {
                str::from_utf8(chunk)
                    .ok()
                    .and_then(|s| u64::from_str_radix(&("1".to_owned() + s), 16).ok())
            })
            .collect();

        match values {
            Some(values) => Ok(self.encode(&values)),
            None => Err(Error::Hex),
        }
    }

    /// Decodes a hashid into a hex string.
    pub fn decode_hex(&self, value: &str) -> Result<String> {
        use std::fmt::Write;

        let values = self.decode(value)?;

        let mut result = String::new();
        let mut buffer = String::new();

        for n in values {
            write!(buffer, "{:x}", n).unwrap();
            result.push_str(&buffer[1..]);
            buffer.clear();
        }

        Ok(result)
    }
}

impl Default for Harsh {
    fn default() -> Self {
        Harsh::new()
    }
}

#[inline]
fn create_nhash(values: &[u64]) -> u64 {
    values
        .iter()
        .enumerate()
        .fold(0, |a, (idx, value)| a + (value % (idx + 100) as u64))
}

fn hash(mut value: u64, alphabet: &[u8]) -> String {
    let length = alphabet.len() as u64;
    let mut hash = Vec::new();

    loop {
        hash.push(alphabet[(value % length) as usize]);
        value /= length;

        if value == 0 {
            hash.reverse();
            return String::from_utf8(hash).expect("omg fml");
        }
    }
}

fn unhash(input: &[u8], alphabet: &[u8]) -> Option<u64> {
    input.iter().enumerate().fold(Some(0), |a, (idx, &value)| {
        let pos = alphabet.iter().position(|&item| item == value)? as u64;
        let b = (alphabet.len() as u64).checked_pow((input.len() - idx - 1) as u32)?;
        let c = pos.checked_mul(b)?;
        a.map(|a| a + c)
    })
}

#[cfg(test)]
mod tests {
    use super::{Harsh, HarshBuilder};

    #[test]
    fn harsh_default_does_not_panic() {
        Harsh::default();
    }

    #[test]
    fn can_encode() {
        let harsh = HarshBuilder::new()
            .salt("this is my salt")
            .build()
            .expect("failed to initialize harsh");

        assert_eq!(
            "4o6Z7KqxE",
            harsh.encode(&[1226198605112]),
            "error encoding [1226198605112]"
        );
        assert_eq!("laHquq", harsh.encode(&[1, 2, 3]));
    }

    #[test]
    fn can_encode_with_guards() {
        let harsh = HarshBuilder::new()
            .salt("this is my salt")
            .length(8)
            .build()
            .expect("failed to initialize harsh");

        assert_eq!("GlaHquq0", harsh.encode(&[1, 2, 3]));
    }

    #[test]
    fn can_encode_with_padding() {
        let harsh = HarshBuilder::new()
            .salt("this is my salt")
            .length(12)
            .build()
            .expect("failed to initialize harsh");

        assert_eq!("9LGlaHquq06D", harsh.encode(&[1, 2, 3]));
    }

    #[test]
    fn can_decode() {
        let harsh = HarshBuilder::new()
            .salt("this is my salt")
            .build()
            .expect("failed to initialize harsh");

        assert_eq!(
            &[1226198605112],
            &harsh.decode("4o6Z7KqxE").expect("failed to decode")[..],
            "error decoding \"4o6Z7KqxE\""
        );
        assert_eq!(
            &[1u64, 2, 3],
            &harsh.decode("laHquq").expect("failed to decode")[..]
        );
    }

    #[test]
    fn can_decode_with_guards() {
        let harsh = HarshBuilder::new()
            .salt("this is my salt")
            .length(8)
            .build()
            .expect("failed to initialize harsh");

        assert_eq!(
            &[1u64, 2, 3],
            &harsh.decode("GlaHquq0").expect("failed to decode")[..]
        );
    }

    #[test]
    fn can_decode_with_padding() {
        let harsh = HarshBuilder::new()
            .salt("this is my salt")
            .length(12)
            .build()
            .expect("failed to initialize harsh");

        assert_eq!(
            &[1u64, 2, 3],
            &harsh.decode("9LGlaHquq06D").expect("failed to decode")[..]
        );
    }

    #[test]
    fn can_encode_hex() {
        let harsh = HarshBuilder::new()
            .salt("this is my salt")
            .build()
            .expect("failed to initialize harsh");

        assert_eq!(
            "lzY",
            &harsh.encode_hex("FA").expect("Failed to encode"),
            "error encoding `FA`"
        );
        assert_eq!(
            "MemE",
            &harsh.encode_hex("26dd").expect("Failed to encode"),
            "error encoding `26dd`"
        );
        assert_eq!(
            "eBMrb",
            &harsh.encode_hex("FF1A").expect("Failed to encode"),
            "error encoding `FF1A`"
        );
        assert_eq!(
            "D9NPE",
            &harsh.encode_hex("12abC").expect("Failed to encode"),
            "error encoding `12abC`"
        );
        assert_eq!(
            "9OyNW",
            &harsh.encode_hex("185b0").expect("Failed to encode"),
            "error encoding `185b0`"
        );
        assert_eq!(
            "MRWNE",
            &harsh.encode_hex("17b8d").expect("Failed to encode"),
            "error encoding `17b8d`"
        );
        assert_eq!(
            "4o6Z7KqxE",
            &harsh.encode_hex("1d7f21dd38").expect("Failed to encode"),
            "error encoding `1d7f21dd38`"
        );
        assert_eq!(
            "ooweQVNB",
            &harsh.encode_hex("20015111d").expect("Failed to encode"),
            "error encoding `20015111d`"
        );
        assert_eq!(
            "kRNrpKlJ",
            &harsh.encode_hex("deadbeef").expect("Failed to encode"),
            "error encoding `deadbeef`"
        );

        let harsh = HarshBuilder::new().build().unwrap();
        assert_eq!(
            "y42LW46J9luq3Xq9XMly",
            &harsh
                .encode_hex("507f1f77bcf86cd799439011",)
                .expect("failed to encode",),
            "error encoding `507f1f77bcf86cd799439011`"
        );
    }

    #[test]
    fn can_encode_hex_with_guards() {
        let harsh = HarshBuilder::new()
            .salt("this is my salt")
            .length(10)
            .build()
            .expect("failed to initialize harsh");

        assert_eq!(
            "GkRNrpKlJd",
            &harsh.encode_hex("deadbeef").expect("Failed to encode"),
        );
    }

    #[test]
    fn can_encode_hex_with_padding() {
        let harsh = HarshBuilder::new()
            .salt("this is my salt")
            .length(12)
            .build()
            .expect("failed to initialize harsh");

        assert_eq!(
            "RGkRNrpKlJde",
            &harsh.encode_hex("deadbeef").expect("Failed to encode"),
        );
    }

    #[test]
    fn can_decode_hex() {
        let harsh = HarshBuilder::new()
            .salt("this is my salt")
            .build()
            .expect("failed to initialize harsh");

        assert_eq!(
            "fa",
            harsh.decode_hex("lzY").expect("failed to decode"),
            "error decoding `FA`"
        );
        assert_eq!(
            "26dd",
            harsh.decode_hex("MemE").expect("failed to decode"),
            "error decoding `26dd`"
        );
        assert_eq!(
            "ff1a",
            harsh.decode_hex("eBMrb").expect("failed to decode"),
            "error decoding `FF1A`"
        );
        assert_eq!(
            "12abc",
            harsh.decode_hex("D9NPE").expect("failed to decode"),
            "error decoding `12abC`"
        );
        assert_eq!(
            "185b0",
            harsh.decode_hex("9OyNW").expect("failed to decode"),
            "error decoding `185b0`"
        );
        assert_eq!(
            "17b8d",
            harsh.decode_hex("MRWNE").expect("failed to decode"),
            "error decoding `17b8d`"
        );
        assert_eq!(
            "1d7f21dd38",
            harsh.decode_hex("4o6Z7KqxE").expect("failed to decode"),
            "error decoding `1d7f21dd38`"
        );
        assert_eq!(
            "20015111d",
            harsh.decode_hex("ooweQVNB").expect("failed to decode"),
            "error decoding `20015111d`"
        );
        assert_eq!(
            "deadbeef",
            harsh.decode_hex("kRNrpKlJ").expect("failed to decode"),
            "error decoding `deadbeef`"
        );

        let harsh = HarshBuilder::new().build().unwrap();
        assert_eq!(
            "507f1f77bcf86cd799439011",
            harsh
                .decode_hex("y42LW46J9luq3Xq9XMly",)
                .expect("failed to decode",),
            "error decoding `y42LW46J9luq3Xq9XMly`"
        );
    }

    #[test]
    fn can_decode_hex_with_guards() {
        let harsh = HarshBuilder::new()
            .salt("this is my salt")
            .length(10)
            .build()
            .expect("failed to initialize harsh");

        assert_eq!(
            "deadbeef",
            harsh.decode_hex("GkRNrpKlJd").expect("failed to decode"),
            "failed to decode GkRNrpKlJd"
        );
    }

    #[test]
    fn can_decode_hex_with_padding() {
        let harsh = HarshBuilder::new()
            .salt("this is my salt")
            .length(12)
            .build()
            .expect("failed to initialize harsh");

        assert_eq!(
            "deadbeef",
            harsh.decode_hex("RGkRNrpKlJde").expect("failed to decode"),
            "failed to decode RGkRNrpKlJde"
        );
    }

    #[test]
    fn can_encode_with_custom_alphabet() {
        let harsh = HarshBuilder::new()
            .alphabet("abcdefghijklmnopqrstuvwxyz")
            .build()
            .expect("failed to initialize harsh");

        assert_eq!(
            "mdfphx",
            harsh.encode(&[1, 2, 3]),
            "failed to encode [1, 2, 3]"
        );
    }

    #[test]
    #[should_panic]
    fn can_decode_with_invalid_alphabet() {
        let harsh = Harsh::default();
        harsh.decode("this$ain't|a\number").unwrap();
    }

    #[test]
    fn can_decode_with_custom_alphabet() {
        let harsh = HarshBuilder::new()
            .alphabet("abcdefghijklmnopqrstuvwxyz")
            .build()
            .expect("failed to initialize harsh");

        assert_eq!(
            &[1, 2, 3],
            &harsh.decode("mdfphx").expect("failed to decode")[..],
            "failed to decode mdfphx"
        );
    }

    #[test]
    fn create_nhash() {
        let values = &[1, 2, 3];
        let nhash = super::create_nhash(values);
        assert_eq!(6, nhash);
    }

    #[test]
    fn hash() {
        let result = super::hash(22, b"abcdefghijklmnopqrstuvwxyz");
        assert_eq!("w", result);
    }

    #[test]
    fn shuffle() {
        let salt = b"1234";
        let mut values = "asdfzxcvqwer".bytes().collect::<Vec<_>>();
        super::shuffle(&mut values, salt);

        assert_eq!("vdwqfrzcsxae", String::from_utf8_lossy(&values));
    }

    #[test]
    fn guard_characters_should_be_added_to_left_first() {
        let harsh = HarshBuilder::new().length(3).build().unwrap();
        let hashed_value = harsh.encode(&[1]);

        assert_eq!(&hashed_value, "ejR");
        assert_eq!(vec![1], harsh.decode("ejR").unwrap());
    }

    #[test]
    #[should_panic]
    fn appended_garbage_data_invalidates_hashid() {
        let harsh = HarshBuilder::new().length(4).build().unwrap();
        let id = harsh.encode(&[1, 2]) + "12";
        harsh.decode(id).unwrap();
    }
}