spotify_id.rs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. use std;
  2. use util::u128;
  3. use byteorder::{BigEndian, ByteOrder};
  4. use std::ascii::AsciiExt;
  5. #[derive(Debug,Copy,Clone,PartialEq,Eq,Hash)]
  6. pub struct SpotifyId(u128);
  7. #[derive(Debug,Copy,Clone,PartialEq,Eq,Hash)]
  8. pub struct FileId(pub [u8; 20]);
  9. const BASE62_DIGITS: &'static [u8] =
  10. b"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  11. const BASE16_DIGITS: &'static [u8] = b"0123456789abcdef";
  12. impl SpotifyId {
  13. pub fn from_base16(id: &str) -> SpotifyId {
  14. assert!(id.is_ascii());
  15. let data = id.as_bytes();
  16. let mut n: u128 = std::num::Zero::zero();
  17. for c in data {
  18. let d = BASE16_DIGITS.iter().position(|e| e == c).unwrap() as u8;
  19. n = n * u128::from(16);
  20. n = n + u128::from(d);
  21. }
  22. SpotifyId(n)
  23. }
  24. pub fn from_base62(id: &str) -> SpotifyId {
  25. assert!(id.is_ascii());
  26. let data = id.as_bytes();
  27. let mut n: u128 = std::num::Zero::zero();
  28. for c in data {
  29. let d = BASE62_DIGITS.iter().position(|e| e == c).unwrap() as u8;
  30. n = n * u128::from(62);
  31. n = n + u128::from(d);
  32. }
  33. SpotifyId(n)
  34. }
  35. pub fn from_raw(data: &[u8]) -> SpotifyId {
  36. assert_eq!(data.len(), 16);
  37. let high = BigEndian::read_u64(&data[0..8]);
  38. let low = BigEndian::read_u64(&data[8..16]);
  39. SpotifyId(u128::from_parts(high, low))
  40. }
  41. pub fn to_base16(&self) -> String {
  42. let &SpotifyId(ref n) = self;
  43. let (high, low) = n.parts();
  44. let mut data = [0u8; 32];
  45. for i in 0..16 {
  46. data[31 - i] = BASE16_DIGITS[(low.wrapping_shr(4 * i as u32) & 0xF) as usize];
  47. }
  48. for i in 0..16 {
  49. data[15 - i] = BASE16_DIGITS[(high.wrapping_shr(4 * i as u32) & 0xF) as usize];
  50. }
  51. std::str::from_utf8(&data).unwrap().to_owned()
  52. }
  53. pub fn to_raw(&self) -> [u8; 16] {
  54. let &SpotifyId(ref n) = self;
  55. let (high, low) = n.parts();
  56. let mut data = [0u8; 16];
  57. BigEndian::write_u64(&mut data[0..8], high);
  58. BigEndian::write_u64(&mut data[8..16], low);
  59. data
  60. }
  61. }
  62. impl FileId {
  63. pub fn to_base16(&self) -> String {
  64. self.0
  65. .iter()
  66. .map(|b| format!("{:02x}", b))
  67. .collect::<Vec<String>>()
  68. .concat()
  69. }
  70. }