spotify_id.rs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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] = 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 = std::num::Zero::zero();
  16. for c in data {
  17. let d = BASE16_DIGITS.position_elem(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 = std::num::Zero::zero();
  27. for c in data {
  28. let d = BASE62_DIGITS.position_elem(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_string()
  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. impl FileId {
  62. pub fn to_base16(&self) -> String {
  63. self.0.iter()
  64. .map(|b| format!("{:02x}", b))
  65. .collect::<Vec<String>>()
  66. .concat()
  67. }
  68. }