spotify_id.rs 2.6 KB

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