hippofish/packages/backend/native-utils/src/mastodon_api.rs

71 lines
1.7 KiB
Rust
Raw Normal View History

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,
}
#[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 => {
let mut out: i128 = 0;
2023-05-25 08:34:48 +02:00
for (i, c) in in_id.to_lowercase().chars().rev().enumerate() {
out += num_from_char(c)? as i128 * 36_i128.pow(i as u32);
2023-05-25 08:34:48 +02:00
}
2023-05-25 08:34:48 +02:00
Ok(out.to_string())
}
2023-07-03 00:18:30 +02:00
FirefishId => {
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-05-25 08:34:48 +02:00
while input != 0 {
out.insert(0, char_from_num((input % 36) as u8)?);
input /= 36;
}
2023-05-25 08:34:48 +02:00
Ok(out)
}
}
}
// -- 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-05-25 08:34:48 +02:00
Err(Error::new(
Status::InvalidArg,
"Invalid character in parsed base36 id",
))
}
#[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))
}