2023-03-31 03:58:28 +02:00
|
|
|
use napi::{bindgen_prelude::*, Error, Status};
|
|
|
|
use napi_derive::napi;
|
|
|
|
|
|
|
|
static CHAR_COLLECTION: &str = "0123456789abcdefghijklmnopqrstuvwxyz";
|
|
|
|
|
|
|
|
// -- NAPI exports --
|
|
|
|
|
|
|
|
#[napi]
|
|
|
|
pub enum IdConvertType {
|
2023-05-25 08:34:48 +02:00
|
|
|
MastodonId,
|
2023-07-03 00:18:30 +02:00
|
|
|
FirefishId,
|
2023-03-31 03:58:28 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
#[napi]
|
|
|
|
pub fn convert_id(in_id: String, id_convert_type: IdConvertType) -> napi::Result<String> {
|
2023-05-25 08:34:48 +02:00
|
|
|
use IdConvertType::*;
|
|
|
|
match id_convert_type {
|
|
|
|
MastodonId => {
|
2023-07-02 02:36:56 +02:00
|
|
|
let mut out: i128 = 0;
|
2023-05-25 08:34:48 +02:00
|
|
|
for (i, c) in in_id.to_lowercase().chars().rev().enumerate() {
|
2023-07-02 02:36:56 +02:00
|
|
|
out += num_from_char(c)? as i128 * 36_i128.pow(i as u32);
|
2023-05-25 08:34:48 +02:00
|
|
|
}
|
2023-03-31 03:58:28 +02:00
|
|
|
|
2023-05-25 08:34:48 +02:00
|
|
|
Ok(out.to_string())
|
2023-03-31 03:58:28 +02:00
|
|
|
}
|
2023-07-03 00:18:30 +02:00
|
|
|
FirefishId => {
|
2023-07-02 02:36:56 +02:00
|
|
|
let mut input: i128 = match in_id.parse() {
|
2023-05-25 08:34:48 +02:00
|
|
|
Ok(s) => s,
|
|
|
|
Err(_) => {
|
|
|
|
return Err(Error::new(
|
|
|
|
Status::InvalidArg,
|
2023-06-12 08:12:22 +02:00
|
|
|
"Unable to parse ID as MastodonId",
|
2023-05-25 08:34:48 +02:00
|
|
|
))
|
|
|
|
}
|
|
|
|
};
|
|
|
|
let mut out = String::new();
|
2023-03-31 03:58:28 +02:00
|
|
|
|
2023-05-25 08:34:48 +02:00
|
|
|
while input != 0 {
|
|
|
|
out.insert(0, char_from_num((input % 36) as u8)?);
|
|
|
|
input /= 36;
|
|
|
|
}
|
2023-03-31 03:58:28 +02:00
|
|
|
|
2023-05-25 08:34:48 +02:00
|
|
|
Ok(out)
|
|
|
|
}
|
2023-03-31 03:58:28 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// -- end --
|
|
|
|
|
|
|
|
#[inline(always)]
|
|
|
|
fn num_from_char(character: char) -> napi::Result<u8> {
|
2023-05-25 08:34:48 +02:00
|
|
|
for (i, c) in CHAR_COLLECTION.chars().enumerate() {
|
|
|
|
if c == character {
|
|
|
|
return Ok(i as u8);
|
|
|
|
}
|
2023-03-31 03:58:28 +02:00
|
|
|
}
|
|
|
|
|
2023-05-25 08:34:48 +02:00
|
|
|
Err(Error::new(
|
|
|
|
Status::InvalidArg,
|
|
|
|
"Invalid character in parsed base36 id",
|
|
|
|
))
|
2023-03-31 03:58:28 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
#[inline(always)]
|
|
|
|
fn char_from_num(number: u8) -> napi::Result<char> {
|
2023-05-25 08:34:48 +02:00
|
|
|
CHAR_COLLECTION
|
|
|
|
.chars()
|
|
|
|
.nth(number as usize)
|
|
|
|
.ok_or(Error::from_status(Status::Unknown))
|
2023-03-31 03:58:28 +02:00
|
|
|
}
|