repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/config/mod.rs | src/config/mod.rs | pub mod enums;
pub mod structs;
pub mod impls; | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/config/impls.rs | src/config/impls.rs | pub mod configuration;
pub mod configuration_error; | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/config/impls/configuration.rs | src/config/impls/configuration.rs | use std::fs::File;
use std::io::Write;
use std::sync::Arc;
use std::thread::available_parallelism;
use regex::Regex;
use crate::common::structs::custom_error::CustomError;
use crate::config::enums::configuration_error::ConfigurationError;
use crate::config::structs::api_trackers_config::ApiTrackersConfig;
use crate::config::structs::configuration::Configuration;
use crate::config::structs::database_config::DatabaseConfig;
use crate::config::structs::database_structure_config::DatabaseStructureConfig;
use crate::config::structs::database_structure_config_blacklist::DatabaseStructureConfigBlacklist;
use crate::config::structs::database_structure_config_keys::DatabaseStructureConfigKeys;
use crate::config::structs::database_structure_config_torrents::DatabaseStructureConfigTorrents;
use crate::config::structs::database_structure_config_users::DatabaseStructureConfigUsers;
use crate::config::structs::database_structure_config_whitelist::DatabaseStructureConfigWhitelist;
use crate::config::structs::http_trackers_config::HttpTrackersConfig;
use crate::config::structs::sentry_config::SentryConfig;
use crate::config::structs::tracker_config::TrackerConfig;
use crate::config::structs::udp_trackers_config::UdpTrackersConfig;
use crate::database::enums::database_drivers::DatabaseDrivers;
use std::env;
impl Configuration {
#[tracing::instrument(level = "debug")]
pub fn init() -> Configuration {
Configuration {
log_level: String::from("info"),
log_console_interval: 60,
tracker_config: TrackerConfig {
api_key: String::from("MyApiKey"),
whitelist_enabled: false,
blacklist_enabled: false,
keys_enabled: false,
keys_cleanup_interval: 60,
users_enabled: false,
request_interval: 1800,
request_interval_minimum: 1800,
peers_timeout: 2700,
peers_cleanup_interval: 900,
peers_cleanup_threads: 256,
total_downloads: 0,
swagger: false,
prometheus_id: String::from("torrust_actix")
},
sentry_config: SentryConfig {
enabled: false,
dsn: "".to_string(),
debug: false,
sample_rate: 1.0,
max_breadcrumbs: 100,
attach_stacktrace: true,
send_default_pii: false,
traces_sample_rate: 1.0,
},
database: DatabaseConfig {
engine: DatabaseDrivers::sqlite3,
path: String::from("sqlite://data.db"),
persistent: false,
persistent_interval: 60,
insert_vacant: false,
remove_action: false,
update_completed: true,
update_peers: false,
},
database_structure: DatabaseStructureConfig {
torrents: DatabaseStructureConfigTorrents {
table_name: String::from("torrents"),
column_infohash: String::from("infohash"),
bin_type_infohash: true,
column_seeds: String::from("seeds"),
column_peers: String::from("peers"),
column_completed: String::from("completed")
},
whitelist: DatabaseStructureConfigWhitelist {
table_name: String::from("whitelist"),
column_infohash: String::from("infohash"),
bin_type_infohash: true,
},
blacklist: DatabaseStructureConfigBlacklist {
table_name: String::from("blacklist"),
column_infohash: String::from("infohash"),
bin_type_infohash: true,
},
keys: DatabaseStructureConfigKeys {
table_name: String::from("keys"),
column_hash: String::from("hash"),
bin_type_hash: true,
column_timeout: String::from("timeout")
},
users: DatabaseStructureConfigUsers {
table_name: String::from("users"),
id_uuid: true,
column_uuid: String::from("uuid"),
column_id: "id".to_string(),
column_active: String::from("active"),
column_key: String::from("key"),
bin_type_key: true,
column_uploaded: String::from("uploaded"),
column_downloaded: String::from("downloaded"),
column_completed: String::from("completed"),
column_updated: String::from("updated"),
}
},
http_server: vec!(
HttpTrackersConfig {
enabled: true,
bind_address: String::from("0.0.0.0:6969"),
real_ip: String::from("X-Real-IP"),
keep_alive: 60,
request_timeout: 15,
disconnect_timeout: 15,
max_connections: 25000,
threads: available_parallelism().unwrap().get() as u64,
ssl: false,
ssl_key: String::from(""),
ssl_cert: String::from(""),
tls_connection_rate: 256
}
),
udp_server: vec!(
UdpTrackersConfig {
enabled: true,
bind_address: String::from("0.0.0.0:6969"),
udp_threads: 4,
worker_threads: available_parallelism().unwrap().get(),
receive_buffer_size: 134217728,
send_buffer_size: 67108864,
reuse_address: true
}
),
api_server: vec!(
ApiTrackersConfig {
enabled: true,
bind_address: String::from("0.0.0.0:8080"),
real_ip: String::from("X-Real-IP"),
keep_alive: 60,
request_timeout: 30,
disconnect_timeout: 30,
max_connections: 25000,
threads: available_parallelism().unwrap().get() as u64,
ssl: false,
ssl_key: String::from(""),
ssl_cert: String::from(""),
tls_connection_rate: 256
}
)
}
}
#[tracing::instrument(level = "debug")]
pub fn env_overrides(config: &mut Configuration) -> &mut Configuration {
if let Ok(value) = env::var("LOG_LEVEL") { config.log_level = value; }
if let Ok(value) = env::var("LOG_CONSOLE_INTERVAL") { config.log_console_interval = value.parse::<u64>().unwrap_or(60u64); }
// Tracker config
if let Ok(value) = env::var("TRACKER__API_KEY") {
config.tracker_config.api_key = value
}
if let Ok(value) = env::var("TRACKER__WHITELIST_ENABLED") {
config.tracker_config.whitelist_enabled = match value.as_str() { "true" => { true } "false" => { false } _ => { false } };
}
if let Ok(value) = env::var("TRACKER__BLACKLIST_ENABLED") {
config.tracker_config.blacklist_enabled = match value.as_str() { "true" => { true } "false" => { false } _ => { false } };
}
if let Ok(value) = env::var("TRACKER__KEYS_ENABLED") {
config.tracker_config.keys_enabled = match value.as_str() { "true" => { true } "false" => { false } _ => { false } };
}
if let Ok(value) = env::var("TRACKER__USERS_ENABLED") {
config.tracker_config.users_enabled = match value.as_str() { "true" => { true } "false" => { false } _ => { false } };
}
if let Ok(value) = env::var("TRACKER__SWAGGER") {
config.tracker_config.swagger = match value.as_str() { "true" => { true } "false" => { false } _ => { false } };
}
if let Ok(value) = env::var("TRACKER__KEYS_CLEANUP_INTERVAL") {
config.tracker_config.keys_cleanup_interval = value.parse::<u64>().unwrap_or(60u64);
}
if let Ok(value) = env::var("TRACKER__REQUEST_INTERVAL") {
config.tracker_config.request_interval = value.parse::<u64>().unwrap_or(1800u64);
}
if let Ok(value) = env::var("TRACKER__REQUEST_INTERVAL_MINIMUM") {
config.tracker_config.request_interval_minimum = value.parse::<u64>().unwrap_or(1800u64);
}
if let Ok(value) = env::var("TRACKER__PEERS_TIMEOUT") {
config.tracker_config.peers_timeout = value.parse::<u64>().unwrap_or(2700u64);
}
if let Ok(value) = env::var("TRACKER__PEERS_CLEANUP_INTERVAL") {
config.tracker_config.peers_cleanup_interval = value.parse::<u64>().unwrap_or(900u64);
}
if let Ok(value) = env::var("TRACKER__PEERS_CLEANUP_THREADS") {
config.tracker_config.peers_cleanup_threads = value.parse::<u64>().unwrap_or(256u64);
}
if let Ok(value) = env::var("TRACKER__PROMETHEUS_ID") {
config.tracker_config.prometheus_id = value;
}
// Sentry config
if let Ok(value) = env::var("SENTRY__ENABLED") {
config.sentry_config.enabled = match value.as_str() { "true" => { true } "false" => { false } _ => { false } };
}
if let Ok(value) = env::var("SENTRY__DEBUG") {
config.sentry_config.debug = match value.as_str() { "true" => { true } "false" => { false } _ => { false } };
}
if let Ok(value) = env::var("SENTRY__ATTACH_STACKTRACE") {
config.sentry_config.attach_stacktrace = match value.as_str() { "true" => { true } "false" => { false } _ => { true } };
}
if let Ok(value) = env::var("SENTRY__SEND_DEFAULT_PII") {
config.sentry_config.send_default_pii = match value.as_str() { "true" => { true } "false" => { false } _ => { false } };
}
if let Ok(value) = env::var("SENTRY__DSN") {
config.sentry_config.dsn = value;
}
if let Ok(value) = env::var("SENTRY__MAX_BREADCRUMBS") {
config.sentry_config.max_breadcrumbs = value.parse::<usize>().unwrap_or(100);
}
if let Ok(value) = env::var("SENTRY__SAMPLE_RATE") {
config.sentry_config.sample_rate = value.parse::<f32>().unwrap_or(1.0);
}
if let Ok(value) = env::var("SENTRY__TRACES_SAMPLE_RATE") {
config.sentry_config.traces_sample_rate = value.parse::<f32>().unwrap_or(1.0);
}
// Database config
if let Ok(value) = env::var("DATABASE__PERSISTENT") {
config.database.persistent = match value.as_str() { "true" => { true } "false" => { false } _ => { false } };
}
if let Ok(value) = env::var("DATABASE__INSERT_VACANT") {
config.database.insert_vacant = match value.as_str() { "true" => { true } "false" => { false } _ => { false } };
}
if let Ok(value) = env::var("DATABASE__REMOVE_ACTION") {
config.database.remove_action = match value.as_str() { "true" => { true } "false" => { false } _ => { false } };
}
if let Ok(value) = env::var("DATABASE__UPDATE_COMPLETED") {
config.database.update_completed = match value.as_str() { "true" => { true } "false" => { false } _ => { true } };
}
if let Ok(value) = env::var("DATABASE__UPDATE_PEERS") {
config.database.update_peers = match value.as_str() { "true" => { true } "false" => { false } _ => { false } };
}
if let Ok(value) = env::var("DATABASE__PATH") {
config.database.path = value;
}
if let Ok(value) = env::var("DATABASE__ENGINE") {
config.database.engine = match value.as_str() {
"sqlite3" => { DatabaseDrivers::sqlite3 }
"mysql" => { DatabaseDrivers::mysql }
"pgsql" => { DatabaseDrivers::pgsql }
_ => { DatabaseDrivers::sqlite3 }
};
}
if let Ok(value) = env::var("DATABASE__PERSISTENT_INTERVAL") {
config.database.persistent_interval = value.parse::<u64>().unwrap_or(60u64);
}
// Database Structure Torrents config
if let Ok(value) = env::var("DATABASE_STRUCTURE__TORRENTS__BIN_TYPE_INFOHASH") {
config.database_structure.torrents.bin_type_infohash = match value.as_str() { "true" => { true } "false" => { false } _ => { true } };
}
if let Ok(value) = env::var("DATABASE_STRUCTURE__TORRENTS__TABLE_NAME") {
config.database_structure.torrents.table_name = value;
}
if let Ok(value) = env::var("DATABASE_STRUCTURE__TORRENTS__COLUMN_INFOHASH") {
config.database_structure.torrents.column_infohash = value;
}
if let Ok(value) = env::var("DATABASE_STRUCTURE__TORRENTS__COLUMN_SEEDS") {
config.database_structure.torrents.column_seeds = value;
}
if let Ok(value) = env::var("DATABASE_STRUCTURE__TORRENTS__COLUMN_PEERS") {
config.database_structure.torrents.column_peers = value;
}
if let Ok(value) = env::var("DATABASE_STRUCTURE__TORRENTS__COLUMN_COMPLETED") {
config.database_structure.torrents.column_completed = value;
}
// Database Structure Whitelist config
if let Ok(value) = env::var("DATABASE_STRUCTURE__WHITELIST__BIN_TYPE_INFOHASH") {
config.database_structure.whitelist.bin_type_infohash = match value.as_str() { "true" => { true } "false" => { false } _ => { true } };
}
if let Ok(value) = env::var("DATABASE_STRUCTURE__WHITELIST__TABLE_NAME") {
config.database_structure.whitelist.table_name = value;
}
if let Ok(value) = env::var("DATABASE_STRUCTURE__WHITELIST__COLUMN_INFOHASH") {
config.database_structure.whitelist.column_infohash = value;
}
// Database Structure Blacklist config
if let Ok(value) = env::var("DATABASE_STRUCTURE__BLACKLIST__BIN_TYPE_INFOHASH") {
config.database_structure.blacklist.bin_type_infohash = match value.as_str() { "true" => { true } "false" => { false } _ => { true } };
}
if let Ok(value) = env::var("DATABASE_STRUCTURE__BLACKLIST__TABLE_NAME") {
config.database_structure.blacklist.table_name = value;
}
if let Ok(value) = env::var("DATABASE_STRUCTURE__BLACKLIST__COLUMN_INFOHASH") {
config.database_structure.blacklist.column_infohash = value;
}
// Database Structure Keys config
if let Ok(value) = env::var("DATABASE_STRUCTURE__KEYS__BIN_TYPE_HASH") {
config.database_structure.keys.bin_type_hash = match value.as_str() { "true" => { true } "false" => { false } _ => { true } };
}
if let Ok(value) = env::var("DATABASE_STRUCTURE__KEYS__TABLE_NAME") {
config.database_structure.keys.table_name = value;
}
if let Ok(value) = env::var("DATABASE_STRUCTURE__KEYS__COLUMN_HASH") {
config.database_structure.keys.column_hash = value;
}
if let Ok(value) = env::var("DATABASE_STRUCTURE__KEYS__COLUMN_TIMEOUT") {
config.database_structure.keys.column_timeout = value;
}
// Database Structure Users config
if let Ok(value) = env::var("DATABASE_STRUCTURE__USERS__ID_UUID") {
config.database_structure.users.id_uuid = match value.as_str() { "true" => { true } "false" => { false } _ => { true } };
}
if let Ok(value) = env::var("DATABASE_STRUCTURE__USERS__BIN_TYPE_KEY") {
config.database_structure.users.bin_type_key = match value.as_str() { "true" => { true } "false" => { false } _ => { true } };
}
if let Ok(value) = env::var("DATABASE_STRUCTURE__USERS__TABLE_NAME") {
config.database_structure.users.table_name = value;
}
if let Ok(value) = env::var("DATABASE_STRUCTURE__USERS__COLUMN_UUID") {
config.database_structure.users.column_uuid = value;
}
if let Ok(value) = env::var("DATABASE_STRUCTURE__USERS__COLUMN_ID") {
config.database_structure.users.column_id = value;
}
if let Ok(value) = env::var("DATABASE_STRUCTURE__USERS__COLUMN_ACTIVE") {
config.database_structure.users.column_active = value;
}
if let Ok(value) = env::var("DATABASE_STRUCTURE__USERS__COLUMN_KEY") {
config.database_structure.users.column_key = value;
}
if let Ok(value) = env::var("DATABASE_STRUCTURE__USERS__COLUMN_UPLOADED") {
config.database_structure.users.column_uploaded = value;
}
if let Ok(value) = env::var("DATABASE_STRUCTURE__USERS__COLUMN_DOWNLOADED") {
config.database_structure.users.column_downloaded = value;
}
if let Ok(value) = env::var("DATABASE_STRUCTURE__USERS__COLUMN_COMPLETED") {
config.database_structure.users.column_completed = value;
}
if let Ok(value) = env::var("DATABASE_STRUCTURE__USERS__COLUMN_UPDATED") {
config.database_structure.users.column_updated = value;
}
// Possible overrides for the API stack
let mut api_iteration = 0;
loop {
match config.api_server.get_mut(api_iteration) {
None => {
break;
}
Some(block) => {
if let Ok(value) = env::var(format!("API_{api_iteration}_ENABLED")) {
block.enabled = match value.as_str() { "true" => { true } "false" => { false } _ => { true } };
}
if let Ok(value) = env::var(format!("API_{api_iteration}_SSL")) {
block.ssl = match value.as_str() { "true" => { true } "false" => { false } _ => { false } };
}
if let Ok(value) = env::var(format!("API_{api_iteration}_BIND_ADDRESS")) {
block.bind_address = value;
}
if let Ok(value) = env::var(format!("API_{api_iteration}_REAL_IP")) {
block.real_ip = value;
}
if let Ok(value) = env::var(format!("API_{api_iteration}_SSL_KEY")) {
block.ssl_key = value;
}
if let Ok(value) = env::var(format!("API_{api_iteration}_SSL_CERT")) {
block.ssl_cert = value;
}
if let Ok(value) = env::var(format!("API_{api_iteration}_KEEP_ALIVE")) {
block.keep_alive = value.parse::<u64>().unwrap_or(60);
}
if let Ok(value) = env::var(format!("API_{api_iteration}_REQUEST_TIMEOUT")) {
block.request_timeout = value.parse::<u64>().unwrap_or(30);
}
if let Ok(value) = env::var(format!("API_{api_iteration}_DISCONNECT_TIMEOUT")) {
block.disconnect_timeout = value.parse::<u64>().unwrap_or(30);
}
if let Ok(value) = env::var(format!("API_{api_iteration}_MAX_CONNECTIONS")) {
block.max_connections = value.parse::<u64>().unwrap_or(25000);
}
if let Ok(value) = env::var(format!("API_{api_iteration}_THREADS")) {
block.threads = value.parse::<u64>().unwrap_or(available_parallelism().unwrap().get() as u64);
}
if let Ok(value) = env::var(format!("API_{api_iteration}_TLS_CONNECTION_RATE")) {
block.tls_connection_rate = value.parse::<u64>().unwrap_or(256);
}
}
}
api_iteration += 1;
}
// Possible overrides for the HTTP stack
let mut http_iteration = 0;
loop {
match config.http_server.get_mut(http_iteration) {
None => {
break;
}
Some(block) => {
if let Ok(value) = env::var(format!("HTTP_{http_iteration}_ENABLED")) {
block.enabled = match value.as_str() { "true" => { true } "false" => { false } _ => { true } };
}
if let Ok(value) = env::var(format!("HTTP_{http_iteration}_SSL")) {
block.ssl = match value.as_str() { "true" => { true } "false" => { false } _ => { false } };
}
if let Ok(value) = env::var(format!("HTTP_{http_iteration}_BIND_ADDRESS")) {
block.bind_address = value;
}
if let Ok(value) = env::var(format!("HTTP_{http_iteration}_REAL_IP")) {
block.real_ip = value;
}
if let Ok(value) = env::var(format!("HTTP_{http_iteration}_SSL_KEY")) {
block.ssl_key = value;
}
if let Ok(value) = env::var(format!("HTTP_{http_iteration}_SSL_CERT")) {
block.ssl_cert = value;
}
if let Ok(value) = env::var(format!("HTTP_{http_iteration}_KEEP_ALIVE")) {
block.keep_alive = value.parse::<u64>().unwrap_or(60);
}
if let Ok(value) = env::var(format!("HTTP_{http_iteration}_REQUEST_TIMEOUT")) {
block.request_timeout = value.parse::<u64>().unwrap_or(30);
}
if let Ok(value) = env::var(format!("HTTP_{http_iteration}_DISCONNECT_TIMEOUT")) {
block.disconnect_timeout = value.parse::<u64>().unwrap_or(30);
}
if let Ok(value) = env::var(format!("HTTP_{http_iteration}_MAX_CONNECTIONS")) {
block.max_connections = value.parse::<u64>().unwrap_or(25000);
}
if let Ok(value) = env::var(format!("HTTP_{http_iteration}_THREADS")) {
block.threads = value.parse::<u64>().unwrap_or(available_parallelism().unwrap().get() as u64);
}
if let Ok(value) = env::var(format!("HTTP_{http_iteration}_TLS_CONNECTION_RATE")) {
block.tls_connection_rate = value.parse::<u64>().unwrap_or(256);
}
}
}
http_iteration += 1;
}
// Possible overrides for the UDP stack
let mut udp_iteration = 0;
loop {
match config.udp_server.get_mut(udp_iteration) {
None => {
break;
}
Some(block) => {
if let Ok(value) = env::var(format!("UDP_{udp_iteration}_ENABLED")) {
block.enabled = match value.as_str() { "true" => { true } "false" => { false } _ => { true } };
}
if let Ok(value) = env::var(format!("UDP_{udp_iteration}_BIND_ADDRESS")) {
block.bind_address = value;
}
if let Ok(value) = env::var(format!("UDP_{udp_iteration}_UDP_THREADS")) {
block.udp_threads = value.parse::<usize>().unwrap_or(2);
}
if let Ok(value) = env::var(format!("UDP_{udp_iteration}_WORKER_THREADS")) {
block.worker_threads = value.parse::<usize>().unwrap_or(available_parallelism().unwrap().get());
}
if let Ok(value) = env::var(format!("UDP_{udp_iteration}_RECEIVE_BUFFER_SIZE")) {
block.receive_buffer_size = value.parse::<usize>().unwrap_or(134217728);
}
if let Ok(value) = env::var(format!("UDP_{udp_iteration}_SEND_BUFFER_SIZE")) {
block.send_buffer_size = value.parse::<usize>().unwrap_or(67108864);
}
if let Ok(value) = env::var(format!("UDP_{udp_iteration}_REUSE_ADDRESS")) {
block.reuse_address = match value.as_str() { "true" => { true } "false" => { false } _ => { true } };
}
}
}
udp_iteration += 1;
}
config
}
#[tracing::instrument(level = "debug")]
pub fn load(data: &[u8]) -> Result<Configuration, toml::de::Error> {
toml::from_str(&String::from_utf8_lossy(data))
}
#[tracing::instrument(level = "debug")]
pub fn load_file(path: &str) -> Result<Configuration, ConfigurationError> {
match std::fs::read(path) {
Err(e) => Err(ConfigurationError::IOError(e)),
Ok(data) => {
match Self::load(data.as_slice()) {
Ok(cfg) => {
Ok(cfg)
}
Err(e) => Err(ConfigurationError::ParseError(e)),
}
}
}
}
#[tracing::instrument(level = "debug")]
pub fn save_file(path: &str, data: String) -> Result<(), ConfigurationError> {
match File::create(path) {
Ok(mut file) => {
match file.write_all(data.as_ref()) {
Ok(_) => Ok(()),
Err(e) => Err(ConfigurationError::IOError(e))
}
}
Err(e) => Err(ConfigurationError::IOError(e))
}
}
#[tracing::instrument(level = "debug")]
pub fn save_from_config(config: Arc<Configuration>, path: &str)
{
let config_toml = toml::to_string(&config).unwrap();
match Self::save_file(path, config_toml) {
Ok(_) => { eprintln!("[CONFIG SAVE] Config file is saved"); }
Err(_) => { eprintln!("[CONFIG SAVE] Unable to save to {path}"); }
}
}
#[tracing::instrument(level = "debug")]
pub fn load_from_file(create: bool) -> Result<Configuration, CustomError> {
let mut config = Configuration::init();
match Configuration::load_file("config.toml") {
Ok(c) => { config = c; }
Err(error) => {
eprintln!("No config file found or corrupt.");
eprintln!("[ERROR] {error}");
if !create {
eprintln!("You can either create your own config.toml file, or start this app using '--create-config' as parameter.");
return Err(CustomError::new("will not create automatically config.toml file"));
}
eprintln!("Creating config file..");
let config_toml = toml::to_string(&config).unwrap();
let save_file = Configuration::save_file("config.toml", config_toml);
return match save_file {
Ok(_) => {
eprintln!("Please edit the config.TOML in the root folder, exiting now...");
Err(CustomError::new("create config.toml file"))
}
Err(e) => {
eprintln!("config.toml file could not be created, check permissions...");
eprintln!("{e}");
Err(CustomError::new("could not create config.toml file"))
}
};
}
};
Self::env_overrides(&mut config);
println!("[VALIDATE] Validating configuration...");
Self::validate(config.clone());
Ok(config)
}
#[tracing::instrument(level = "debug")]
pub fn validate(config: Configuration) {
// Check Map
let check_map = vec![
("[TRACKER_CONFIG] prometheus_id", config.tracker_config.clone().prometheus_id, r"^[a-zA-Z0-9_]+$".to_string()),
("[DB: torrents]", config.database_structure.clone().torrents.table_name, r"^[a-z_][a-z0-9_]{0,30}$".to_string()),
("[DB: torrents] Column: infohash", config.database_structure.clone().torrents.column_infohash, r"^[a-z_][a-z0-9_]{0,30}$".to_string()),
("[DB: torrents] Column: seeds", config.database_structure.clone().torrents.column_seeds, r"^[a-z_][a-z0-9_]{0,30}$".to_string()),
("[DB: torrents] Column: peers", config.database_structure.clone().torrents.column_peers, r"^[a-z_][a-z0-9_]{0,30}$".to_string()),
("[DB: torrents] Column: completed", config.database_structure.clone().torrents.column_completed, r"^[a-z_][a-z0-9_]{0,30}$".to_string()),
("[DB: whitelist]", config.database_structure.clone().whitelist.table_name, r"^[a-z_][a-z0-9_]{0,30}$".to_string()),
("[DB: whitelist] Column: infohash", config.database_structure.clone().whitelist.column_infohash, r"^[a-z_][a-z0-9_]{0,30}$".to_string()),
("[DB: blacklist]", config.database_structure.clone().blacklist.table_name, r"^[a-z_][a-z0-9_]{0,30}$".to_string()),
("[DB: blacklist] Column: infohash", config.database_structure.clone().blacklist.column_infohash, r"^[a-z_][a-z0-9_]{0,30}$".to_string()),
("[DB: keys]", config.database_structure.clone().keys.table_name, r"^[a-z_][a-z0-9_]{0,30}$".to_string()),
("[DB: keys] Column: hash", config.database_structure.clone().keys.column_hash, r"^[a-z_][a-z0-9_]{0,30}$".to_string()),
("[DB: keys] Column: timeout", config.database_structure.clone().keys.column_timeout, r"^[a-z_][a-z0-9_]{0,30}$".to_string()),
("[DB: users]", config.database_structure.clone().users.table_name, r"^[a-z_][a-z0-9_]{0,30}$".to_string()),
("[DB: users] Column: id", config.database_structure.clone().users.column_id, r"^[a-z_][a-z0-9_]{0,30}$".to_string()),
("[DB: users] Column: uuid", config.database_structure.clone().users.column_uuid, r"^[a-z_][a-z0-9_]{0,30}$".to_string()),
("[DB: users] Column: key", config.database_structure.clone().users.column_key, r"^[a-z_][a-z0-9_]{0,30}$".to_string()),
("[DB: users] Column: uploaded", config.database_structure.clone().users.column_uploaded, r"^[a-z_][a-z0-9_]{0,30}$".to_string()),
("[DB: users] Column: downloaded", config.database_structure.clone().users.column_downloaded, r"^[a-z_][a-z0-9_]{0,30}$".to_string()),
("[DB: users] Column: completed", config.database_structure.clone().users.column_completed, r"^[a-z_][a-z0-9_]{0,30}$".to_string()),
("[DB: users] Column: active", config.database_structure.clone().users.column_active, r"^[a-z_][a-z0-9_]{0,30}$".to_string()),
("[DB: users] Column: updated", config.database_structure.clone().users.column_updated, r"^[a-z_][a-z0-9_]{0,30}$".to_string()),
];
// Validation
for (name, value, regex) in check_map {
Self::validate_value(name, value, regex);
}
}
#[tracing::instrument(level = "debug")]
pub fn validate_value(name: &str, value: String, regex: String)
{
let regex_check = Regex::new(regex.as_str()).unwrap();
if !regex_check.is_match(value.as_str()){
panic!("[VALIDATE CONFIG] Error checking {name} [:] Name: \"{value}\" [:] Regex: \"{regex_check}\"");
}
}
} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/config/impls/configuration_error.rs | src/config/impls/configuration_error.rs | use crate::config::enums::configuration_error::ConfigurationError;
impl std::fmt::Display for ConfigurationError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
ConfigurationError::IOError(e) => e.fmt(f),
ConfigurationError::ParseError(e) => e.fmt(f)
}
}
}
impl std::error::Error for ConfigurationError {} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/config/structs/database_structure_config_blacklist.rs | src/config/structs/database_structure_config_blacklist.rs | use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct DatabaseStructureConfigBlacklist {
pub table_name: String,
pub column_infohash: String,
pub bin_type_infohash: bool
} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/config/structs/http_trackers_config.rs | src/config/structs/http_trackers_config.rs | use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct HttpTrackersConfig {
pub enabled: bool,
pub bind_address: String,
pub real_ip: String,
pub keep_alive: u64,
pub request_timeout: u64,
pub disconnect_timeout: u64,
pub max_connections: u64,
pub threads: u64,
pub ssl: bool,
pub ssl_key: String,
pub ssl_cert: String,
pub tls_connection_rate: u64
} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/config/structs/configuration.rs | src/config/structs/configuration.rs | use serde::{Deserialize, Serialize};
use crate::config::structs::api_trackers_config::ApiTrackersConfig;
use crate::config::structs::database_config::DatabaseConfig;
use crate::config::structs::database_structure_config::DatabaseStructureConfig;
use crate::config::structs::http_trackers_config::HttpTrackersConfig;
use crate::config::structs::sentry_config::SentryConfig;
use crate::config::structs::tracker_config::TrackerConfig;
use crate::config::structs::udp_trackers_config::UdpTrackersConfig;
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Configuration {
pub log_level: String,
pub log_console_interval: u64,
pub tracker_config: TrackerConfig,
pub sentry_config: SentryConfig,
pub database: DatabaseConfig,
pub database_structure: DatabaseStructureConfig,
pub http_server: Vec<HttpTrackersConfig>,
pub udp_server: Vec<UdpTrackersConfig>,
pub api_server: Vec<ApiTrackersConfig>
} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/config/structs/udp_trackers_config.rs | src/config/structs/udp_trackers_config.rs | use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct UdpTrackersConfig {
pub enabled: bool,
pub bind_address: String,
pub udp_threads: usize,
pub worker_threads: usize,
pub receive_buffer_size: usize,
pub send_buffer_size: usize,
pub reuse_address: bool
} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/config/structs/database_structure_config.rs | src/config/structs/database_structure_config.rs | use serde::{Deserialize, Serialize};
use crate::config::structs::database_structure_config_blacklist::DatabaseStructureConfigBlacklist;
use crate::config::structs::database_structure_config_keys::DatabaseStructureConfigKeys;
use crate::config::structs::database_structure_config_torrents::DatabaseStructureConfigTorrents;
use crate::config::structs::database_structure_config_users::DatabaseStructureConfigUsers;
use crate::config::structs::database_structure_config_whitelist::DatabaseStructureConfigWhitelist;
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct DatabaseStructureConfig {
pub torrents: DatabaseStructureConfigTorrents,
pub whitelist: DatabaseStructureConfigWhitelist,
pub blacklist: DatabaseStructureConfigBlacklist,
pub keys: DatabaseStructureConfigKeys,
pub users: DatabaseStructureConfigUsers
} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/config/structs/database_structure_config_whitelist.rs | src/config/structs/database_structure_config_whitelist.rs | use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct DatabaseStructureConfigWhitelist {
pub table_name: String,
pub column_infohash: String,
pub bin_type_infohash: bool
} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/config/structs/api_trackers_config.rs | src/config/structs/api_trackers_config.rs | use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ApiTrackersConfig {
pub enabled: bool,
pub bind_address: String,
pub real_ip: String,
pub keep_alive: u64,
pub request_timeout: u64,
pub disconnect_timeout: u64,
pub max_connections: u64,
pub threads: u64,
pub ssl: bool,
pub ssl_key: String,
pub ssl_cert: String,
pub tls_connection_rate: u64
} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/config/structs/database_structure_config_keys.rs | src/config/structs/database_structure_config_keys.rs | use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct DatabaseStructureConfigKeys {
pub table_name: String,
pub column_hash: String,
pub bin_type_hash: bool,
pub column_timeout: String
} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/config/structs/database_config.rs | src/config/structs/database_config.rs | use serde::{Deserialize, Serialize};
use crate::database::enums::database_drivers::DatabaseDrivers;
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct DatabaseConfig {
pub engine: DatabaseDrivers,
pub path: String,
pub persistent: bool,
pub persistent_interval: u64,
pub insert_vacant: bool,
pub remove_action: bool,
pub update_completed: bool,
pub update_peers: bool
} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/config/structs/sentry_config.rs | src/config/structs/sentry_config.rs | use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct SentryConfig {
pub enabled: bool,
pub dsn: String,
pub debug: bool,
pub sample_rate: f32,
pub max_breadcrumbs: usize,
pub attach_stacktrace: bool,
pub send_default_pii: bool,
pub traces_sample_rate: f32
} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/config/structs/database_structure_config_torrents.rs | src/config/structs/database_structure_config_torrents.rs | use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct DatabaseStructureConfigTorrents {
pub table_name: String,
pub column_infohash: String,
pub bin_type_infohash: bool,
pub column_seeds: String,
pub column_peers: String,
pub column_completed: String
} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/config/structs/tracker_config.rs | src/config/structs/tracker_config.rs | use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct TrackerConfig {
pub api_key: String,
pub whitelist_enabled: bool,
pub blacklist_enabled: bool,
pub keys_enabled: bool,
pub keys_cleanup_interval: u64,
pub users_enabled: bool,
pub request_interval: u64,
pub request_interval_minimum: u64,
pub peers_timeout: u64,
pub peers_cleanup_interval: u64,
pub peers_cleanup_threads: u64,
pub total_downloads: u64,
pub swagger: bool,
pub prometheus_id: String,
} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/config/structs/database_structure_config_users.rs | src/config/structs/database_structure_config_users.rs | use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct DatabaseStructureConfigUsers {
pub table_name: String,
pub id_uuid: bool,
pub column_uuid: String,
pub column_id: String,
pub column_key: String,
pub bin_type_key: bool,
pub column_uploaded: String,
pub column_downloaded: String,
pub column_completed: String,
pub column_updated: String,
pub column_active: String
} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/config/enums/configuration_error.rs | src/config/enums/configuration_error.rs | #[derive(Debug)]
pub enum ConfigurationError {
IOError(std::io::Error),
ParseError(toml::de::Error),
} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/database/structs.rs | src/database/structs.rs | pub mod database_connector;
pub mod database_connector_sqlite;
pub mod database_connector_mysql;
pub mod database_connector_pgsql; | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/database/enums.rs | src/database/enums.rs | pub mod database_drivers; | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/database/mod.rs | src/database/mod.rs | pub mod enums;
pub mod impls;
pub mod structs; | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/database/impls.rs | src/database/impls.rs | pub mod database_connector;
pub mod database_connector_sqlite;
pub mod database_connector_mysql;
pub mod database_connector_pgsql; | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/database/impls/database_connector_pgsql.rs | src/database/impls/database_connector_pgsql.rs | use std::collections::BTreeMap;
use std::ops::Deref;
use std::process::exit;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
use async_std::task;
use futures_util::TryStreamExt;
use log::{error, info};
use sha1::{Digest, Sha1};
use sqlx::{ConnectOptions, Error, Pool, Postgres, Row, Transaction};
use sqlx::postgres::{PgConnectOptions, PgPoolOptions};
use crate::config::structs::configuration::Configuration;
use crate::database::enums::database_drivers::DatabaseDrivers;
use crate::database::structs::database_connector::DatabaseConnector;
use crate::database::structs::database_connector_pgsql::DatabaseConnectorPgSQL;
use crate::stats::enums::stats_event::StatsEvent;
use crate::tracker::enums::updates_action::UpdatesAction;
use crate::tracker::structs::info_hash::InfoHash;
use crate::tracker::structs::torrent_entry::TorrentEntry;
use crate::tracker::structs::torrent_tracker::TorrentTracker;
use crate::tracker::structs::user_entry_item::UserEntryItem;
use crate::tracker::structs::user_id::UserId;
impl DatabaseConnectorPgSQL {
#[tracing::instrument(level = "debug")]
pub async fn create(dsl: &str) -> Result<Pool<Postgres>, Error>
{
let options = PgConnectOptions::from_str(dsl)?
.log_statements(log::LevelFilter::Debug)
.log_slow_statements(log::LevelFilter::Debug, Duration::from_secs(1));
PgPoolOptions::new().connect_with(options).await
}
#[tracing::instrument(level = "debug")]
pub async fn database_connector(config: Arc<Configuration>, create_database: bool) -> DatabaseConnector
{
let pgsql_connect = DatabaseConnectorPgSQL::create(config.database.clone().path.as_str()).await;
if pgsql_connect.is_err() {
error!("[PgSQL] Unable to connect to PgSQL on DSL {}", config.database.clone().path);
error!("[PgSQL] Message: {:#?}", pgsql_connect.unwrap_err().into_database_error().unwrap().message());
exit(1);
}
let mut structure = DatabaseConnector { mysql: None, sqlite: None, pgsql: None, engine: None };
structure.pgsql = Some(DatabaseConnectorPgSQL { pool: pgsql_connect.unwrap() });
structure.engine = Some(DatabaseDrivers::pgsql);
if create_database {
let pool = &structure.pgsql.clone().unwrap().pool;
info!("[BOOT] Database creation triggered for PgSQL.");
// Create Torrent DB
info!("[BOOT PgSQL] Creating table {}", config.database_structure.clone().torrents.table_name);
match config.database_structure.clone().torrents.bin_type_infohash {
true => {
match sqlx::query(
format!(
"CREATE TABLE IF NOT EXISTS public.{} ({} bytea NOT NULL, {} integer NOT NULL DEFAULT 0, {} integer NOT NULL DEFAULT 0, {} bigint NOT NULL DEFAULT 0, CONSTRAINT torrents_pkey PRIMARY KEY ({})) TABLESPACE pg_default",
config.database_structure.clone().torrents.table_name,
config.database_structure.clone().torrents.column_infohash,
config.database_structure.clone().torrents.column_seeds,
config.database_structure.clone().torrents.column_peers,
config.database_structure.clone().torrents.column_completed,
config.database_structure.clone().torrents.column_infohash
).as_str()
).execute(pool).await {
Ok(_) => {}
Err(error) => { panic!("[PgSQL] Error: {error}"); }
}
}
false => {
match sqlx::query(
format!(
"CREATE TABLE IF NOT EXISTS public.{} ({} character(40) NOT NULL, {} integer NOT NULL DEFAULT 0, {} integer NOT NULL DEFAULT 0, {} bigint NOT NULL DEFAULT 0, CONSTRAINT torrents_pkey PRIMARY KEY ({})) TABLESPACE pg_default",
config.database_structure.clone().torrents.table_name,
config.database_structure.clone().torrents.column_infohash,
config.database_structure.clone().torrents.column_seeds,
config.database_structure.clone().torrents.column_peers,
config.database_structure.clone().torrents.column_completed,
config.database_structure.clone().torrents.column_infohash
).as_str()
).execute(pool).await {
Ok(_) => {}
Err(error) => { panic!("[PgSQL] Error: {error}"); }
}
}
}
// Create Whitelist DB
info!("[BOOT PgSQL] Creating table {}", config.database_structure.clone().whitelist.table_name);
match config.database_structure.clone().whitelist.bin_type_infohash {
true => {
match sqlx::query(
format!(
"CREATE TABLE IF NOT EXISTS public.{} ({} bytea NOT NULL, CONSTRAINT whitelist_pkey PRIMARY KEY ({})) TABLESPACE pg_default",
config.database_structure.clone().whitelist.table_name,
config.database_structure.clone().whitelist.column_infohash,
config.database_structure.clone().whitelist.column_infohash
).as_str()
).execute(pool).await {
Ok(_) => {}
Err(error) => { panic!("[PgSQL] Error: {error}"); }
}
}
false => {
match sqlx::query(
format!(
"CREATE TABLE IF NOT EXISTS public.{} ({} character(40) NOT NULL, CONSTRAINT whitelist_pkey PRIMARY KEY ({})) TABLESPACE pg_default",
config.database_structure.clone().whitelist.table_name,
config.database_structure.clone().whitelist.column_infohash,
config.database_structure.clone().whitelist.column_infohash
).as_str()
).execute(pool).await {
Ok(_) => {}
Err(error) => { panic!("[PgSQL] Error: {error}"); }
}
}
}
// Create Blacklist DB
info!("[BOOT PgSQL] Creating table {}", config.database_structure.clone().blacklist.table_name);
match config.database_structure.clone().blacklist.bin_type_infohash {
true => {
match sqlx::query(
format!(
"CREATE TABLE IF NOT EXISTS public.{} ({} bytea NOT NULL, CONSTRAINT blacklist_pkey PRIMARY KEY ({})) TABLESPACE pg_default",
config.database_structure.clone().blacklist.table_name,
config.database_structure.clone().blacklist.column_infohash,
config.database_structure.clone().blacklist.column_infohash
).as_str()
).execute(pool).await {
Ok(_) => {}
Err(error) => { panic!("[PgSQL] Error: {error}"); }
}
}
false => {
match sqlx::query(
format!(
"CREATE TABLE IF NOT EXISTS public.{} ({} character(40) NOT NULL, CONSTRAINT blacklist_pkey PRIMARY KEY ({})) TABLESPACE pg_default",
config.database_structure.clone().blacklist.table_name,
config.database_structure.clone().blacklist.column_infohash,
config.database_structure.clone().blacklist.column_infohash
).as_str()
).execute(pool).await {
Ok(_) => {}
Err(error) => { panic!("[PgSQL] Error: {error}"); }
}
}
}
// Create Keys DB
info!("[BOOT PgSQL] Creating table {}", config.database_structure.clone().keys.table_name);
match config.database_structure.clone().keys.bin_type_hash {
true => {
match sqlx::query(
format!(
"CREATE TABLE IF NOT EXISTS public.{} ({} bytea NOT NULL, {} integer NOT NULL DEFAULT 0, CONSTRAINT keys_pkey PRIMARY KEY ({})) TABLESPACE pg_default",
config.database_structure.clone().keys.table_name,
config.database_structure.clone().keys.column_hash,
config.database_structure.clone().keys.column_timeout,
config.database_structure.clone().keys.column_hash
).as_str()
).execute(pool).await {
Ok(_) => {}
Err(error) => { panic!("[PgSQL] Error: {error}"); }
}
}
false => {
match sqlx::query(
format!(
"CREATE TABLE IF NOT EXISTS public.{} ({} character(40) NOT NULL, {} integer NOT NULL DEFAULT 0, CONSTRAINT keys_pkey PRIMARY KEY ({})) TABLESPACE pg_default",
config.database_structure.clone().keys.table_name,
config.database_structure.clone().keys.column_hash,
config.database_structure.clone().keys.column_timeout,
config.database_structure.clone().keys.column_hash
).as_str()
).execute(pool).await {
Ok(_) => {}
Err(error) => { panic!("[PgSQL] Error: {error}"); }
}
}
}
// Create Users DB
info!("[BOOT PgSQL] Creating table {}", config.database_structure.clone().users.table_name);
match config.database_structure.clone().users.id_uuid {
true => {
match config.database_structure.clone().users.bin_type_key {
true => {
match sqlx::query(
format!(
"CREATE TABLE IF NOT EXISTS public.{} ({} character(36) NOT NULL, {} bytea NOT NULL, {} bigint NOT NULL DEFAULT 0, {} bigint NOT NULL DEFAULT 0, {} bigint NOT NULL DEFAULT 0, {} smallint NOT NULL DEFAULT 0, {} integer NOT NULL DEFAULT 0, CONSTRAINT uuid_pkey PRIMARY KEY ({})) TABLESPACE pg_default",
config.database_structure.clone().users.table_name,
config.database_structure.clone().users.column_uuid,
config.database_structure.clone().users.column_key,
config.database_structure.clone().users.column_uploaded,
config.database_structure.clone().users.column_downloaded,
config.database_structure.clone().users.column_completed,
config.database_structure.clone().users.column_active,
config.database_structure.clone().users.column_updated,
config.database_structure.clone().users.column_uuid
).as_str()
).execute(pool).await {
Ok(_) => {}
Err(error) => { panic!("[PgSQL] Error: {error}"); }
}
}
false => {
match sqlx::query(
format!(
"CREATE TABLE IF NOT EXISTS public.{} ({} character(36) NOT NULL, {} character(40) NOT NULL, {} bigint NOT NULL DEFAULT 0, {} bigint NOT NULL DEFAULT 0, {} bigint NOT NULL DEFAULT 0, {} smallint NOT NULL DEFAULT 0, {} integer NOT NULL DEFAULT 0, CONSTRAINT uuid_pkey PRIMARY KEY ({})) TABLESPACE pg_default",
config.database_structure.clone().users.table_name,
config.database_structure.clone().users.column_uuid,
config.database_structure.clone().users.column_key,
config.database_structure.clone().users.column_uploaded,
config.database_structure.clone().users.column_downloaded,
config.database_structure.clone().users.column_completed,
config.database_structure.clone().users.column_active,
config.database_structure.clone().users.column_updated,
config.database_structure.clone().users.column_uuid
).as_str()
).execute(pool).await {
Ok(_) => {}
Err(error) => { panic!("[PgSQL] Error: {error}"); }
}
}
}
}
false => {
match config.database_structure.clone().users.bin_type_key {
true => {
match sqlx::query(
format!(
"CREATE TABLE IF NOT EXISTS public.{} ({} bigserial NOT NULL, {} bytea NOT NULL, {} bigint NOT NULL DEFAULT 0, {} bigint NOT NULL DEFAULT 0, {} bigint NOT NULL DEFAULT 0, {} smallint NOT NULL DEFAULT 0, {} integer NOT NULL DEFAULT 0, CONSTRAINT id_pkey PRIMARY KEY ({})) TABLESPACE pg_default",
config.database_structure.clone().users.table_name,
config.database_structure.clone().users.column_id,
config.database_structure.clone().users.column_key,
config.database_structure.clone().users.column_uploaded,
config.database_structure.clone().users.column_downloaded,
config.database_structure.clone().users.column_completed,
config.database_structure.clone().users.column_active,
config.database_structure.clone().users.column_updated,
config.database_structure.clone().users.column_id
).as_str()
).execute(pool).await {
Ok(_) => {}
Err(error) => { panic!("[PgSQL] Error: {error}"); }
}
}
false => {
match sqlx::query(
format!(
"CREATE TABLE IF NOT EXISTS public.{} ({} bigserial NOT NULL, {} character(40) NOT NULL, {} bigint NOT NULL DEFAULT 0, {} bigint NOT NULL DEFAULT 0, {} bigint NOT NULL DEFAULT 0, {} smallint NOT NULL DEFAULT 0, {} integer NOT NULL DEFAULT 0, CONSTRAINT id_pkey PRIMARY KEY ({})) TABLESPACE pg_default",
config.database_structure.clone().users.table_name,
config.database_structure.clone().users.column_id,
config.database_structure.clone().users.column_key,
config.database_structure.clone().users.column_uploaded,
config.database_structure.clone().users.column_downloaded,
config.database_structure.clone().users.column_completed,
config.database_structure.clone().users.column_active,
config.database_structure.clone().users.column_updated,
config.database_structure.clone().users.column_id
).as_str()
).execute(pool).await {
Ok(_) => {}
Err(error) => { panic!("[PgSQL] Error: {error}"); }
}
}
}
}
}
info!("[BOOT] Created the database and tables, restart without the parameter to start the app.");
task::sleep(Duration::from_secs(1)).await;
exit(0);
}
structure
}
#[tracing::instrument(level = "debug")]
pub async fn load_torrents(&self, tracker: Arc<TorrentTracker>) -> Result<(u64, u64), Error>
{
let mut start = 0u64;
let length = 100000u64;
let mut torrents = 0u64;
let mut completed = 0u64;
let structure = tracker.config.deref().clone().database_structure.clone().torrents;
loop {
let string_format = match tracker.config.deref().clone().database_structure.torrents.bin_type_infohash {
true => {
format!(
"SELECT encode({}::bytea, 'hex'), {} FROM {} LIMIT {}, {}",
structure.column_infohash,
structure.column_completed,
structure.table_name,
start,
length
)
}
false => {
format!(
"SELECT {}, {} FROM {} LIMIT {}, {}",
structure.column_infohash,
structure.column_completed,
structure.table_name,
start,
length
)
}
};
let mut rows = sqlx::query(string_format.as_str()).fetch(&self.pool);
while let Some(result) = rows.try_next().await? {
let info_hash_data: &[u8] = result.get(structure.column_infohash.as_str());
let info_hash: [u8; 20] = <[u8; 20]>::try_from(hex::decode(info_hash_data).unwrap()[0..20].as_ref()).unwrap();
let completed_count: i64 = result.get(structure.column_completed.as_str());
tracker.add_torrent(
InfoHash(info_hash),
TorrentEntry {
seeds: BTreeMap::new(),
peers: BTreeMap::new(),
completed: completed_count as u64,
updated: std::time::Instant::now()
}
);
torrents += 1;
completed += completed_count as u64;
}
start += length;
if torrents < start {
break;
}
info!("[PgSQL] Loaded {torrents} torrents");
}
tracker.set_stats(StatsEvent::Completed, completed as i64);
info!("[PgSQL] Loaded {torrents} torrents with {completed} completed");
Ok((torrents, completed))
}
#[tracing::instrument(level = "debug")]
pub async fn save_torrents(&self, tracker: Arc<TorrentTracker>, torrents: BTreeMap<InfoHash, (TorrentEntry, UpdatesAction)>) -> Result<(), Error>
{
let mut torrents_transaction = self.pool.begin().await?;
let mut torrents_handled_entries = 0u64;
let structure = tracker.config.deref().clone().database_structure.clone().torrents;
for (info_hash, (torrent_entry, updates_action)) in torrents.iter() {
torrents_handled_entries += 1;
match updates_action {
UpdatesAction::Remove => {
if tracker.config.deref().clone().database.remove_action {
let string_format = match tracker.config.deref().clone().database_structure.torrents.bin_type_infohash {
true => {
format!(
"DELETE FROM {} WHERE {}=decode('{}', 'hex')",
structure.table_name,
structure.column_infohash,
info_hash
)
}
false => {
format!(
"DELETE FROM {} WHERE {}='{}'",
structure.table_name,
structure.column_infohash,
info_hash
)
}
};
match sqlx::query(string_format.as_str()).execute(&mut *torrents_transaction).await {
Ok(_) => {}
Err(e) => {
error!("[PgSQL] Error: {e}");
return Err(e);
}
}
}
}
UpdatesAction::Add | UpdatesAction::Update => {
match tracker.config.deref().clone().database.insert_vacant {
true => {
if tracker.config.deref().clone().database.update_peers {
let string_format = match tracker.config.deref().clone().database_structure.torrents.bin_type_infohash {
true => {
format!(
"INSERT INTO {} ({}, {}, {}) VALUES (decode('{}', 'hex'), {}, {}) ON CONFLICT ({}) DO UPDATE SET {}=excluded.{}, {}=excluded.{}",
structure.table_name,
structure.column_infohash,
structure.column_seeds,
structure.column_peers,
info_hash,
torrent_entry.seeds.len(),
torrent_entry.peers.len(),
structure.column_infohash,
structure.column_seeds,
structure.column_seeds,
structure.column_peers,
structure.column_peers
)
}
false => {
format!(
"INSERT INTO {} ({}, {}, {}) VALUES ('{}', {}, {}) ON CONFLICT ({}) DO UPDATE SET {}=excluded.{}, {}=excluded.{}",
structure.table_name,
structure.column_infohash,
structure.column_seeds,
structure.column_peers,
info_hash,
torrent_entry.seeds.len(),
torrent_entry.peers.len(),
structure.column_infohash,
structure.column_seeds,
structure.column_seeds,
structure.column_peers,
structure.column_peers
)
}
};
match sqlx::query(string_format.as_str()).execute(&mut *torrents_transaction).await {
Ok(_) => {}
Err(e) => {
error!("[PgSQL] Error: {e}");
return Err(e);
}
}
}
if tracker.config.deref().clone().database.update_completed {
let string_format = match tracker.config.deref().clone().database_structure.torrents.bin_type_infohash {
true => {
format!(
"INSERT INTO {} ({}, {}) VALUES (decode('{}', 'hex'), {}) ON CONFLICT ({}) DO UPDATE SET {}=excluded.{}",
structure.table_name,
structure.column_infohash,
structure.column_completed,
info_hash,
torrent_entry.completed,
structure.column_infohash,
structure.column_completed,
structure.column_completed
)
}
false => {
format!(
"INSERT INTO {} ({}, {}) VALUES ('{}', {}) ON CONFLICT ({}) DO UPDATE SET {}=excluded.{}",
structure.table_name,
structure.column_infohash,
structure.column_completed,
info_hash,
torrent_entry.completed,
structure.column_infohash,
structure.column_completed,
structure.column_completed
)
}
};
match sqlx::query(string_format.as_str()).execute(&mut *torrents_transaction).await {
Ok(_) => {}
Err(e) => {
error!("[PgSQL] Error: {e}");
return Err(e);
}
}
}
}
false => {
if tracker.config.deref().clone().database.update_peers {
let string_format = match tracker.config.deref().clone().database_structure.torrents.bin_type_infohash {
true => {
format!(
"UPDATE {} SET ({}, {}) = ({}, {}) WHERE {}=decode('{}', 'hex') AND NOT EXISTS (SELECT 1 FROM {} WHERE {}=decode('{}', 'hex'))",
structure.table_name,
structure.column_seeds,
structure.column_peers,
torrent_entry.seeds.len(),
torrent_entry.peers.len(),
structure.column_infohash,
info_hash,
structure.table_name,
structure.column_infohash,
info_hash
)
}
false => {
format!(
"UPDATE {} SET ({}, {}) = ({}, {}) WHERE {}='{}' AND NOT EXISTS (SELECT 1 FROM {} WHERE {}='{}')",
structure.table_name,
structure.column_seeds,
structure.column_peers,
torrent_entry.seeds.len(),
torrent_entry.peers.len(),
structure.column_infohash,
info_hash,
structure.table_name,
structure.column_infohash,
info_hash
)
}
};
match sqlx::query(string_format.as_str()).execute(&mut *torrents_transaction).await {
Ok(_) => {}
Err(e) => {
error!("[PgSQL] Error: {e}");
return Err(e);
}
}
}
if tracker.config.deref().clone().database.update_completed {
let string_format = match tracker.config.deref().clone().database_structure.torrents.bin_type_infohash {
true => {
format!(
"UPDATE {} SET {}={} WHERE {}=decode('{}', 'hex') AND EXISTS (SELECT 1 FROM {} WHERE {}=decode('{}', 'hex'))",
structure.table_name,
structure.column_completed,
torrent_entry.completed,
structure.column_infohash,
info_hash,
structure.table_name,
structure.column_infohash,
info_hash
)
}
false => {
format!(
"UPDATE {} SET {}={} WHERE {}='{}' AND EXISTS (SELECT 1 FROM {} WHERE {}='{}')",
structure.table_name,
structure.column_completed,
torrent_entry.completed,
structure.column_infohash,
info_hash,
structure.table_name,
structure.column_infohash,
info_hash
)
}
};
match sqlx::query(string_format.as_str()).execute(&mut *torrents_transaction).await {
Ok(_) => {}
Err(e) => {
error!("[PgSQL] Error: {e}");
return Err(e);
}
}
}
}
}
}
}
if (torrents_handled_entries as f64 / 1000f64).fract() == 0.0 || torrents.len() as u64 == torrents_handled_entries {
info!("[PgSQL] Handled {torrents_handled_entries} torrents");
}
}
| rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | true |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/database/impls/database_connector_sqlite.rs | src/database/impls/database_connector_sqlite.rs | use std::collections::BTreeMap;
use std::ops::Deref;
use std::process::exit;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
use async_std::task;
use futures_util::TryStreamExt;
use log::{error, info};
use sha1::{Digest, Sha1};
use sqlx::{ConnectOptions, Error, Sqlite, Pool, Row, Transaction};
use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
use crate::config::structs::configuration::Configuration;
use crate::database::enums::database_drivers::DatabaseDrivers;
use crate::database::structs::database_connector::DatabaseConnector;
use crate::database::structs::database_connector_sqlite::DatabaseConnectorSQLite;
use crate::stats::enums::stats_event::StatsEvent;
use crate::tracker::enums::updates_action::UpdatesAction;
use crate::tracker::structs::info_hash::InfoHash;
use crate::tracker::structs::torrent_entry::TorrentEntry;
use crate::tracker::structs::torrent_tracker::TorrentTracker;
use crate::tracker::structs::user_entry_item::UserEntryItem;
use crate::tracker::structs::user_id::UserId;
impl DatabaseConnectorSQLite {
#[tracing::instrument(level = "debug")]
pub async fn create(dsl: &str) -> Result<Pool<Sqlite>, Error>
{
let options = SqliteConnectOptions::from_str(dsl)?
.log_statements(log::LevelFilter::Debug)
.log_slow_statements(log::LevelFilter::Debug, Duration::from_secs(1));
SqlitePoolOptions::new().connect_with(options.create_if_missing(true)).await
}
#[tracing::instrument(level = "debug")]
pub async fn database_connector(config: Arc<Configuration>, create_database: bool) -> DatabaseConnector
{
let sqlite_connect = DatabaseConnectorSQLite::create(config.database.clone().path.as_str()).await;
if sqlite_connect.is_err() {
error!("[SQLite] Unable to connect to SQLite on DSL {}", config.database.clone().path);
error!("[SQLite] Message: {:#?}", sqlite_connect.unwrap_err().into_database_error().unwrap().message());
exit(1);
}
let mut structure = DatabaseConnector { mysql: None, sqlite: None, pgsql: None, engine: None };
structure.sqlite = Some(DatabaseConnectorSQLite { pool: sqlite_connect.unwrap() });
structure.engine = Some(DatabaseDrivers::sqlite3);
if create_database {
let pool = &structure.sqlite.clone().unwrap().pool;
info!("[BOOT] Database creation triggered for SQLite.");
info!("[BOOT SQLite] Setting the PRAGMA config...");
let _ = sqlx::query("PRAGMA temp_store = memory;").execute(pool).await;
let _ = sqlx::query("PRAGMA mmap_size = 30000000000;").execute(pool).await;
let _ = sqlx::query("PRAGMA page_size = 32768;").execute(pool).await;
let _ = sqlx::query("PRAGMA synchronous = full;").execute(pool).await;
// Create Torrent DB
info!("[BOOT SQLite] Creating table {}", config.database_structure.clone().torrents.table_name);
match config.database_structure.clone().torrents.bin_type_infohash {
true => {
match sqlx::query(
format!(
"CREATE TABLE IF NOT EXISTS `{}` (`{}` BLOB PRIMARY KEY NOT NULL, `{}` INTEGER DEFAULT 0, `{}` INTEGER DEFAULT 0, `{}` INTEGER DEFAULT 0)",
config.database_structure.clone().torrents.table_name,
config.database_structure.clone().torrents.column_infohash,
config.database_structure.clone().torrents.column_seeds,
config.database_structure.clone().torrents.column_peers,
config.database_structure.clone().torrents.column_completed
).as_str()
).execute(pool).await {
Ok(_) => {}
Err(error) => { panic!("[SQLite] Error: {error}"); }
}
}
false => {
match sqlx::query(
format!(
"CREATE TABLE IF NOT EXISTS `{}` (`{}` TEXT PRIMARY KEY NOT NULL, `{}` INTEGER DEFAULT 0, `{}` INTEGER DEFAULT 0, `{}` INTEGER DEFAULT 0)",
config.database_structure.clone().torrents.table_name,
config.database_structure.clone().torrents.column_infohash,
config.database_structure.clone().torrents.column_seeds,
config.database_structure.clone().torrents.column_peers,
config.database_structure.clone().torrents.column_completed
).as_str()
).execute(pool).await {
Ok(_) => {}
Err(error) => { panic!("[SQLite] Error: {error}"); }
}
}
}
// Create Whitelist DB
info!("[BOOT SQLite] Creating table {}", config.database_structure.clone().whitelist.table_name);
match config.database_structure.clone().whitelist.bin_type_infohash {
true => {
match sqlx::query(
format!(
"CREATE TABLE IF NOT EXISTS `{}` (`{}` BLOB PRIMARY KEY NOT NULL)",
config.database_structure.clone().whitelist.table_name,
config.database_structure.clone().whitelist.column_infohash
).as_str()
).execute(pool).await {
Ok(_) => {}
Err(error) => { panic!("[SQLite] Error: {error}"); }
}
}
false => {
match sqlx::query(
format!(
"CREATE TABLE IF NOT EXISTS `{}` (`{}` TEXT PRIMARY KEY NOT NULL)",
config.database_structure.clone().whitelist.table_name,
config.database_structure.clone().whitelist.column_infohash
).as_str()
).execute(pool).await {
Ok(_) => {}
Err(error) => { panic!("[SQLite] Error: {error}"); }
}
}
}
// Create Blacklist DB
info!("[BOOT SQLite] Creating table {}", config.database_structure.clone().blacklist.table_name);
match config.database_structure.clone().blacklist.bin_type_infohash {
true => {
match sqlx::query(
format!(
"CREATE TABLE IF NOT EXISTS `{}` (`{}` BLOB PRIMARY KEY NOT NULL)",
config.database_structure.clone().blacklist.table_name,
config.database_structure.clone().blacklist.column_infohash
).as_str()
).execute(pool).await {
Ok(_) => {}
Err(error) => { panic!("[SQLite] Error: {error}"); }
}
}
false => {
match sqlx::query(
format!(
"CREATE TABLE IF NOT EXISTS `{}` (`{}` TEXT PRIMARY KEY NOT NULL)",
config.database_structure.clone().blacklist.table_name,
config.database_structure.clone().blacklist.column_infohash
).as_str()
).execute(pool).await {
Ok(_) => {}
Err(error) => { panic!("[SQLite] Error: {error}"); }
}
}
}
// Create Keys DB
info!("[BOOT SQLite] Creating table {}", config.database_structure.clone().keys.table_name);
match config.database_structure.clone().keys.bin_type_hash {
true => {
match sqlx::query(
format!(
"CREATE TABLE IF NOT EXISTS `{}` (`{}` BLOB PRIMARY KEY NOT NULL, `{}` INTEGER DEFAULT 0)",
config.database_structure.clone().keys.table_name,
config.database_structure.clone().keys.column_hash,
config.database_structure.clone().keys.column_timeout
).as_str()
).execute(pool).await {
Ok(_) => {}
Err(error) => { panic!("[SQLite] Error: {error}"); }
}
}
false => {
match sqlx::query(
format!(
"CREATE TABLE IF NOT EXISTS `{}` (`{}` TEXT PRIMARY KEY NOT NULL, `{}` INTEGER DEFAULT 0)",
config.database_structure.clone().keys.table_name,
config.database_structure.clone().keys.column_hash,
config.database_structure.clone().keys.column_timeout
).as_str()
).execute(pool).await {
Ok(_) => {}
Err(error) => { panic!("[SQLite] Error: {error}"); }
}
}
}
// Create Users DB
info!("[BOOT SQLite] Creating table {}", config.database_structure.clone().users.table_name);
match config.database_structure.clone().users.id_uuid {
true => {
match config.database_structure.clone().users.bin_type_key {
true => {
match sqlx::query(
format!(
"CREATE TABLE IF NOT EXISTS `{}` (`{}` TEXT PRIMARY KEY NOT NULL, `{}` BLOB NOT NULL, `{}` INTEGER NOT NULL DEFAULT 0, `{}` INTEGER NOT NULL DEFAULT 0, `{}` INTEGER NOT NULL DEFAULT 0, `{}` INTEGER NOT NULL DEFAULT 0, `{}` INTEGER NOT NULL DEFAULT 0)",
config.database_structure.clone().users.table_name,
config.database_structure.clone().users.column_uuid,
config.database_structure.clone().users.column_key,
config.database_structure.clone().users.column_uploaded,
config.database_structure.clone().users.column_downloaded,
config.database_structure.clone().users.column_completed,
config.database_structure.clone().users.column_active,
config.database_structure.clone().users.column_updated
).as_str()
).execute(pool).await {
Ok(_) => {}
Err(error) => { panic!("[SQLite] Error: {error}"); }
}
}
false => {
match sqlx::query(
format!(
"CREATE TABLE IF NOT EXISTS `{}` (`{}` TEXT PRIMARY KEY NOT NULL, `{}` TEXT NOT NULL, `{}` INTEGER NOT NULL DEFAULT 0, `{}` INTEGER NOT NULL DEFAULT 0, `{}` INTEGER NOT NULL DEFAULT 0, `{}` INTEGER NOT NULL DEFAULT 0, `{}` INTEGER NOT NULL DEFAULT 0)",
config.database_structure.clone().users.table_name,
config.database_structure.clone().users.column_uuid,
config.database_structure.clone().users.column_key,
config.database_structure.clone().users.column_uploaded,
config.database_structure.clone().users.column_downloaded,
config.database_structure.clone().users.column_completed,
config.database_structure.clone().users.column_active,
config.database_structure.clone().users.column_updated
).as_str()
).execute(pool).await {
Ok(_) => {}
Err(error) => { panic!("[SQLite] Error: {error}"); }
}
}
}
}
false => {
match config.database_structure.clone().users.bin_type_key {
true => {
match sqlx::query(
format!(
"CREATE TABLE IF NOT EXISTS `{}` (`{}` INTEGER PRIMARY KEY AUTOINCREMENT, `{}` BLOB NOT NULL, `{}` INTEGER NOT NULL DEFAULT 0, `{}` INTEGER NOT NULL DEFAULT 0, `{}` INTEGER NOT NULL DEFAULT 0, `{}` INTEGER NOT NULL DEFAULT 0, `{}` INTEGER NOT NULL DEFAULT 0)",
config.database_structure.clone().users.table_name,
config.database_structure.clone().users.column_id,
config.database_structure.clone().users.column_key,
config.database_structure.clone().users.column_uploaded,
config.database_structure.clone().users.column_downloaded,
config.database_structure.clone().users.column_completed,
config.database_structure.clone().users.column_active,
config.database_structure.clone().users.column_updated
).as_str()
).execute(pool).await {
Ok(_) => {}
Err(error) => { panic!("[SQLite] Error: {error}"); }
}
}
false => {
match sqlx::query(
format!(
"CREATE TABLE IF NOT EXISTS `{}` (`{}` INTEGER PRIMARY KEY AUTOINCREMENT, `{}` TEXT NOT NULL, `{}` INTEGER NOT NULL DEFAULT 0, `{}` INTEGER NOT NULL DEFAULT 0, `{}` INTEGER NOT NULL DEFAULT 0, `{}` INTEGER NOT NULL DEFAULT 0, `{}` INTEGER NOT NULL DEFAULT 0)",
config.database_structure.clone().users.table_name,
config.database_structure.clone().users.column_id,
config.database_structure.clone().users.column_key,
config.database_structure.clone().users.column_uploaded,
config.database_structure.clone().users.column_downloaded,
config.database_structure.clone().users.column_completed,
config.database_structure.clone().users.column_active,
config.database_structure.clone().users.column_updated
).as_str()
).execute(pool).await {
Ok(_) => {}
Err(error) => { panic!("[SQLite] Error: {error}"); }
}
}
}
}
}
info!("[BOOT] Created the database and tables, restart without the parameter to start the app.");
task::sleep(Duration::from_secs(1)).await;
exit(0);
}
structure
}
#[tracing::instrument(level = "debug")]
pub async fn load_torrents(&self, tracker: Arc<TorrentTracker>) -> Result<(u64, u64), Error>
{
let mut start = 0u64;
let length = 100000u64;
let mut torrents = 0u64;
let mut completed = 0u64;
let structure = tracker.config.deref().clone().database_structure.clone().torrents;
loop {
let string_format = match tracker.config.deref().clone().database_structure.torrents.bin_type_infohash {
true => {
format!(
"SELECT hex(`{}`) AS `{}`, `{}` FROM `{}` LIMIT {}, {}",
structure.column_infohash,
structure.column_infohash,
structure.column_completed,
structure.table_name,
start,
length
)
}
false => {
format!(
"SELECT `{}`, `{}` FROM `{}` LIMIT {}, {}",
structure.column_infohash,
structure.column_completed,
structure.table_name,
start,
length
)
}
};
let mut rows = sqlx::query(string_format.as_str()).fetch(&self.pool);
while let Some(result) = rows.try_next().await? {
let info_hash_data: &[u8] = result.get(structure.column_infohash.as_str());
let info_hash: [u8; 20] = <[u8; 20]>::try_from(hex::decode(info_hash_data).unwrap()[0..20].as_ref()).unwrap();
let completed_count: u32 = result.get(structure.column_completed.as_str());
tracker.add_torrent(
InfoHash(info_hash),
TorrentEntry {
seeds: BTreeMap::new(),
peers: BTreeMap::new(),
completed: completed_count as u64,
updated: std::time::Instant::now()
}
);
torrents += 1;
completed += completed_count as u64;
}
start += length;
if torrents < start {
break;
}
info!("[SQLite] Handled {torrents} torrents");
}
tracker.set_stats(StatsEvent::Completed, completed as i64);
info!("[SQLite] Loaded {torrents} torrents with {completed} completed");
Ok((torrents, completed))
}
#[tracing::instrument(level = "debug")]
pub async fn save_torrents(&self, tracker: Arc<TorrentTracker>, torrents: BTreeMap<InfoHash, (TorrentEntry, UpdatesAction)>) -> Result<(), Error>
{
let mut torrents_transaction = self.pool.begin().await?;
let mut torrents_handled_entries = 0u64;
let structure = tracker.config.deref().clone().database_structure.clone().torrents;
for (info_hash, (torrent_entry, updates_action)) in torrents.iter() {
torrents_handled_entries += 1;
match updates_action {
UpdatesAction::Remove => {
if tracker.config.deref().clone().database.remove_action {
let string_format = match tracker.config.deref().clone().database_structure.torrents.bin_type_infohash {
true => {
format!(
"DELETE FROM `{}` WHERE `{}`=X'{}'",
structure.table_name,
structure.column_infohash,
info_hash
)
}
false => {
format!(
"DELETE FROM `{}` WHERE `{}`='{}'",
structure.table_name,
structure.column_infohash,
info_hash
)
}
};
match sqlx::query(string_format.as_str()).execute(&mut *torrents_transaction).await {
Ok(_) => {}
Err(e) => {
error!("[SQLite] Error: {e}");
return Err(e);
}
}
}
}
UpdatesAction::Add | UpdatesAction::Update => {
match tracker.config.deref().clone().database.insert_vacant {
true => {
if tracker.config.deref().clone().database.update_peers {
let string_format = match tracker.config.deref().clone().database_structure.torrents.bin_type_infohash {
true => {
format!(
"INSERT INTO `{}` (`{}`, `{}`, `{}`) VALUES (X'{}', {}, {}) ON CONFLICT (`{}`) DO UPDATE SET `{}`=excluded.`{}`, `{}`=excluded.`{}`",
structure.table_name,
structure.column_infohash,
structure.column_seeds,
structure.column_peers,
info_hash,
torrent_entry.seeds.len(),
torrent_entry.peers.len(),
structure.column_infohash,
structure.column_seeds,
structure.column_seeds,
structure.column_peers,
structure.column_peers
)
}
false => {
format!(
"INSERT INTO `{}` (`{}`, `{}`, `{}`) VALUES ('{}', {}, {}) ON CONFLICT (`{}`) DO UPDATE SET `{}`=excluded.`{}`, `{}`=excluded.`{}`",
structure.table_name,
structure.column_infohash,
structure.column_seeds,
structure.column_peers,
info_hash,
torrent_entry.seeds.len(),
torrent_entry.peers.len(),
structure.column_infohash,
structure.column_seeds,
structure.column_seeds,
structure.column_peers,
structure.column_peers
)
}
};
match sqlx::query(string_format.as_str()).execute(&mut *torrents_transaction).await {
Ok(_) => {}
Err(e) => {
error!("[SQLite] Error: {e}");
return Err(e);
}
}
}
if tracker.config.deref().clone().database.update_completed {
let string_format = match tracker.config.deref().clone().database_structure.torrents.bin_type_infohash {
true => {
format!(
"INSERT INTO `{}` (`{}`, `{}`) VALUES (X'{}', {}) ON CONFLICT (`{}`) DO UPDATE SET `{}`=excluded.`{}`",
structure.table_name,
structure.column_infohash,
structure.column_completed,
info_hash,
torrent_entry.completed,
structure.column_infohash,
structure.column_completed,
structure.column_completed
)
}
false => {
format!(
"INSERT INTO `{}` (`{}`, `{}`) VALUES ('{}', {}) ON CONFLICT (`{}`) DO UPDATE SET `{}`=excluded.`{}`",
structure.table_name,
structure.column_infohash,
structure.column_completed,
info_hash,
torrent_entry.completed,
structure.column_infohash,
structure.column_completed,
structure.column_completed
)
}
};
match sqlx::query(string_format.as_str()).execute(&mut *torrents_transaction).await {
Ok(_) => {}
Err(e) => {
error!("[SQLite] Error: {e}");
return Err(e);
}
}
}
}
false => {
if tracker.config.deref().clone().database.update_peers {
let string_format = match tracker.config.deref().clone().database_structure.torrents.bin_type_infohash {
true => {
format!(
"UPDATE OR IGNORE `{}` SET `{}`={}, `{}`={} WHERE `{}`=X'{}'",
structure.table_name,
structure.column_seeds,
torrent_entry.seeds.len(),
structure.column_peers,
torrent_entry.peers.len(),
structure.column_infohash,
info_hash
)
}
false => {
format!(
"UPDATE OR IGNORE `{}` SET `{}`={}, `{}`={} WHERE `{}`='{}'",
structure.table_name,
structure.column_seeds,
torrent_entry.seeds.len(),
structure.column_peers,
torrent_entry.peers.len(),
structure.column_infohash,
info_hash
)
}
};
match sqlx::query(string_format.as_str()).execute(&mut *torrents_transaction).await {
Ok(_) => {}
Err(e) => {
error!("[SQLite] Error: {e}");
return Err(e);
}
}
}
if tracker.config.deref().clone().database.update_completed {
let string_format = match tracker.config.deref().clone().database_structure.torrents.bin_type_infohash {
true => {
format!(
"UPDATE IGNORE `{}` SET `{}`={} WHERE `{}`=X'{}'",
structure.table_name,
structure.column_completed,
torrent_entry.completed,
structure.column_infohash,
info_hash
)
}
false => {
format!(
"UPDATE IGNORE `{}` SET `{}`={} WHERE `{}`='{}'",
structure.table_name,
structure.column_completed,
torrent_entry.completed,
structure.column_infohash,
info_hash
)
}
};
match sqlx::query(string_format.as_str()).execute(&mut *torrents_transaction).await {
Ok(_) => {}
Err(e) => {
error!("[SQLite] Error: {e}");
return Err(e);
}
}
}
}
}
}
}
if (torrents_handled_entries as f64 / 1000f64).fract() == 0.0 || torrents.len() as u64 == torrents_handled_entries {
info!("[SQLite] Handled {torrents_handled_entries} torrents");
}
}
info!("[SQLite] Handled {torrents_handled_entries} torrents");
self.commit(torrents_transaction).await
}
#[tracing::instrument(level = "debug")]
pub async fn load_whitelist(&self, tracker: Arc<TorrentTracker>) -> Result<u64, Error>
{
let mut start = 0u64;
let length = 100000u64;
let mut hashes = 0u64;
let structure = tracker.config.deref().clone().database_structure.clone().whitelist;
loop {
let string_format = match tracker.config.deref().clone().database_structure.whitelist.bin_type_infohash {
true => {
format!(
"SELECT HEX(`{}`) AS `{}` FROM `{}` LIMIT {}, {}",
structure.column_infohash,
structure.column_infohash,
structure.table_name,
start,
length
)
}
false => {
format!(
"SELECT `{}` FROM `{}` LIMIT {}, {}",
structure.column_infohash,
structure.table_name,
start,
length
)
}
};
let mut rows = sqlx::query(string_format.as_str()).fetch(&self.pool);
while let Some(result) = rows.try_next().await? {
let info_hash_data: &[u8] = result.get(structure.column_infohash.as_str());
let info_hash: [u8; 20] = <[u8; 20]>::try_from(hex::decode(info_hash_data).unwrap()[0..20].as_ref()).unwrap();
tracker.add_whitelist(InfoHash(info_hash));
hashes += 1;
}
start += length;
if hashes < start {
break;
}
info!("[SQLite] Handled {hashes} whitelisted torrents");
}
info!("[SQLite] Handled {hashes} whitelisted torrents");
Ok(hashes)
}
#[tracing::instrument(level = "debug")]
| rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | true |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/database/impls/database_connector_mysql.rs | src/database/impls/database_connector_mysql.rs | use std::collections::BTreeMap;
use std::ops::Deref;
use std::process::exit;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
use async_std::task;
use futures_util::TryStreamExt;
use log::{error, info};
use sha1::{Digest, Sha1};
use sqlx::{ConnectOptions, Error, MySql, Pool, Row, Transaction};
use sqlx::mysql::{MySqlConnectOptions, MySqlPoolOptions};
use crate::config::structs::configuration::Configuration;
use crate::database::enums::database_drivers::DatabaseDrivers;
use crate::database::structs::database_connector::DatabaseConnector;
use crate::database::structs::database_connector_mysql::DatabaseConnectorMySQL;
use crate::stats::enums::stats_event::StatsEvent;
use crate::tracker::enums::updates_action::UpdatesAction;
use crate::tracker::structs::info_hash::InfoHash;
use crate::tracker::structs::torrent_entry::TorrentEntry;
use crate::tracker::structs::torrent_tracker::TorrentTracker;
use crate::tracker::structs::user_entry_item::UserEntryItem;
use crate::tracker::structs::user_id::UserId;
impl DatabaseConnectorMySQL {
#[tracing::instrument(level = "debug")]
pub async fn create(dsl: &str) -> Result<Pool<MySql>, Error>
{
MySqlPoolOptions::new().connect_with(
MySqlConnectOptions::from_str(dsl)?
.log_statements(log::LevelFilter::Debug)
.log_slow_statements(log::LevelFilter::Debug, Duration::from_secs(1))
).await
}
#[tracing::instrument(level = "debug")]
pub async fn database_connector(config: Arc<Configuration>, create_database: bool) -> DatabaseConnector
{
let mysql_connect = DatabaseConnectorMySQL::create(config.database.clone().path.as_str()).await;
if mysql_connect.is_err() {
error!("[MySQL] Unable to connect to MySQL on DSL {}", config.database.clone().path);
error!("[MySQL] Message: {:#?}", mysql_connect.unwrap_err().into_database_error().unwrap().message());
exit(1);
}
let mut structure = DatabaseConnector { mysql: None, sqlite: None, pgsql: None, engine: None };
structure.mysql = Some(DatabaseConnectorMySQL { pool: mysql_connect.unwrap() });
structure.engine = Some(DatabaseDrivers::mysql);
if create_database {
let pool = &structure.mysql.clone().unwrap().pool;
info!("[BOOT] Database creation triggered for MySQL.");
// Create Torrent DB
info!("[BOOT MySQL] Creating table {}", config.database_structure.clone().torrents.table_name);
match config.database_structure.clone().torrents.bin_type_infohash {
true => {
match sqlx::query(
format!(
"CREATE TABLE `{}` (`{}` BINARY(20) NOT NULL, `{}` INT NOT NULL DEFAULT 0, `{}` INT NOT NULL DEFAULT 0, `{}` BIGINT UNSIGNED NOT NULL DEFAULT 0, PRIMARY KEY (`{}`)) COLLATE='utf8mb4_general_ci'",
config.database_structure.clone().torrents.table_name,
config.database_structure.clone().torrents.column_infohash,
config.database_structure.clone().torrents.column_seeds,
config.database_structure.clone().torrents.column_peers,
config.database_structure.clone().torrents.column_completed,
config.database_structure.clone().torrents.column_infohash
).as_str()
).execute(pool).await {
Ok(_) => {}
Err(error) => { panic!("[MySQL] Error: {error}"); }
}
}
false => {
match sqlx::query(
format!(
"CREATE TABLE `{}` (`{}` VARCHAR(40) NOT NULL, `{}` INT NOT NULL DEFAULT 0, `{}` INT NOT NULL DEFAULT 0, `{}` BIGINT UNSIGNED NOT NULL DEFAULT 0, PRIMARY KEY (`{}`)) COLLATE='utf8mb4_general_ci'",
config.database_structure.clone().torrents.table_name,
config.database_structure.clone().torrents.column_infohash,
config.database_structure.clone().torrents.column_seeds,
config.database_structure.clone().torrents.column_peers,
config.database_structure.clone().torrents.column_completed,
config.database_structure.clone().torrents.column_infohash
).as_str()
).execute(pool).await {
Ok(_) => {}
Err(error) => { panic!("[MySQL] Error: {error}"); }
}
}
}
// Create Whitelist DB
info!("[BOOT MySQL] Creating table {}", config.database_structure.clone().whitelist.table_name);
match config.database_structure.clone().whitelist.bin_type_infohash {
true => {
match sqlx::query(
format!(
"CREATE TABLE `{}` (`{}` BINARY(20) NOT NULL, PRIMARY KEY (`{}`)) COLLATE='utf8mb4_general_ci'",
config.database_structure.clone().whitelist.table_name,
config.database_structure.clone().whitelist.column_infohash,
config.database_structure.clone().whitelist.column_infohash
).as_str()
).execute(pool).await {
Ok(_) => {}
Err(error) => { panic!("[MySQL] Error: {error}"); }
}
}
false => {
match sqlx::query(
format!(
"CREATE TABLE `{}` (`{}` VARCHAR(40) NOT NULL, PRIMARY KEY (`{}`)) COLLATE='utf8mb4_general_ci'",
config.database_structure.clone().whitelist.table_name,
config.database_structure.clone().whitelist.column_infohash,
config.database_structure.clone().whitelist.column_infohash
).as_str()
).execute(pool).await {
Ok(_) => {}
Err(error) => { panic!("[MySQL] Error: {error}"); }
}
}
}
// Create Blacklist DB
info!("[BOOT MySQL] Creating table {}", config.database_structure.clone().blacklist.table_name);
match config.database_structure.clone().blacklist.bin_type_infohash {
true => {
match sqlx::query(
format!(
"CREATE TABLE `{}` (`{}` BINARY(20) NOT NULL, PRIMARY KEY (`{}`)) COLLATE='utf8mb4_general_ci'",
config.database_structure.clone().blacklist.table_name,
config.database_structure.clone().blacklist.column_infohash,
config.database_structure.clone().blacklist.column_infohash
).as_str()
).execute(pool).await {
Ok(_) => {}
Err(error) => { panic!("[MySQL] Error: {error}"); }
}
}
false => {
match sqlx::query(
format!(
"CREATE TABLE `{}` (`{}` VARCHAR(40) NOT NULL, PRIMARY KEY (`{}`)) COLLATE='utf8mb4_general_ci'",
config.database_structure.clone().blacklist.table_name,
config.database_structure.clone().blacklist.column_infohash,
config.database_structure.clone().blacklist.column_infohash
).as_str()
).execute(pool).await {
Ok(_) => {}
Err(error) => { panic!("[MySQL] Error: {error}"); }
}
}
}
// Create Keys DB
info!("[BOOT MySQL] Creating table {}", config.database_structure.clone().keys.table_name);
match config.database_structure.clone().keys.bin_type_hash {
true => {
match sqlx::query(
format!(
"CREATE TABLE `{}` (`{}` BINARY(20) NOT NULL, `{}` INT NOT NULL DEFAULT 0, PRIMARY KEY (`{}`)) COLLATE='utf8mb4_general_ci'",
config.database_structure.clone().keys.table_name,
config.database_structure.clone().keys.column_hash,
config.database_structure.clone().keys.column_timeout,
config.database_structure.clone().keys.column_hash
).as_str()
).execute(pool).await {
Ok(_) => {}
Err(error) => { panic!("[MySQL] Error: {error}"); }
}
}
false => {
match sqlx::query(
format!(
"CREATE TABLE `{}` (`{}` VARCHAR(40) NOT NULL, `{}` INT NOT NULL DEFAULT 0, PRIMARY KEY (`{}`)) COLLATE='utf8mb4_general_ci'",
config.database_structure.clone().keys.table_name,
config.database_structure.clone().keys.column_hash,
config.database_structure.clone().keys.column_timeout,
config.database_structure.clone().keys.column_hash
).as_str()
).execute(pool).await {
Ok(_) => {}
Err(error) => { panic!("[MySQL] Error: {error}"); }
}
}
}
// Create Users DB
info!("[BOOT MySQL] Creating table {}", config.database_structure.clone().users.table_name);
match config.database_structure.clone().users.id_uuid {
true => {
match config.database_structure.clone().users.bin_type_key {
true => {
match sqlx::query(
format!(
"CREATE TABLE `{}` (`{}` VARCHAR(36) NOT NULL, `{}` BINARY(20) NOT NULL, `{}` BIGINT UNSIGNED NOT NULL DEFAULT 0, `{}` BIGINT UNSIGNED NOT NULL DEFAULT 0, `{}` BIGINT UNSIGNED NOT NULL DEFAULT 0, `{}` TINYINT NOT NULL DEFAULT 0, `{}` INT NOT NULL DEFAULT 0, PRIMARY KEY (`{}`)) COLLATE='utf8mb4_general_ci'",
config.database_structure.clone().users.table_name,
config.database_structure.clone().users.column_uuid,
config.database_structure.clone().users.column_key,
config.database_structure.clone().users.column_uploaded,
config.database_structure.clone().users.column_downloaded,
config.database_structure.clone().users.column_completed,
config.database_structure.clone().users.column_active,
config.database_structure.clone().users.column_updated,
config.database_structure.clone().users.column_uuid
).as_str()
).execute(pool).await {
Ok(_) => {}
Err(error) => { panic!("[MySQL] Error: {error}"); }
}
}
false => {
match sqlx::query(
format!(
"CREATE TABLE `{}` (`{}` VARCHAR(36) NOT NULL, `{}` VARCHAR(40) NOT NULL, `{}` BIGINT UNSIGNED NOT NULL DEFAULT 0, `{}` BIGINT UNSIGNED NOT NULL DEFAULT 0, `{}` BIGINT UNSIGNED NOT NULL DEFAULT 0, `{}` TINYINT NOT NULL DEFAULT 0, `{}` INT NOT NULL DEFAULT 0, PRIMARY KEY (`{}`)) COLLATE='utf8mb4_general_ci'",
config.database_structure.clone().users.table_name,
config.database_structure.clone().users.column_uuid,
config.database_structure.clone().users.column_key,
config.database_structure.clone().users.column_uploaded,
config.database_structure.clone().users.column_downloaded,
config.database_structure.clone().users.column_completed,
config.database_structure.clone().users.column_active,
config.database_structure.clone().users.column_updated,
config.database_structure.clone().users.column_uuid
).as_str()
).execute(pool).await {
Ok(_) => {}
Err(error) => { panic!("[MySQL] Error: {error}"); }
}
}
}
}
false => {
match config.database_structure.clone().users.bin_type_key {
true => {
match sqlx::query(
format!(
"CREATE TABLE `{}` (`{}` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, `{}` BINARY(20) NOT NULL, `{}` BIGINT UNSIGNED NOT NULL DEFAULT 0, `{}` BIGINT UNSIGNED NOT NULL DEFAULT 0, `{}` BIGINT UNSIGNED NOT NULL DEFAULT 0, `{}` TINYINT NOT NULL DEFAULT 0, `{}` INT NOT NULL DEFAULT 0, PRIMARY KEY (`{}`)) COLLATE='utf8mb4_general_ci'",
config.database_structure.clone().users.table_name,
config.database_structure.clone().users.column_id,
config.database_structure.clone().users.column_key,
config.database_structure.clone().users.column_uploaded,
config.database_structure.clone().users.column_downloaded,
config.database_structure.clone().users.column_completed,
config.database_structure.clone().users.column_active,
config.database_structure.clone().users.column_updated,
config.database_structure.clone().users.column_id
).as_str()
).execute(pool).await {
Ok(_) => {}
Err(error) => { panic!("[MySQL] Error: {error}"); }
}
}
false => {
match sqlx::query(
format!(
"CREATE TABLE `{}` (`{}` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, `{}` VARCHAR(40) NOT NULL, `{}` BIGINT UNSIGNED NOT NULL DEFAULT 0, `{}` BIGINT UNSIGNED NOT NULL DEFAULT 0, `{}` BIGINT UNSIGNED NOT NULL DEFAULT 0, `{}` TINYINT NOT NULL DEFAULT 0, `{}` INT NOT NULL DEFAULT 0, PRIMARY KEY (`{}`)) COLLATE='utf8mb4_general_ci'",
config.database_structure.clone().users.table_name,
config.database_structure.clone().users.column_id,
config.database_structure.clone().users.column_key,
config.database_structure.clone().users.column_uploaded,
config.database_structure.clone().users.column_downloaded,
config.database_structure.clone().users.column_completed,
config.database_structure.clone().users.column_active,
config.database_structure.clone().users.column_updated,
config.database_structure.clone().users.column_id
).as_str()
).execute(pool).await {
Ok(_) => {}
Err(error) => { panic!("[MySQL] Error: {error}"); }
}
}
}
}
}
info!("[BOOT] Created the database and tables, restart without the parameter to start the app.");
task::sleep(Duration::from_secs(1)).await;
exit(0);
}
structure
}
#[tracing::instrument(level = "debug")]
pub async fn load_torrents(&self, tracker: Arc<TorrentTracker>) -> Result<(u64, u64), Error>
{
let mut start = 0u64;
let length = 100000u64;
let mut torrents = 0u64;
let mut completed = 0u64;
let structure = tracker.config.deref().clone().database_structure.clone().torrents;
loop {
let string_format = match tracker.config.deref().clone().database_structure.torrents.bin_type_infohash {
true => {
format!(
"SELECT HEX(`{}`) AS `{}`, `{}` FROM `{}` LIMIT {}, {}",
structure.column_infohash,
structure.column_infohash,
structure.column_completed,
structure.table_name,
start,
length
)
}
false => {
format!(
"SELECT `{}`, `{}` FROM `{}` LIMIT {}, {}",
structure.column_infohash,
structure.column_completed,
structure.table_name,
start,
length
)
}
};
let mut rows = sqlx::query(string_format.as_str()).fetch(&self.pool);
while let Some(result) = rows.try_next().await? {
let info_hash_data: &[u8] = result.get(structure.column_infohash.as_str());
let info_hash: [u8; 20] = <[u8; 20]>::try_from(hex::decode(info_hash_data).unwrap()[0..20].as_ref()).unwrap();
let completed_count: u64 = result.get(structure.column_completed.as_str());
tracker.add_torrent(
InfoHash(info_hash),
TorrentEntry {
seeds: BTreeMap::new(),
peers: BTreeMap::new(),
completed: completed_count,
updated: std::time::Instant::now()
}
);
torrents += 1;
completed += completed_count;
}
start += length;
if torrents < start {
break;
}
info!("[MySQL] Handled {torrents} torrents");
}
tracker.set_stats(StatsEvent::Completed, completed as i64);
info!("[MySQL] Loaded {torrents} torrents with {completed} completed");
Ok((torrents, completed))
}
#[tracing::instrument(level = "debug")]
pub async fn save_torrents(&self, tracker: Arc<TorrentTracker>, torrents: BTreeMap<InfoHash, (TorrentEntry, UpdatesAction)>) -> Result<(), Error>
{
let mut torrents_transaction = self.pool.begin().await?;
let mut torrents_handled_entries = 0u64;
let structure = tracker.config.deref().clone().database_structure.clone().torrents;
for (info_hash, (torrent_entry, updates_action)) in torrents.iter() {
torrents_handled_entries += 1;
match updates_action {
UpdatesAction::Remove => {
if tracker.config.deref().clone().database.remove_action {
let string_format = match tracker.config.deref().clone().database_structure.torrents.bin_type_infohash {
true => {
format!(
"DELETE FROM `{}` WHERE `{}`=UNHEX('{}')",
structure.table_name,
structure.column_infohash,
info_hash
)
}
false => {
format!(
"DELETE FROM `{}` WHERE `{}`='{}'",
structure.table_name,
structure.column_infohash,
info_hash
)
}
};
match sqlx::query(string_format.as_str()).execute(&mut *torrents_transaction).await {
Ok(_) => {}
Err(e) => {
error!("[MySQL] Error: {e}");
return Err(e);
}
}
}
}
UpdatesAction::Add | UpdatesAction::Update => {
match tracker.config.deref().clone().database.insert_vacant {
true => {
if tracker.config.deref().clone().database.update_peers {
let string_format = match tracker.config.deref().clone().database_structure.torrents.bin_type_infohash {
true => {
format!(
"INSERT INTO `{}` (`{}`, `{}`, `{}`) VALUES (UNHEX('{}'), {}, {}) ON DUPLICATE KEY UPDATE `{}` = VALUES(`{}`), `{}`=VALUES(`{}`)",
structure.table_name,
structure.column_infohash,
structure.column_seeds,
structure.column_peers,
info_hash,
torrent_entry.seeds.len(),
torrent_entry.peers.len(),
structure.column_seeds,
structure.column_seeds,
structure.column_peers,
structure.column_peers
)
}
false => {
format!(
"INSERT INTO `{}` (`{}`, `{}`, `{}`) VALUES ('{}', {}, {}) ON DUPLICATE KEY UPDATE `{}`=VALUES(`{}`), `{}`=VALUES(`{}`)",
structure.table_name,
structure.column_infohash,
structure.column_seeds,
structure.column_peers,
info_hash,
torrent_entry.seeds.len(),
torrent_entry.peers.len(),
structure.column_seeds,
structure.column_seeds,
structure.column_peers,
structure.column_peers
)
}
};
match sqlx::query(string_format.as_str()).execute(&mut *torrents_transaction).await {
Ok(_) => {}
Err(e) => {
error!("[MySQL] Error: {e}");
return Err(e);
}
}
}
if tracker.config.deref().clone().database.update_completed {
let string_format = match tracker.config.deref().clone().database_structure.torrents.bin_type_infohash {
true => {
format!(
"INSERT INTO `{}` (`{}`, `{}`) VALUES (UNHEX('{}'), {}) ON DUPLICATE KEY UPDATE `{}`=VALUES(`{}`)",
structure.table_name,
structure.column_infohash,
structure.column_completed,
info_hash,
torrent_entry.completed,
structure.column_completed,
structure.column_completed
)
}
false => {
format!(
"INSERT INTO `{}` (`{}`, `{}`) VALUES ('{}', {}) ON DUPLICATE KEY UPDATE `{}`=VALUES(`{}`)",
structure.table_name,
structure.column_infohash,
structure.column_completed,
info_hash,
torrent_entry.completed,
structure.column_completed,
structure.column_completed
)
}
};
match sqlx::query(string_format.as_str()).execute(&mut *torrents_transaction).await {
Ok(_) => {}
Err(e) => {
error!("[MySQL] Error: {e}");
return Err(e);
}
}
}
}
false => {
if tracker.config.deref().clone().database.update_peers {
let string_format = match tracker.config.deref().clone().database_structure.torrents.bin_type_infohash {
true => {
format!(
"UPDATE IGNORE `{}` SET `{}`={}, `{}`={} WHERE `{}`=UNHEX('{}')",
structure.table_name,
structure.column_seeds,
torrent_entry.seeds.len(),
structure.column_peers,
torrent_entry.peers.len(),
structure.column_infohash,
info_hash
)
}
false => {
format!(
"UPDATE IGNORE `{}` SET `{}`={}, `{}`={} WHERE `{}`='{}'",
structure.table_name,
structure.column_seeds,
torrent_entry.seeds.len(),
structure.column_peers,
torrent_entry.peers.len(),
structure.column_infohash,
info_hash
)
}
};
match sqlx::query(string_format.as_str()).execute(&mut *torrents_transaction).await {
Ok(_) => {}
Err(e) => {
error!("[MySQL] Error: {e}");
return Err(e);
}
}
}
if tracker.config.deref().clone().database.update_completed {
let string_format = match tracker.config.deref().clone().database_structure.torrents.bin_type_infohash {
true => {
format!(
"UPDATE IGNORE `{}` SET `{}`={} WHERE `{}`=UNHEX('{}')",
structure.table_name,
structure.column_completed,
torrent_entry.completed,
structure.column_infohash,
info_hash
)
}
false => {
format!(
"UPDATE IGNORE `{}` SET `{}`={} WHERE `{}`='{}'",
structure.table_name,
structure.column_completed,
torrent_entry.completed,
structure.column_infohash,
info_hash
)
}
};
match sqlx::query(string_format.as_str()).execute(&mut *torrents_transaction).await {
Ok(_) => {}
Err(e) => {
error!("[MySQL] Error: {e}");
return Err(e);
}
}
}
}
}
}
}
if (torrents_handled_entries as f64 / 1000f64).fract() == 0.0 || torrents.len() as u64 == torrents_handled_entries {
info!("[MySQL] Handled {torrents_handled_entries} torrents");
}
}
info!("[MySQL] Handled {torrents_handled_entries} torrents");
self.commit(torrents_transaction).await
}
#[tracing::instrument(level = "debug")]
pub async fn load_whitelist(&self, tracker: Arc<TorrentTracker>) -> Result<u64, Error>
{
let mut start = 0u64;
let length = 100000u64;
let mut hashes = 0u64;
let structure = tracker.config.deref().clone().database_structure.clone().whitelist;
loop {
let string_format = match tracker.config.deref().clone().database_structure.whitelist.bin_type_infohash {
true => {
format!(
"SELECT HEX(`{}`) AS `{}` FROM `{}` LIMIT {}, {}",
structure.column_infohash,
structure.column_infohash,
structure.table_name,
start,
length
)
}
false => {
format!(
"SELECT `{}` FROM `{}` LIMIT {}, {}",
structure.column_infohash,
structure.table_name,
start,
length
)
}
};
| rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | true |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/database/impls/database_connector.rs | src/database/impls/database_connector.rs | use std::collections::BTreeMap;
use std::sync::Arc;
use sqlx::Error;
use crate::config::structs::configuration::Configuration;
use crate::database::enums::database_drivers::DatabaseDrivers;
use crate::database::structs::database_connector::DatabaseConnector;
use crate::database::structs::database_connector_mysql::DatabaseConnectorMySQL;
use crate::database::structs::database_connector_pgsql::DatabaseConnectorPgSQL;
use crate::database::structs::database_connector_sqlite::DatabaseConnectorSQLite;
use crate::tracker::enums::updates_action::UpdatesAction;
use crate::tracker::structs::info_hash::InfoHash;
use crate::tracker::structs::torrent_entry::TorrentEntry;
use crate::tracker::structs::torrent_tracker::TorrentTracker;
use crate::tracker::structs::user_entry_item::UserEntryItem;
use crate::tracker::structs::user_id::UserId;
impl DatabaseConnector {
#[tracing::instrument(level = "debug")]
pub async fn new(config: Arc<Configuration>, create_database: bool) -> DatabaseConnector
{
match &config.database.engine {
DatabaseDrivers::sqlite3 => { DatabaseConnectorSQLite::database_connector(config, create_database).await }
DatabaseDrivers::mysql => { DatabaseConnectorMySQL::database_connector(config, create_database).await }
DatabaseDrivers::pgsql => { DatabaseConnectorPgSQL::database_connector(config, create_database).await }
}
}
#[tracing::instrument(level = "debug")]
pub async fn load_torrents(&self, tracker: Arc<TorrentTracker>) -> Result<(u64, u64), Error>
{
if self.engine.is_some() {
return match self.engine.clone().unwrap() {
DatabaseDrivers::sqlite3 => { self.sqlite.clone().unwrap().load_torrents(tracker.clone()).await }
DatabaseDrivers::mysql => { self.mysql.clone().unwrap().load_torrents(tracker.clone()).await }
DatabaseDrivers::pgsql => { self.pgsql.clone().unwrap().load_torrents(tracker.clone()).await }
};
}
Err(Error::RowNotFound)
}
#[tracing::instrument(level = "debug")]
pub async fn load_whitelist(&self, tracker: Arc<TorrentTracker>) -> Result<u64, Error>
{
if self.engine.is_some() {
return match self.engine.clone().unwrap() {
DatabaseDrivers::sqlite3 => { self.sqlite.clone().unwrap().load_whitelist(tracker.clone()).await }
DatabaseDrivers::mysql => { self.mysql.clone().unwrap().load_whitelist(tracker.clone()).await }
DatabaseDrivers::pgsql => { self.pgsql.clone().unwrap().load_whitelist(tracker.clone()).await }
};
}
Err(Error::RowNotFound)
}
#[tracing::instrument(level = "debug")]
pub async fn load_blacklist(&self, tracker: Arc<TorrentTracker>) -> Result<u64, Error>
{
if self.engine.is_some() {
return match self.engine.clone().unwrap() {
DatabaseDrivers::sqlite3 => { self.sqlite.clone().unwrap().load_blacklist(tracker.clone()).await }
DatabaseDrivers::mysql => { self.mysql.clone().unwrap().load_blacklist(tracker.clone()).await }
DatabaseDrivers::pgsql => { self.pgsql.clone().unwrap().load_blacklist(tracker.clone()).await }
};
}
Err(Error::RowNotFound)
}
#[tracing::instrument(level = "debug")]
pub async fn load_keys(&self, tracker: Arc<TorrentTracker>) -> Result<u64, Error>
{
if self.engine.is_some() {
return match self.engine.clone().unwrap() {
DatabaseDrivers::sqlite3 => { self.sqlite.clone().unwrap().load_keys(tracker.clone()).await }
DatabaseDrivers::mysql => { self.mysql.clone().unwrap().load_keys(tracker.clone()).await }
DatabaseDrivers::pgsql => { self.pgsql.clone().unwrap().load_keys(tracker.clone()).await }
};
}
Err(Error::RowNotFound)
}
#[tracing::instrument(level = "debug")]
pub async fn load_users(&self, tracker: Arc<TorrentTracker>) -> Result<u64, Error>
{
if self.engine.is_some() {
return match self.engine.clone().unwrap() {
DatabaseDrivers::sqlite3 => { self.sqlite.clone().unwrap().load_users(tracker.clone()).await }
DatabaseDrivers::mysql => { self.mysql.clone().unwrap().load_users(tracker.clone()).await }
DatabaseDrivers::pgsql => { self.pgsql.clone().unwrap().load_users(tracker.clone()).await }
};
}
Err(Error::RowNotFound)
}
#[tracing::instrument(level = "debug")]
pub async fn save_whitelist(&self, tracker: Arc<TorrentTracker>, whitelists: Vec<(InfoHash, UpdatesAction)>) -> Result<u64, Error>
{
if self.engine.is_some() {
return match self.engine.clone().unwrap() {
DatabaseDrivers::sqlite3 => { self.sqlite.clone().unwrap().save_whitelist(tracker.clone(), whitelists).await }
DatabaseDrivers::mysql => { self.mysql.clone().unwrap().save_whitelist(tracker.clone(), whitelists).await }
DatabaseDrivers::pgsql => { self.pgsql.clone().unwrap().save_whitelist(tracker.clone(), whitelists).await }
};
}
Err(Error::RowNotFound)
}
#[tracing::instrument(level = "debug")]
pub async fn save_blacklist(&self, tracker: Arc<TorrentTracker>, blacklists: Vec<(InfoHash, UpdatesAction)>) -> Result<u64, Error>
{
if self.engine.is_some() {
return match self.engine.clone().unwrap() {
DatabaseDrivers::sqlite3 => { self.sqlite.clone().unwrap().save_blacklist(tracker.clone(), blacklists).await }
DatabaseDrivers::mysql => { self.mysql.clone().unwrap().save_blacklist(tracker.clone(), blacklists).await }
DatabaseDrivers::pgsql => { self.pgsql.clone().unwrap().save_blacklist(tracker.clone(), blacklists).await }
};
}
Err(Error::RowNotFound)
}
#[tracing::instrument(level = "debug")]
pub async fn save_keys(&self, tracker: Arc<TorrentTracker>, keys: BTreeMap<InfoHash, (i64, UpdatesAction)>) -> Result<u64, Error>
{
if self.engine.is_some() {
return match self.engine.clone().unwrap() {
DatabaseDrivers::sqlite3 => { self.sqlite.clone().unwrap().save_keys(tracker.clone(), keys).await }
DatabaseDrivers::mysql => { self.mysql.clone().unwrap().save_keys(tracker.clone(), keys).await }
DatabaseDrivers::pgsql => { self.pgsql.clone().unwrap().save_keys(tracker.clone(), keys).await }
};
}
Err(Error::RowNotFound)
}
#[tracing::instrument(level = "debug")]
pub async fn save_torrents(&self, tracker: Arc<TorrentTracker>, torrents: BTreeMap<InfoHash, (TorrentEntry, UpdatesAction)>) -> Result<(), Error>
{
if self.engine.is_some() {
return match self.engine.clone().unwrap() {
DatabaseDrivers::sqlite3 => { self.sqlite.clone().unwrap().save_torrents(tracker.clone(), torrents).await }
DatabaseDrivers::mysql => { self.mysql.clone().unwrap().save_torrents(tracker.clone(), torrents).await }
DatabaseDrivers::pgsql => { self.pgsql.clone().unwrap().save_torrents(tracker.clone(), torrents).await }
};
}
Err(Error::RowNotFound)
}
#[tracing::instrument(level = "debug")]
pub async fn save_users(&self, tracker: Arc<TorrentTracker>, users: BTreeMap<UserId, (UserEntryItem, UpdatesAction)>) -> Result<(), Error>
{
if self.engine.is_some() {
return match self.engine.clone().unwrap() {
DatabaseDrivers::sqlite3 => { self.sqlite.clone().unwrap().save_users(tracker.clone(), users).await }
DatabaseDrivers::mysql => { self.mysql.clone().unwrap().save_users(tracker.clone(), users).await }
DatabaseDrivers::pgsql => { self.pgsql.clone().unwrap().save_users(tracker.clone(), users).await }
};
}
Err(Error::RowNotFound)
}
#[tracing::instrument(level = "debug")]
pub async fn reset_seeds_peers(&self, tracker: Arc<TorrentTracker>) -> Result<(), Error>
{
if self.engine.is_some() {
return match self.engine.clone().unwrap() {
DatabaseDrivers::sqlite3 => { self.sqlite.clone().unwrap().reset_seeds_peers(tracker.clone()).await }
DatabaseDrivers::mysql => { self.mysql.clone().unwrap().reset_seeds_peers(tracker.clone()).await }
DatabaseDrivers::pgsql => { self.pgsql.clone().unwrap().reset_seeds_peers(tracker.clone()).await }
};
}
Err(Error::RowNotFound)
}
} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/database/structs/database_connector_pgsql.rs | src/database/structs/database_connector_pgsql.rs | use sqlx::{Pool, Postgres};
#[derive(Debug, Clone)]
pub struct DatabaseConnectorPgSQL {
pub(crate) pool: Pool<Postgres>,
} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/database/structs/database_connector_sqlite.rs | src/database/structs/database_connector_sqlite.rs | use sqlx::{Pool, Sqlite};
#[derive(Debug, Clone)]
pub struct DatabaseConnectorSQLite {
pub(crate) pool: Pool<Sqlite>,
} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/database/structs/database_connector_mysql.rs | src/database/structs/database_connector_mysql.rs | use sqlx::{MySql, Pool};
#[derive(Debug, Clone)]
pub struct DatabaseConnectorMySQL {
pub(crate) pool: Pool<MySql>,
} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/database/structs/database_connector.rs | src/database/structs/database_connector.rs | use crate::database::enums::database_drivers::DatabaseDrivers;
use crate::database::structs::database_connector_mysql::DatabaseConnectorMySQL;
use crate::database::structs::database_connector_pgsql::DatabaseConnectorPgSQL;
use crate::database::structs::database_connector_sqlite::DatabaseConnectorSQLite;
#[derive(Debug, Clone)]
pub struct DatabaseConnector {
pub(crate) mysql: Option<DatabaseConnectorMySQL>,
pub(crate) sqlite: Option<DatabaseConnectorSQLite>,
pub(crate) pgsql: Option<DatabaseConnectorPgSQL>,
pub(crate) engine: Option<DatabaseDrivers>,
} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/database/enums/database_drivers.rs | src/database/enums/database_drivers.rs | use clap::ValueEnum;
use serde::{Deserialize, Serialize};
#[allow(non_camel_case_types)]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)]
pub enum DatabaseDrivers {
sqlite3,
mysql,
pgsql,
} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/http/http.rs | src/http/http.rs | use std::borrow::Cow;
use std::fs::File;
use std::future::Future;
use std::io::{BufReader, Write};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::process::exit;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
use actix_cors::Cors;
use actix_web::{App, http, HttpRequest, HttpResponse, HttpServer, web};
use actix_web::dev::ServerHandle;
use actix_web::http::header::ContentType;
use actix_web::web::{Data, ServiceConfig};
use bip_bencode::{ben_bytes, ben_int, ben_list, ben_map, BMutAccess};
use log::{debug, error, info};
use crate::common::common::parse_query;
use crate::common::structs::custom_error::CustomError;
use crate::config::structs::http_trackers_config::HttpTrackersConfig;
use crate::http::structs::http_service_data::HttpServiceData;
use crate::http::types::{HttpServiceQueryHashingMapErr, HttpServiceQueryHashingMapOk};
use crate::stats::enums::stats_event::StatsEvent;
use crate::tracker::enums::torrent_peers_type::TorrentPeersType;
use crate::tracker::structs::info_hash::InfoHash;
use crate::tracker::structs::torrent_tracker::TorrentTracker;
use crate::tracker::structs::user_id::UserId;
#[tracing::instrument(level = "debug")]
pub fn http_service_cors() -> Cors
{
Cors::default()
.send_wildcard()
.allowed_methods(vec!["GET"])
.allowed_headers(vec![http::header::X_FORWARDED_FOR, http::header::ACCEPT])
.allowed_header(http::header::CONTENT_TYPE)
.max_age(1)
}
#[tracing::instrument(level = "debug")]
pub fn http_service_routes(data: Arc<HttpServiceData>) -> Box<dyn Fn(&mut ServiceConfig)>
{
Box::new(move |cfg: &mut ServiceConfig| {
cfg.app_data(Data::new(data.clone()));
cfg.service(web::resource("/announce")
.route(web::get().to(http_service_announce))
);
cfg.service(web::resource("/{key}/announce")
.route(web::get().to(http_service_announce_key))
);
cfg.service(web::resource("/{key}/{userkey}announce")
.route(web::get().to(http_service_announce_userkey))
);
cfg.service(web::resource("/scrape")
.route(web::get().to(http_service_scrape))
);
cfg.service(web::resource("/{key}/scrape")
.route(web::get().to(http_service_scrape_key))
);
cfg.default_service(web::route().to(http_service_not_found));
})
}
#[tracing::instrument(level = "debug")]
pub async fn http_service(
addr: SocketAddr,
data: Arc<TorrentTracker>,
http_server_object: HttpTrackersConfig,
) -> (ServerHandle, impl Future<Output=Result<(), std::io::Error>>)
{
let keep_alive = http_server_object.keep_alive;
let request_timeout = http_server_object.request_timeout;
let disconnect_timeout = http_server_object.disconnect_timeout;
let worker_threads = http_server_object.threads as usize;
if http_server_object.ssl {
info!("[HTTPS] Starting server listener with SSL on {addr}");
if http_server_object.ssl_key.is_empty() || http_server_object.ssl_cert.is_empty() {
error!("[HTTPS] No SSL key or SSL certificate given, exiting...");
exit(1);
}
let key_file = &mut BufReader::new(match File::open(http_server_object.ssl_key.clone()) {
Ok(data) => { data }
Err(data) => {
sentry::capture_error(&data);
panic!("[HTTPS] SSL key unreadable: {data}");
}
});
let certs_file = &mut BufReader::new(match File::open(http_server_object.ssl_cert.clone()) {
Ok(data) => { data }
Err(data) => { panic!("[HTTPS] SSL cert unreadable: {data}"); }
});
let tls_certs = match rustls_pemfile::certs(certs_file).collect::<Result<Vec<_>, _>>() {
Ok(data) => { data }
Err(data) => { panic!("[HTTPS] SSL cert couldn't be extracted: {data}"); }
};
let tls_key = match rustls_pemfile::pkcs8_private_keys(key_file).next().unwrap() {
Ok(data) => { data }
Err(data) => { panic!("[HTTPS] SSL key couldn't be extracted: {data}"); }
};
let tls_config = match rustls::ServerConfig::builder().with_no_client_auth().with_single_cert(tls_certs, rustls::pki_types::PrivateKeyDer::Pkcs8(tls_key)) {
Ok(data) => { data }
Err(data) => { panic!("[HTTPS] SSL config couldn't be created: {data}"); }
};
let server = match data.config.sentry_config.clone().enabled {
true => {
HttpServer::new(move || {
App::new()
.wrap(sentry_actix::Sentry::new())
.wrap(http_service_cors())
.configure(http_service_routes(Arc::new(HttpServiceData {
torrent_tracker: data.clone(),
http_trackers_config: Arc::new(http_server_object.clone())
})))
})
.keep_alive(Duration::from_secs(keep_alive))
.client_request_timeout(Duration::from_secs(request_timeout))
.client_disconnect_timeout(Duration::from_secs(disconnect_timeout))
.workers(worker_threads)
.bind_rustls_0_23((addr.ip(), addr.port()), tls_config)
.unwrap()
.disable_signals()
.run()
}
false => {
HttpServer::new(move || {
App::new()
.wrap(http_service_cors())
.configure(http_service_routes(Arc::new(HttpServiceData {
torrent_tracker: data.clone(),
http_trackers_config: Arc::new(http_server_object.clone())
})))
})
.keep_alive(Duration::from_secs(keep_alive))
.client_request_timeout(Duration::from_secs(request_timeout))
.client_disconnect_timeout(Duration::from_secs(disconnect_timeout))
.workers(worker_threads)
.bind_rustls_0_23((addr.ip(), addr.port()), tls_config)
.unwrap()
.disable_signals()
.run()
}
};
return (server.handle(), server);
}
info!("[HTTP] Starting server listener on {addr}");
let server = match data.config.sentry_config.clone().enabled {
true => {
HttpServer::new(move || {
App::new()
.wrap(sentry_actix::Sentry::new())
.wrap(http_service_cors())
.configure(http_service_routes(Arc::new(HttpServiceData {
torrent_tracker: data.clone(),
http_trackers_config: Arc::new(http_server_object.clone())
})))
})
.keep_alive(Duration::from_secs(keep_alive))
.client_request_timeout(Duration::from_secs(request_timeout))
.client_disconnect_timeout(Duration::from_secs(disconnect_timeout))
.workers(worker_threads)
.bind((addr.ip(), addr.port()))
.unwrap()
.disable_signals()
.run()
}
false => {
HttpServer::new(move || {
App::new()
.wrap(http_service_cors())
.configure(http_service_routes(Arc::new(HttpServiceData {
torrent_tracker: data.clone(),
http_trackers_config: Arc::new(http_server_object.clone())
})))
})
.keep_alive(Duration::from_secs(keep_alive))
.client_request_timeout(Duration::from_secs(request_timeout))
.client_disconnect_timeout(Duration::from_secs(disconnect_timeout))
.workers(worker_threads)
.bind((addr.ip(), addr.port()))
.unwrap()
.disable_signals()
.run()
}
};
(server.handle(), server)
}
#[tracing::instrument(level = "debug")]
pub async fn http_service_announce_key(request: HttpRequest, path: web::Path<String>, data: Data<Arc<HttpServiceData>>) -> HttpResponse
{
let ip = match http_validate_ip(request.clone(), data.clone()).await {
Ok(ip) => {
http_stat_update(ip, data.torrent_tracker.clone(), StatsEvent::Tcp4AnnouncesHandled, StatsEvent::Tcp6AnnouncesHandled, 1);
ip
},
Err(result) => { return result; }
};
if data.torrent_tracker.config.tracker_config.clone().keys_enabled {
let key = path.clone();
let key_check = http_service_check_key_validation(data.torrent_tracker.clone(), key).await;
if let Some(value) = key_check {
http_stat_update(ip, data.torrent_tracker.clone(), StatsEvent::Tcp4Failure, StatsEvent::Tcp6Failure, 1);
return value;
}
}
if data.torrent_tracker.config.tracker_config.clone().users_enabled && !data.torrent_tracker.config.tracker_config.clone().keys_enabled {
let user_key = path.clone();
let user_key_check = http_service_check_user_key_validation(data.torrent_tracker.clone(), user_key.clone()).await;
if user_key_check.is_none() {
return http_service_announce_handler(request, ip, data.torrent_tracker.clone(), Some(http_service_decode_hex_user_id(user_key.clone()).await.unwrap())).await;
}
}
http_service_announce_handler(request, ip, data.torrent_tracker.clone(), None).await
}
#[tracing::instrument(level = "debug")]
pub async fn http_service_announce_userkey(request: HttpRequest, path: web::Path<(String, String)>, data: Data<Arc<HttpServiceData>>) -> HttpResponse
{
let ip = match http_validate_ip(request.clone(), data.clone()).await {
Ok(ip) => {
http_stat_update(ip, data.torrent_tracker.clone(), StatsEvent::Tcp4AnnouncesHandled, StatsEvent::Tcp6AnnouncesHandled, 1);
ip
},
Err(result) => { return result; }
};
if data.torrent_tracker.config.tracker_config.clone().keys_enabled {
let key = path.clone().0;
let key_check = http_service_check_key_validation(data.torrent_tracker.clone(), key).await;
if let Some(value) = key_check {
http_stat_update(ip, data.torrent_tracker.clone(), StatsEvent::Tcp4Failure, StatsEvent::Tcp6Failure, 1);
return value;
}
}
if data.torrent_tracker.config.tracker_config.clone().users_enabled {
let user_key = path.clone().1;
let user_key_check = http_service_check_user_key_validation(data.torrent_tracker.clone(), user_key.clone()).await;
if user_key_check.is_none() {
return http_service_announce_handler(request, ip, data.torrent_tracker.clone(), Some(http_service_decode_hex_user_id(user_key.clone()).await.unwrap())).await;
}
}
http_service_announce_handler(request, ip, data.torrent_tracker.clone(), None).await
}
#[tracing::instrument(level = "debug")]
pub async fn http_service_announce(request: HttpRequest, data: Data<Arc<HttpServiceData>>) -> HttpResponse
{
let ip = match http_validate_ip(request.clone(), data.clone()).await {
Ok(ip) => {
http_stat_update(ip, data.torrent_tracker.clone(), StatsEvent::Tcp4AnnouncesHandled, StatsEvent::Tcp6AnnouncesHandled, 1);
ip
},
Err(result) => {
return result;
}
};
if data.torrent_tracker.config.tracker_config.clone().keys_enabled {
http_stat_update(ip, data.torrent_tracker.clone(), StatsEvent::Tcp4Failure, StatsEvent::Tcp6Failure, 1);
return HttpResponse::Ok().content_type(ContentType::plaintext()).body(ben_map!{
"failure reason" => ben_bytes!("missing key")
}.encode());
}
http_service_announce_handler(request, ip, data.torrent_tracker.clone(), None).await
}
#[tracing::instrument(level = "debug")]
pub async fn http_service_announce_handler(request: HttpRequest, ip: IpAddr, data: Arc<TorrentTracker>, user_key: Option<UserId>) -> HttpResponse
{
let query_map_result = parse_query(Some(request.query_string().to_string()));
let query_map = match http_service_query_hashing(query_map_result) {
Ok(result) => { result }
Err(err) => {
http_stat_update(ip, data.clone(), StatsEvent::Tcp4Failure, StatsEvent::Tcp6Failure, 1);
return err;
}
};
let announce = data.validate_announce(ip, query_map).await;
let announce_unwrapped = match announce {
Ok(result) => { result }
Err(e) => {
return HttpResponse::Ok().content_type(ContentType::plaintext()).body(ben_map! {
"failure reason" => ben_bytes!(e.to_string())
}.encode());
}
};
if data.config.tracker_config.clone().whitelist_enabled && !data.check_whitelist(announce_unwrapped.info_hash) {
return HttpResponse::Ok().content_type(ContentType::plaintext()).body(ben_map! {
"failure reason" => ben_bytes!("unknown info_hash")
}.encode());
}
if data.config.tracker_config.clone().blacklist_enabled && data.check_blacklist(announce_unwrapped.info_hash) {
return HttpResponse::Ok().content_type(ContentType::plaintext()).body(ben_map! {
"failure reason" => ben_bytes!("forbidden info_hash")
}.encode());
}
let (_torrent_peer, torrent_entry) = match data.handle_announce(data.clone(), announce_unwrapped.clone(), user_key).await {
Ok(result) => { result }
Err(e) => {
http_stat_update(ip, data.clone(), StatsEvent::Tcp4Failure, StatsEvent::Tcp6Failure, 1);
return HttpResponse::Ok().content_type(ContentType::plaintext()).body(ben_map! {
"failure reason" => ben_bytes!(e.to_string())
}.encode());
}
};
if announce_unwrapped.compact {
let mut peers_list: Vec<u8> = Vec::new();
return match ip {
IpAddr::V4(_) => {
if announce_unwrapped.left != 0 {
let seeds = data.get_peers(
&torrent_entry.seeds,
TorrentPeersType::IPv4,
Some(ip),
72
);
for (_, torrent_peer) in seeds.iter() {
let peer_pre_parse = match torrent_peer.peer_addr.ip().to_string().parse::<Ipv4Addr>() {
Ok(ip) => { ip }
Err(e) => {
error!("[IPV4 Error] {} - {}", torrent_peer.peer_addr.ip(), e);
return HttpResponse::Ok().content_type(ContentType::plaintext()).body(ben_map! {
"failure reason" => ben_bytes!(e.to_string())
}.encode());
}
};
let _ = peers_list.write(&u32::from(peer_pre_parse).to_be_bytes());
peers_list.write_all(&announce_unwrapped.clone().port.to_be_bytes()).unwrap();
}
}
if peers_list.len() != 72 {
let peers = data.get_peers(
&torrent_entry.peers,
TorrentPeersType::IPv4,
Some(ip),
72
);
for (_, torrent_peer) in peers.iter() {
if peers_list.len() != 72 {
let peer_pre_parse = match torrent_peer.peer_addr.ip().to_string().parse::<Ipv4Addr>() {
Ok(ip) => { ip }
Err(e) => {
error!("[IPV4 Error] {} - {}", torrent_peer.peer_addr.ip(), e);
return HttpResponse::Ok().content_type(ContentType::plaintext()).body(ben_map! {
"failure reason" => ben_bytes!(e.to_string())
}.encode());
}
};
let _ = peers_list.write(&u32::from(peer_pre_parse).to_be_bytes());
peers_list.write_all(&announce_unwrapped.clone().port.to_be_bytes()).unwrap();
continue;
}
break;
}
}
HttpResponse::Ok().content_type(ContentType::plaintext()).body(ben_map! {
"interval" => ben_int!(data.config.tracker_config.clone().request_interval as i64),
"min interval" => ben_int!(data.config.tracker_config.clone().request_interval_minimum as i64),
"complete" => ben_int!(torrent_entry.seeds.len() as i64),
"incomplete" => ben_int!(torrent_entry.clone().peers.len() as i64),
"downloaded" => ben_int!(torrent_entry.completed as i64),
"peers" => ben_bytes!(peers_list)
}.encode())
}
IpAddr::V6(_) => {
if announce_unwrapped.left != 0 {
let seeds = data.get_peers(
&torrent_entry.seeds,
TorrentPeersType::IPv6,
Some(ip),
72
);
for (_, torrent_peer) in seeds.iter() {
let peer_pre_parse = match torrent_peer.peer_addr.ip().to_string().parse::<Ipv6Addr>() {
Ok(ip) => { ip }
Err(e) => {
error!("[IPV6 Error] {} - {}", torrent_peer.peer_addr.ip(), e);
return HttpResponse::Ok().content_type(ContentType::plaintext()).body(ben_map! {
"failure reason" => ben_bytes!(e.to_string())
}.encode());
}
};
let _ = peers_list.write(&u128::from(peer_pre_parse).to_be_bytes());
peers_list.write_all(&announce_unwrapped.clone().port.to_be_bytes()).unwrap();
}
}
if peers_list.len() != 72 {
let peers = data.get_peers(
&torrent_entry.peers,
TorrentPeersType::IPv6,
Some(ip),
72
);
for (_, torrent_peer) in peers.iter() {
if peers_list.len() != 72 {
let peer_pre_parse = match torrent_peer.peer_addr.ip().to_string().parse::<Ipv6Addr>() {
Ok(ip) => { ip }
Err(e) => {
error!("[IPV6 Error] {} - {}", torrent_peer.peer_addr.ip(), e);
return HttpResponse::Ok().content_type(ContentType::plaintext()).body(ben_map! {
"failure reason" => ben_bytes!(e.to_string())
}.encode());
}
};
let _ = peers_list.write(&u128::from(peer_pre_parse).to_be_bytes());
peers_list.write_all(&announce_unwrapped.clone().port.to_be_bytes()).unwrap();
continue;
}
break;
}
}
HttpResponse::Ok().content_type(ContentType::plaintext()).body(ben_map! {
"interval" => ben_int!(data.config.tracker_config.clone().request_interval as i64),
"min interval" => ben_int!(data.config.tracker_config.clone().request_interval_minimum as i64),
"complete" => ben_int!(torrent_entry.seeds.len() as i64),
"incomplete" => ben_int!(torrent_entry.peers.len() as i64),
"downloaded" => ben_int!(torrent_entry.completed as i64),
"peers6" => ben_bytes!(peers_list)
}.encode())
}
}
}
let mut peers_list = ben_list!();
let peers_list_mut = peers_list.list_mut().unwrap();
match ip {
IpAddr::V4(_) => {
if announce_unwrapped.left != 0 {
let seeds = data.get_peers(
&torrent_entry.seeds,
TorrentPeersType::IPv4,
Some(ip),
72
);
for (peer_id, torrent_peer) in seeds.iter() {
peers_list_mut.push(ben_map! {
"peer id" => ben_bytes!(peer_id.to_string()),
"ip" => ben_bytes!(torrent_peer.peer_addr.ip().to_string()),
"port" => ben_int!(torrent_peer.peer_addr.port() as i64)
});
}
}
if peers_list_mut.len() != 72 {
let peers = data.get_peers(
&torrent_entry.peers,
TorrentPeersType::IPv4,
Some(ip),
72
);
for (peer_id, torrent_peer) in peers.iter() {
if peers_list_mut.len() != 72 {
peers_list_mut.push(ben_map! {
"peer id" => ben_bytes!(peer_id.to_string()),
"ip" => ben_bytes!(torrent_peer.peer_addr.ip().to_string()),
"port" => ben_int!(torrent_peer.peer_addr.port() as i64)
});
continue;
}
break;
}
}
HttpResponse::Ok().content_type(ContentType::plaintext()).body(ben_map! {
"interval" => ben_int!(data.config.tracker_config.clone().request_interval as i64),
"min interval" => ben_int!(data.config.tracker_config.clone().request_interval_minimum as i64),
"complete" => ben_int!(torrent_entry.seeds.len() as i64),
"incomplete" => ben_int!(torrent_entry.peers.len() as i64),
"downloaded" => ben_int!(torrent_entry.completed as i64),
"peers" => peers_list
}.encode())
}
IpAddr::V6(_) => {
if announce_unwrapped.left != 0 {
let seeds = data.get_peers(
&torrent_entry.seeds,
TorrentPeersType::IPv6,
Some(ip),
72
);
for (peer_id, torrent_peer) in seeds.iter() {
peers_list_mut.push(ben_map! {
"peer id" => ben_bytes!(peer_id.to_string()),
"ip" => ben_bytes!(torrent_peer.peer_addr.ip().to_string()),
"port" => ben_int!(torrent_peer.peer_addr.port() as i64)
});
}
}
if peers_list_mut.len() != 72 {
let peers = data.get_peers(
&torrent_entry.peers,
TorrentPeersType::IPv6,
Some(ip),
72
);
for (peer_id, torrent_peer) in peers.iter() {
if peers_list_mut.len() != 72 {
peers_list_mut.push(ben_map! {
"peer id" => ben_bytes!(peer_id.to_string()),
"ip" => ben_bytes!(torrent_peer.peer_addr.ip().to_string()),
"port" => ben_int!(torrent_peer.peer_addr.port() as i64)
});
continue;
}
break;
}
}
HttpResponse::Ok().content_type(ContentType::plaintext()).body(ben_map! {
"interval" => ben_int!(data.config.tracker_config.clone().request_interval as i64),
"min interval" => ben_int!(data.config.tracker_config.clone().request_interval_minimum as i64),
"complete" => ben_int!(torrent_entry.seeds.len() as i64),
"incomplete" => ben_int!(torrent_entry.peers.len() as i64),
"downloaded" => ben_int!(torrent_entry.completed as i64),
"peers6" => peers_list
}.encode())
}
}
}
#[tracing::instrument(level = "debug")]
pub async fn http_service_scrape_key(request: HttpRequest, path: web::Path<String>, data: Data<Arc<HttpServiceData>>) -> HttpResponse
{
let ip = match http_validate_ip(request.clone(), data.clone()).await {
Ok(ip) => {
match ip.is_ipv4() {
true => {
data.torrent_tracker.update_stats(StatsEvent::Tcp4ScrapesHandled, 1);
}
false => {
data.torrent_tracker.update_stats(StatsEvent::Tcp6ScrapesHandled, 1);
}
}
ip
},
Err(result) => {
return result;
}
};
debug!("[DEBUG] Request from {ip}: Scrape with Key");
if data.torrent_tracker.config.tracker_config.clone().keys_enabled {
let key = path.into_inner();
let key_check = http_service_check_key_validation(data.torrent_tracker.clone(), key).await;
if let Some(value) = key_check { return value; }
}
http_service_scrape_handler(request, ip, data.torrent_tracker.clone()).await
}
#[tracing::instrument(level = "debug")]
pub async fn http_service_scrape_handler(request: HttpRequest, ip: IpAddr, data: Arc<TorrentTracker>) -> HttpResponse
{
let query_map_result = parse_query(Some(request.query_string().to_string()));
let query_map = match http_service_query_hashing(query_map_result) {
Ok(result) => { result }
Err(err) => {
http_stat_update(ip, data.clone(), StatsEvent::Tcp4Failure, StatsEvent::Tcp6Failure, 1);
return err;
}
};
let scrape = data.validate_scrape(query_map).await;
if scrape.is_err() {
http_stat_update(ip, data.clone(), StatsEvent::Tcp4Failure, StatsEvent::Tcp6Failure, 1);
return HttpResponse::Ok().content_type(ContentType::plaintext()).body(ben_map! {
"failure reason" => ben_bytes!(scrape.unwrap_err().to_string())
}.encode());
}
match scrape.as_ref() {
Ok(e) => {
let data_scrape = data.handle_scrape(data.clone(), e.clone()).await;
let mut scrape_list = ben_map!();
let scrape_list_mut = scrape_list.dict_mut().unwrap();
for (info_hash, torrent_entry) in data_scrape.iter() {
scrape_list_mut.insert(Cow::from(info_hash.0.to_vec()), ben_map! {
"complete" => ben_int!(torrent_entry.seeds.len() as i64),
"downloaded" => ben_int!(torrent_entry.completed as i64),
"incomplete" => ben_int!(torrent_entry.peers.len() as i64)
});
}
HttpResponse::Ok().content_type(ContentType::plaintext()).body(ben_map! {
"interval" => ben_int!(data.config.tracker_config.clone().request_interval as i64),
"min interval" => ben_int!(data.config.tracker_config.clone().request_interval_minimum as i64),
"files" => scrape_list
}.encode())
}
Err(e) => {
http_stat_update(ip, data.clone(), StatsEvent::Tcp4Failure, StatsEvent::Tcp6Failure, 1);
HttpResponse::Ok().content_type(ContentType::plaintext()).body(ben_map! {
"failure reason" => ben_bytes!(e.to_string())
}.encode())
}
}
}
#[tracing::instrument(level = "debug")]
pub async fn http_service_scrape(request: HttpRequest, data: Data<Arc<HttpServiceData>>) -> HttpResponse
{
let ip = match http_validate_ip(request.clone(), data.clone()).await {
Ok(ip) => {
match ip.is_ipv4() {
true => {
data.torrent_tracker.update_stats(StatsEvent::Tcp4ScrapesHandled, 1);
}
false => {
data.torrent_tracker.update_stats(StatsEvent::Tcp6ScrapesHandled, 1);
}
}
ip
},
Err(result) => {
return result;
}
};
debug!("[DEBUG] Request from {ip}: Scrape");
http_service_scrape_handler(request, ip, data.torrent_tracker.clone()).await
}
#[tracing::instrument(level = "debug")]
pub async fn http_service_not_found(request: HttpRequest, data: Data<Arc<HttpServiceData>>) -> HttpResponse
{
let ip = match http_validate_ip(request.clone(), data.clone()).await {
Ok(ip) => {
match ip.is_ipv4() {
true => { data.torrent_tracker.update_stats(StatsEvent::Tcp4NotFound, 1); }
false => { data.torrent_tracker.update_stats(StatsEvent::Tcp6NotFound, 1); }
}
ip
},
Err(result) => {
return result;
}
};
debug!("[DEBUG] Request from {ip}: 404 Not Found");
HttpResponse::NotFound().content_type(ContentType::plaintext()).body(std::str::from_utf8(&ben_map! {
"failure reason" => ben_bytes!("unknown request")
}.encode()).unwrap().to_string())
}
#[tracing::instrument(level = "debug")]
pub async fn http_service_stats_log(ip: IpAddr, tracker: Arc<TorrentTracker>)
{
match ip.is_ipv4() {
true => { tracker.update_stats(StatsEvent::Tcp4ConnectionsHandled, 1); }
false => { tracker.update_stats(StatsEvent::Tcp6ConnectionsHandled, 1); }
}
}
#[tracing::instrument(level = "debug")]
pub async fn http_service_decode_hex_hash(hash: String) -> Result<InfoHash, HttpResponse>
{
match hex::decode(hash) {
Ok(hash_result) => { Ok(InfoHash(<[u8; 20]>::try_from(hash_result[0..20].as_ref()).unwrap())) }
Err(_) => {
Err(HttpResponse::InternalServerError().content_type(ContentType::plaintext()).body(std::str::from_utf8(&ben_map! {
"failure reason" => ben_bytes!("unable to decode hex string")
}.encode()).unwrap().to_string()))
}
}
}
#[tracing::instrument(level = "debug")]
pub async fn http_service_decode_hex_user_id(hash: String) -> Result<UserId, HttpResponse>
{
match hex::decode(hash) {
Ok(hash_result) => { Ok(UserId(<[u8; 20]>::try_from(hash_result[0..20].as_ref()).unwrap())) }
Err(_) => {
Err(HttpResponse::InternalServerError().content_type(ContentType::plaintext()).body(std::str::from_utf8(&ben_map! {
"failure reason" => ben_bytes!("unable to decode hex string")
}.encode()).unwrap().to_string()))
}
}
}
#[tracing::instrument(level = "debug")]
pub async fn http_service_retrieve_remote_ip(request: HttpRequest, data: Arc<HttpTrackersConfig>) -> Result<IpAddr, ()>
{
let origin_ip = match request.peer_addr() {
None => {
return Err(());
}
Some(ip) => {
ip.ip()
}
};
match request.headers().get(data.real_ip.clone()) {
Some(header) => {
if header.to_str().is_ok() {
if let Ok(ip) = IpAddr::from_str(header.to_str().unwrap()) {
Ok(ip)
} else {
Err(())
}
} else {
Err(())
}
}
None => {
Ok(origin_ip)
}
}
}
#[tracing::instrument(level = "debug")]
pub async fn http_validate_ip(request: HttpRequest, data: Data<Arc<HttpServiceData>>) -> Result<IpAddr, HttpResponse>
{
match http_service_retrieve_remote_ip(request.clone(), data.http_trackers_config.clone()).await {
Ok(ip) => {
http_service_stats_log(ip, data.torrent_tracker.clone()).await;
Ok(ip)
}
Err(_) => {
Err(HttpResponse::Ok().content_type(ContentType::plaintext()).body(ben_map! {
"failure reason" => ben_bytes!("unknown origin ip")
}.encode()))
}
}
}
#[tracing::instrument(level = "debug")]
| rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | true |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/http/structs.rs | src/http/structs.rs | pub mod http_service_data; | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/http/enums.rs | src/http/enums.rs | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false | |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/http/types.rs | src/http/types.rs | use std::collections::HashMap;
use actix_web::HttpResponse;
pub type HttpServiceQueryHashingMapOk = HashMap<String, Vec<Vec<u8>>>;
pub type HttpServiceQueryHashingMapErr = HttpResponse; | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/http/mod.rs | src/http/mod.rs | pub mod enums;
pub mod structs;
pub mod impls;
pub mod types;
#[allow(clippy::module_inception)]
pub mod http; | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/http/impls.rs | src/http/impls.rs | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false | |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/http/structs/http_service_data.rs | src/http/structs/http_service_data.rs | use std::sync::Arc;
use crate::config::structs::http_trackers_config::HttpTrackersConfig;
use crate::tracker::structs::torrent_tracker::TorrentTracker;
#[derive(Debug)]
pub struct HttpServiceData {
pub(crate) torrent_tracker: Arc<TorrentTracker>,
pub(crate) http_trackers_config: Arc<HttpTrackersConfig>
} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
shekohex/allo-isolate | https://github.com/shekohex/allo-isolate/blob/9134004487720ca3ae3457da84933c4337038f0e/src/catch_unwind.rs | src/catch_unwind.rs | use core::future::Future;
use pin_project::pin_project;
use std::{
any::Any,
panic,
pin::Pin,
task::{Context, Poll},
};
#[pin_project]
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct CatchUnwind<F: Future>(#[pin] F);
impl<F: Future> CatchUnwind<F> {
pub fn new(f: F) -> Self {
Self(f)
}
}
impl<F> Future for CatchUnwind<F>
where
F: Future,
{
type Output = Result<F::Output, Box<dyn Any + Send>>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
let f = this.0;
panic::catch_unwind(panic::AssertUnwindSafe(|| f.poll(cx)))?.map(Ok)
}
}
| rust | Apache-2.0 | 9134004487720ca3ae3457da84933c4337038f0e | 2026-01-04T20:25:25.259611Z | false |
shekohex/allo-isolate | https://github.com/shekohex/allo-isolate/blob/9134004487720ca3ae3457da84933c4337038f0e/src/dart_array.rs | src/dart_array.rs | //! A FFI Compatible Array for Dart
use core::slice;
use std::mem::ManuallyDrop;
use ffi::{DartCObject, DartCObjectType, DartCObjectValue, DartNativeArray};
use crate::{ffi, IntoDart};
/// A wrapper around a list of `DartCObject` that will be dropped after been
/// sent to dart vm.
#[derive(Debug, Clone)]
pub struct DartArray {
inner: Box<[*mut DartCObject]>,
}
impl<I, T: IntoDart> From<I> for DartArray
where
I: Iterator<Item = T>,
{
fn from(iter: I) -> Self {
let vec: Vec<_> = iter
// convert them to dart objects
.map(IntoDart::into_dart)
// box them to be transferred to dart
.map(Box::new)
// as pointers
.map(Box::into_raw)
// then collect everything
.collect();
let inner = vec.into_boxed_slice();
Self { inner }
}
}
impl IntoDart for DartArray {
fn into_dart(self) -> ffi::DartCObject {
let mut s = ManuallyDrop::new(self);
// we drop vec when DartCObject get dropped
let (data, len) = (s.inner.as_mut_ptr(), s.inner.len());
let array = DartNativeArray {
length: len as isize,
values: data,
};
DartCObject {
ty: DartCObjectType::DartArray,
value: DartCObjectValue { as_array: array },
}
}
}
impl From<DartNativeArray> for DartArray {
fn from(arr: DartNativeArray) -> Self {
let inner = unsafe {
let slice =
slice::from_raw_parts_mut(arr.values, arr.length as usize);
Box::from_raw(slice)
};
Self { inner }
}
}
impl Drop for DartArray {
fn drop(&mut self) {
for v in self.inner.iter() {
unsafe {
let _ = Box::from_raw(*v);
}
}
}
}
| rust | Apache-2.0 | 9134004487720ca3ae3457da84933c4337038f0e | 2026-01-04T20:25:25.259611Z | false |
shekohex/allo-isolate | https://github.com/shekohex/allo-isolate/blob/9134004487720ca3ae3457da84933c4337038f0e/src/lib.rs | src/lib.rs | #![deny(
missing_docs,
missing_debug_implementations,
missing_copy_implementations,
elided_lifetimes_in_paths,
rust_2018_idioms,
clippy::fallible_impl_from,
clippy::missing_const_for_fn
)]
#![doc(html_logo_url = "https://avatars0.githubusercontent.com/u/55122894")]
//! Allo Isolate
//! Run Multithreaded Rust along with Dart VM (in isolate).
//!
//! Since you can't call into dart from other threads other than the main
//! thread, that holds our rust code from beaing multithreaded, the way that can be done is using Dart [`Isolate`](https://api.dart.dev/stable/2.8.4/dart-isolate/Isolate-class.html)
//! by creating an isolate, send its [`NativePort`](https://api.dart.dev/stable/2.8.4/dart-ffi/NativePort.html) to Rust side, then rust is freely could run and send the result back on that port.
//!
//! Interacting with Dart VM directly isn't that easy, that is why we created
//! that library, it provides [`IntoDart`] trait to convert between Rust data
//! types and Dart Types, and by default it is implemented for all common rust
//! types.
//!
//! ### Example
//!
//! See [`flutterust`](https://github.com/shekohex/flutterust/tree/master/native/scrap-ffi) and how we used it in the `scrap` package to create a webscrapper using Rust and Flutter.
//!
//! ### Cargo Features
//! - `catch-unwind`: Unwind the Rust stack after a panic, instead of stopping the thread.
//! - `zero-copy`: Zero copy typed data by default without explicit `ZeroCopyBuffer`.
//! For example, `Vec<u8>` in Rust will be moved to the Dart side
//! as `UInt8List` without any copy operation,
//! which can have performance benefits.
/// Holds the Raw Dart FFI Types Required to send messages to Isolate
use atomic::Atomic;
use std::{future::Future, sync::atomic::Ordering};
pub use ffi::ZeroCopyBuffer;
pub use into_dart::{IntoDart, IntoDartExceptPrimitive};
mod dart_array;
mod into_dart;
mod into_dart_extra;
#[cfg(feature = "catch-unwind")]
mod catch_unwind;
#[cfg(feature = "chrono")]
mod chrono;
#[cfg(feature = "uuid")]
mod uuid;
pub mod ffi;
// Please don't use `AtomicPtr` here
// see https://github.com/rust-lang/rfcs/issues/2481
static POST_COBJECT: Atomic<Option<ffi::DartPostCObjectFnType>> =
Atomic::new(None);
/// Stores the function pointer of `Dart_PostCObject`, this only should be
/// called once at the start up of the Dart/Flutter Application. it is exported
/// and marked as `#[no_mangle]`.
///
/// you could use it from Dart as following:
///
/// #### Safety
/// This function should only be called once at the start up of the Dart
/// application.
///
/// ### Example
/// ```dart,ignore
/// import 'dart:ffi';
///
/// typedef dartPostCObject = Pointer Function(
/// Pointer<NativeFunction<Int8 Function(Int64,
/// Pointer<Dart_CObject>)>>);
///
/// // assumes that _dl is the `DynamicLibrary`
/// final storeDartPostCObject =
/// _dl.lookupFunction<dartPostCObject, dartPostCObject>(
/// 'store_dart_post_cobject',
/// );
///
/// // then later call
///
/// storeDartPostCObject(NativeApi.postCObject);
/// ```
#[no_mangle]
pub unsafe extern "C" fn store_dart_post_cobject(
ptr: ffi::DartPostCObjectFnType,
) {
POST_COBJECT.store(Some(ptr), Ordering::Relaxed);
}
/// Simple wrapper around the Dart Isolate Port, nothing
/// else.
#[derive(Copy, Clone, Debug)]
pub struct Isolate {
port: i64,
}
impl Isolate {
/// Create a new `Isolate` with a port obtained from Dart VM side.
///
/// #### Example
/// this a non realistic example lol :D
/// ```rust
/// # use allo_isolate::Isolate;
/// let isolate = Isolate::new(42);
/// ```
pub const fn new(port: i64) -> Self {
Self { port }
}
/// Post an object to the [`Isolate`] over the port
/// Object must implement [`IntoDart`].
///
/// returns `true` if the message posted successfully, otherwise `false`
///
/// #### Safety
/// This assumes that you called [`store_dart_post_cobject`] and we have
/// access to the `Dart_PostCObject` function pointer also, we do check
/// if it is not null.
///
/// #### Example
/// ```rust
/// # use allo_isolate::Isolate;
/// let isolate = Isolate::new(42);
/// isolate.post("Hello Dart !");
/// ```
pub fn post(&self, msg: impl IntoDart) -> bool {
if let Some(func) = POST_COBJECT.load(Ordering::Relaxed) {
unsafe {
let mut msg = msg.into_dart();
// Send the message
let result = func(self.port, &mut msg);
if !result {
ffi::run_destructors(&msg);
}
// I like that dance haha
result
}
} else {
false
}
}
/// Consumes `Self`, Runs the task, await for the result and then post it
/// to the [`Isolate`] over the port
/// Result must implement [`IntoDart`].
///
/// returns `true` if the message posted successfully, otherwise `false`
///
/// #### Safety
/// This assumes that you called [`store_dart_post_cobject`] and we have
/// access to the `Dart_PostCObject` function pointer also, we do check
/// if it is not null.
///
/// #### Example
/// ```rust,ignore
/// # use allo_isolate::Isolate;
/// use async_std::task;
/// let isolate = Isolate::new(42);
/// task::spawn(isolate.task(async { 1 + 2 }));
/// ```
pub async fn task<T, R>(self, t: T) -> bool
where
T: Future<Output = R> + Send + 'static,
R: Send + IntoDart + 'static,
{
self.post(t.await)
}
/// Similar to [`Isolate::task`] but with more logic to catch any panic and
/// report it back
#[cfg(feature = "catch-unwind")]
pub async fn catch_unwind<T, R>(
self,
t: T,
) -> Result<bool, Box<dyn std::any::Any + Send>>
where
T: Future<Output = R> + Send + 'static,
R: Send + IntoDart + 'static,
{
catch_unwind::CatchUnwind::new(t)
.await
.map(|msg| Ok(self.post(msg)))?
}
}
| rust | Apache-2.0 | 9134004487720ca3ae3457da84933c4337038f0e | 2026-01-04T20:25:25.259611Z | false |
shekohex/allo-isolate | https://github.com/shekohex/allo-isolate/blob/9134004487720ca3ae3457da84933c4337038f0e/src/into_dart_extra.rs | src/into_dart_extra.rs | //! The conversions in this file is not lossless. On the contrary, it is lossy
//! and the type that Dart receives will not be the same as the type you send in
//! Rust. For example, numeric types can become String.
use crate::{ffi::*, IntoDart};
impl IntoDart for i8 {
fn into_dart(self) -> DartCObject {
(self as i32).into_dart()
}
}
impl IntoDart for i16 {
fn into_dart(self) -> DartCObject {
(self as i32).into_dart()
}
}
impl IntoDart for u8 {
fn into_dart(self) -> DartCObject {
(self as i32).into_dart()
}
}
impl IntoDart for u16 {
fn into_dart(self) -> DartCObject {
(self as i32).into_dart()
}
}
impl IntoDart for u32 {
fn into_dart(self) -> DartCObject {
(self as i64).into_dart()
}
}
impl IntoDart for u64 {
fn into_dart(self) -> DartCObject {
(self as i64).into_dart()
}
}
impl IntoDart for i128 {
fn into_dart(self) -> DartCObject {
self.to_string().into_dart()
}
}
impl IntoDart for u128 {
fn into_dart(self) -> DartCObject {
self.to_string().into_dart()
}
}
#[cfg(target_pointer_width = "64")]
impl IntoDart for usize {
fn into_dart(self) -> DartCObject {
(self as u64 as i64).into_dart()
}
}
#[cfg(target_pointer_width = "32")]
impl IntoDart for usize {
fn into_dart(self) -> DartCObject {
(self as u32 as i32).into_dart()
}
}
#[cfg(target_pointer_width = "64")]
impl IntoDart for isize {
fn into_dart(self) -> DartCObject {
(self as i64).into_dart()
}
}
#[cfg(target_pointer_width = "32")]
impl IntoDart for isize {
fn into_dart(self) -> DartCObject {
(self as i32).into_dart()
}
}
impl IntoDart for char {
fn into_dart(self) -> DartCObject {
(self as u32).into_dart()
}
}
| rust | Apache-2.0 | 9134004487720ca3ae3457da84933c4337038f0e | 2026-01-04T20:25:25.259611Z | false |
shekohex/allo-isolate | https://github.com/shekohex/allo-isolate/blob/9134004487720ca3ae3457da84933c4337038f0e/src/into_dart.rs | src/into_dart.rs | use std::collections::{HashMap, HashSet};
use std::{
ffi::{c_void, CString},
mem::ManuallyDrop,
};
use crate::{
dart_array::DartArray,
ffi::{DartHandleFinalizer, *},
};
/// A trait to convert between Rust types and Dart Types that could then
/// be sent to the isolate
///
/// see: [`crate::Isolate::post`]
pub trait IntoDart {
/// Consumes `Self` and Performs the conversion.
fn into_dart(self) -> DartCObject;
}
/// A trait that is [`IntoDart`] and is also not a primitive type. It is used to
/// avoid the ambiguity of whether types such as [`Vec<i32>`] should be
/// converted into [`Int32List`] or [`List<int>`]
pub trait IntoDartExceptPrimitive: IntoDart {}
impl<T> IntoDart for T
where
T: Into<DartCObject>,
{
fn into_dart(self) -> DartCObject {
self.into()
}
}
impl<T> IntoDartExceptPrimitive for T where T: IntoDart + Into<DartCObject> {}
impl IntoDart for () {
fn into_dart(self) -> DartCObject {
DartCObject {
ty: DartCObjectType::DartNull,
// I don't know what value should we send, so I send a false
// I guess dart vm check for the type first, so if it is null it
// return null and ignore the value
value: DartCObjectValue { as_bool: false },
}
}
}
#[cfg(feature = "anyhow")]
impl IntoDart for anyhow::Error {
fn into_dart(self) -> DartCObject {
format!("{:?}", self).into_dart()
}
}
impl IntoDart for std::backtrace::Backtrace {
fn into_dart(self) -> DartCObject {
format!("{:?}", self).into_dart()
}
}
#[cfg(feature = "backtrace")]
impl IntoDart for backtrace::Backtrace {
fn into_dart(self) -> DartCObject {
format!("{:?}", self).into_dart()
}
}
impl IntoDart for i32 {
fn into_dart(self) -> DartCObject {
DartCObject {
ty: DartCObjectType::DartInt32,
value: DartCObjectValue { as_int32: self },
}
}
}
impl IntoDart for i64 {
fn into_dart(self) -> DartCObject {
DartCObject {
ty: DartCObjectType::DartInt64,
value: DartCObjectValue { as_int64: self },
}
}
}
impl IntoDart for f32 {
fn into_dart(self) -> DartCObject {
(self as f64).into_dart()
}
}
impl IntoDart for f64 {
fn into_dart(self) -> DartCObject {
DartCObject {
ty: DartCObjectType::DartDouble,
value: DartCObjectValue { as_double: self },
}
}
}
impl IntoDart for bool {
fn into_dart(self) -> DartCObject {
DartCObject {
ty: DartCObjectType::DartBool,
value: DartCObjectValue { as_bool: self },
}
}
}
// https://github.com/sunshine-protocol/allo-isolate/pull/47
//
// Since Dart doesn't have a primitive list implemented for boolean (e.g. `Uint8List` for 8-bit unsigned int),
// we should implement `IntoDartExceptPrimitive` for `bool` so that `Vec<bool>` can be converted to `List<bool>`.
impl IntoDartExceptPrimitive for bool {}
impl IntoDart for String {
fn into_dart(self) -> DartCObject {
let s = CString::new(self).unwrap_or_default();
s.into_dart()
}
}
impl IntoDartExceptPrimitive for String {}
impl IntoDart for &'_ str {
fn into_dart(self) -> DartCObject {
self.to_string().into_dart()
}
}
impl IntoDartExceptPrimitive for &'_ str {}
impl IntoDart for CString {
fn into_dart(self) -> DartCObject {
DartCObject {
ty: DartCObjectType::DartString,
value: DartCObjectValue {
as_string: self.into_raw(),
},
}
}
}
impl IntoDartExceptPrimitive for CString {}
/// It is used when you want to write a generic function on different data types
/// and do not want to repeat yourself dozens of times.
/// For example, inside [Drop] of [DartCObject].
pub(crate) trait DartTypedDataTypeVisitor {
fn visit<T: DartTypedDataTypeTrait>(&self);
}
/// The Rust type for corresponding [DartTypedDataType]
pub trait DartTypedDataTypeTrait {
fn dart_typed_data_type() -> DartTypedDataType;
fn function_pointer_of_free_zero_copy_buffer() -> DartHandleFinalizer;
}
fn vec_to_dart_native_external_typed_data<T>(
vec_from_rust: Vec<T>,
) -> DartCObject
where
T: DartTypedDataTypeTrait,
{
if vec_from_rust.is_empty() {
let data = DartNativeTypedData {
ty: T::dart_typed_data_type(),
length: 0,
values: std::ptr::null_mut(),
};
return DartCObject {
ty: DartCObjectType::DartTypedData,
value: DartCObjectValue {
as_typed_data: data,
},
};
}
let mut vec = vec_from_rust;
vec.shrink_to_fit();
let length = vec.len();
assert_eq!(length, vec.capacity());
let ptr = vec.as_mut_ptr();
DartCObject {
ty: DartCObjectType::DartExternalTypedData,
value: DartCObjectValue {
as_external_typed_data: DartNativeExternalTypedData {
ty: T::dart_typed_data_type(),
length: length as isize,
data: ptr as *mut u8,
peer: Box::into_raw(Box::new(vec)).cast(),
callback: T::function_pointer_of_free_zero_copy_buffer(),
},
},
}
}
macro_rules! dart_typed_data_type_trait_impl {
($($dart_type:path => $rust_type:ident + $free_zero_copy_buffer_func:ident),+) => {
$(
impl DartTypedDataTypeTrait for $rust_type {
fn dart_typed_data_type() -> DartTypedDataType {
$dart_type
}
fn function_pointer_of_free_zero_copy_buffer() -> DartHandleFinalizer {
$free_zero_copy_buffer_func
}
}
impl<const N: usize> IntoDart for [$rust_type;N] {
fn into_dart(self) -> DartCObject {
let vec: Vec<_> = self.into();
vec.into_dart()
}
}
#[cfg(not(feature="zero-copy"))]
impl IntoDart for Vec<$rust_type> {
fn into_dart(self) -> DartCObject {
let mut vec = ManuallyDrop::new(self);
let data = DartNativeTypedData {
ty: $rust_type::dart_typed_data_type(),
length: vec.len() as isize,
values: vec.as_mut_ptr() as *mut _,
};
DartCObject {
ty: DartCObjectType::DartTypedData,
value: DartCObjectValue {
as_typed_data: data,
},
}
}
}
#[cfg(feature="zero-copy")]
impl IntoDart for Vec<$rust_type> {
fn into_dart(self) -> DartCObject {
vec_to_dart_native_external_typed_data(self)
}
}
impl IntoDartExceptPrimitive for Vec<$rust_type> {}
impl IntoDart for HashSet<$rust_type> {
fn into_dart(self) -> DartCObject {
self.into_iter().collect::<Vec<_>>().into_dart()
}
}
#[doc(hidden)]
#[no_mangle]
pub(crate) unsafe extern "C" fn $free_zero_copy_buffer_func(
_isolate_callback_data: *mut c_void,
peer: *mut c_void,
) {
drop(Box::from_raw(peer.cast::<Vec<$rust_type>>()));
}
)+
pub(crate) fn visit_dart_typed_data_type<V: DartTypedDataTypeVisitor>(ty: DartTypedDataType, visitor: &V) {
match ty {
$(
$dart_type => visitor.visit::<$rust_type>(),
)+
_ => panic!("visit_dart_typed_data_type see unexpected DartTypedDataType={:?}", ty)
}
}
}
}
dart_typed_data_type_trait_impl!(
DartTypedDataType::Int8 => i8 + free_zero_copy_buffer_i8,
DartTypedDataType::Uint8 => u8 + free_zero_copy_buffer_u8,
DartTypedDataType::Int16 => i16 + free_zero_copy_buffer_i16,
DartTypedDataType::Uint16 => u16 + free_zero_copy_buffer_u16,
DartTypedDataType::Int32 => i32 + free_zero_copy_buffer_i32,
DartTypedDataType::Uint32 => u32 + free_zero_copy_buffer_u32,
DartTypedDataType::Int64 => i64 + free_zero_copy_buffer_i64,
DartTypedDataType::Uint64 => u64 + free_zero_copy_buffer_u64,
DartTypedDataType::Float32 => f32 + free_zero_copy_buffer_f32,
DartTypedDataType::Float64 => f64 + free_zero_copy_buffer_f64
);
macro_rules! isize_usize {
($rust_type:ident, $delegate_target_type:ident) => {
impl<const N: usize> IntoDart for [$rust_type; N] {
fn into_dart(self) -> DartCObject {
let vec: Vec<_> = self.into();
vec.into_dart()
}
}
impl IntoDart for Vec<$rust_type> {
fn into_dart(self) -> DartCObject {
let vec: Vec<$delegate_target_type> =
self.into_iter().map(|x| x as _).collect();
vec.into_dart()
}
}
impl<const N: usize> IntoDart for ZeroCopyBuffer<[$rust_type; N]> {
fn into_dart(self) -> DartCObject {
let vec: Vec<$rust_type> = self.0.into();
ZeroCopyBuffer(vec).into_dart()
}
}
impl IntoDart for ZeroCopyBuffer<Vec<$rust_type>> {
fn into_dart(self) -> DartCObject {
let vec: Vec<$delegate_target_type> =
self.0.into_iter().map(|x| x as _).collect();
ZeroCopyBuffer(vec).into_dart()
}
}
impl IntoDartExceptPrimitive for Vec<$rust_type> {}
};
}
isize_usize!(isize, i64);
isize_usize!(usize, u64);
impl<T> IntoDart for ZeroCopyBuffer<Vec<T>>
where
T: DartTypedDataTypeTrait,
{
fn into_dart(self) -> DartCObject {
vec_to_dart_native_external_typed_data(self.0)
}
}
impl<T> IntoDartExceptPrimitive for ZeroCopyBuffer<Vec<T>> where
T: DartTypedDataTypeTrait
{
}
impl<T> IntoDart for Vec<T>
where
T: IntoDartExceptPrimitive,
{
fn into_dart(self) -> DartCObject {
DartArray::from(self.into_iter()).into_dart()
}
}
impl<T> IntoDartExceptPrimitive for Vec<T> where T: IntoDartExceptPrimitive {}
impl<T> IntoDart for HashSet<T>
where
T: IntoDartExceptPrimitive,
{
fn into_dart(self) -> DartCObject {
// Treated as `Vec<T>` and become `List` in Dart. It is unordered even though the type is a "list".
self.into_iter().collect::<Vec<_>>().into_dart()
}
}
impl<T> IntoDartExceptPrimitive for HashSet<T> where T: IntoDartExceptPrimitive {}
impl<K, V> IntoDart for HashMap<K, V>
where
K: IntoDart,
V: IntoDart,
(K, V): IntoDartExceptPrimitive,
{
fn into_dart(self) -> DartCObject {
// Treated as `Vec<(K, V)>` and thus become `List<dynamic>` in Dart
self.into_iter().collect::<Vec<_>>().into_dart()
}
}
impl<K, V> IntoDartExceptPrimitive for HashMap<K, V>
where
K: IntoDart,
V: IntoDart,
{
}
impl<T, const N: usize> IntoDart for ZeroCopyBuffer<[T; N]>
where
T: DartTypedDataTypeTrait,
{
fn into_dart(self) -> DartCObject {
let vec: Vec<_> = self.0.into();
ZeroCopyBuffer(vec).into_dart()
}
}
impl<T, const N: usize> IntoDartExceptPrimitive for ZeroCopyBuffer<[T; N]> where
T: DartTypedDataTypeTrait
{
}
impl<T, const N: usize> IntoDart for [T; N]
where
T: IntoDartExceptPrimitive,
{
fn into_dart(self) -> DartCObject {
DartArray::from(IntoIterator::into_iter(self)).into_dart()
}
}
impl<T, const N: usize> IntoDartExceptPrimitive for [T; N] where
T: IntoDartExceptPrimitive
{
}
impl<T> IntoDart for Option<T>
where
T: IntoDart,
{
fn into_dart(self) -> DartCObject {
match self {
Some(v) => v.into_dart(),
None => ().into_dart(),
}
}
}
impl<T> IntoDartExceptPrimitive for Option<T> where T: IntoDart {}
impl<T, E> IntoDart for Result<T, E>
where
T: IntoDart,
E: ToString,
{
fn into_dart(self) -> DartCObject {
match self {
Ok(v) => v.into_dart(),
Err(e) => e.to_string().into_dart(),
}
}
}
impl<T, E> IntoDartExceptPrimitive for Result<T, E>
where
T: IntoDart,
E: ToString,
{
}
/// A workaround to send raw pointers to dart over the port.
/// it will be sent as int64 on 64bit targets, and as int32 on 32bit targets.
#[cfg(target_pointer_width = "64")]
impl<T> IntoDart for *const T {
fn into_dart(self) -> DartCObject {
DartCObject {
ty: DartCObjectType::DartInt64,
value: DartCObjectValue {
as_int64: self as _,
},
}
}
}
#[cfg(target_pointer_width = "64")]
impl<T> IntoDart for *mut T {
fn into_dart(self) -> DartCObject {
DartCObject {
ty: DartCObjectType::DartInt64,
value: DartCObjectValue {
as_int64: self as _,
},
}
}
}
#[cfg(target_pointer_width = "32")]
impl<T> IntoDart for *const T {
fn into_dart(self) -> DartCObject {
DartCObject {
ty: DartCObjectType::DartInt32,
value: DartCObjectValue {
as_int32: self as _,
},
}
}
}
#[cfg(target_pointer_width = "32")]
impl<T> IntoDart for *mut T {
fn into_dart(self) -> DartCObject {
DartCObject {
ty: DartCObjectType::DartInt32,
value: DartCObjectValue {
as_int32: self as _,
},
}
}
}
macro_rules! impl_into_dart_for_tuple {
($( ($($A:ident)+) )*) => {$(
impl<$($A: IntoDart),+> IntoDart for ($($A),+,) {
#[allow(non_snake_case)]
fn into_dart(self) -> DartCObject {
let ($($A),+,) = self;
vec![$($A.into_dart()),+].into_dart()
}
}
impl<$($A: IntoDart),+> IntoDartExceptPrimitive for ($($A),+,) {}
)*};
}
impl_into_dart_for_tuple! {
(A)
(A B)
(A B C)
(A B C D)
(A B C D E)
(A B C D E F)
(A B C D E F G)
(A B C D E F G H)
(A B C D E F G H I)
(A B C D E F G H I J)
}
| rust | Apache-2.0 | 9134004487720ca3ae3457da84933c4337038f0e | 2026-01-04T20:25:25.259611Z | false |
shekohex/allo-isolate | https://github.com/shekohex/allo-isolate/blob/9134004487720ca3ae3457da84933c4337038f0e/src/chrono.rs | src/chrono.rs | //! chrono types
//!
//! based on Dart VM, microseconds unit is used
//!
//! recommendations below implies UTC based conversions,
//! as these are generally easier to work with.
//! > see [timestamp_micros](https://docs.rs/chrono/0.4.20/chrono/naive/struct.NaiveDateTime.html?search=timestamp_micros#method.timestamp_micros)
use crate::{
ffi::{DartCObject, DartHandleFinalizer, DartTypedDataType},
into_dart::{free_zero_copy_buffer_i64, DartTypedDataTypeTrait},
IntoDart,
};
impl IntoDart for chrono::DateTime<chrono::Utc> {
/// on the other side of FFI, value should be reconstructed like:
///
/// - hydrate into Dart [DateTime](https://api.dart.dev/stable/2.18.0/dart-core/DateTime/DateTime.fromMicrosecondsSinceEpoch.html)
/// `DateTime.fromMicrosecondsSinceEpoch(raw, isUtc: true);`
///
/// - hydrate into Rust [DateTime](chrono::DateTime)::<[Utc](chrono::Utc)>
/// ```rust,ignore
/// let s = (raw / 1_000_000) as i64;
/// let ns = (raw.rem_euclid(1_000_000) * 1_000) as u32;
/// chrono::DateTime::<chrono::Utc>::from_utc(
/// chrono::NaiveDateTime::from_timestamp(s, ns), chrono::Utc);
/// ```
///
/// note that it could overflow under the same conditions as of [chrono::NaiveDateTime::from_timestamp](https://docs.rs/chrono/0.4.20/chrono/naive/struct.NaiveDateTime.html#method.from_timestamp)
fn into_dart(self) -> DartCObject {
self.timestamp_micros().into_dart()
}
}
impl IntoDart for chrono::DateTime<chrono::Local> {
/// on the other side of FFI, value should be reconstructed like:
///
/// - hydrate into Dart [DateTime](https://api.dart.dev/stable/2.18.0/dart-core/DateTime/DateTime.fromMicrosecondsSinceEpoch.html)
/// `DateTime.fromMicrosecondsSinceEpoch(raw, isUtc: false);`
///
/// - hydrate into Rust [DateTime](chrono::DateTime)::<[Local](chrono::Local)>
/// ```rust,ignore
/// let s = (raw / 1_000_000) as i64;
/// let ns = (raw.rem_euclid(1_000_000) * 1_000) as u32;
/// chrono::DateTime::<chrono::Local>::from(
/// chrono::DateTime::<chrono::Utc>::from_utc(
/// chrono::NaiveDateTime::from_timestamp(s, ns), chrono::Utc));
/// ```
///
/// note that it could overflow under the same conditions as of [chrono::NaiveDateTime::from_timestamp](https://docs.rs/chrono/0.4.20/chrono/naive/struct.NaiveDateTime.html#method.from_timestamp)
fn into_dart(self) -> DartCObject {
self.timestamp_micros().into_dart()
}
}
impl IntoDart for chrono::NaiveDate {
/// on the other side of FFI, value should be reconstructed like:
///
/// - hydrate into Dart [DateTime](https://api.dart.dev/stable/2.18.0/dart-core/DateTime/DateTime.fromMicrosecondsSinceEpoch.html)
/// `DateTime.fromMicrosecondsSinceEpoch(raw, isUtc: true);`
///
/// - hydrate into Rust [NaiveDateTime](chrono::NaiveDate)
/// ```rust,ignore
/// let s = (raw / 1_000_000) as i64;
/// let ns = (raw.rem_euclid(1_000_000) * 1_000) as u32;
/// chrono::NaiveDateTime::from_timestamp(s, ns)
/// ```
///
/// note that it could overflow under the same conditions as of [chrono::NaiveDateTime::from_timestamp](https://docs.rs/chrono/0.4.20/chrono/naive/struct.NaiveDateTime.html#method.from_timestamp)
fn into_dart(self) -> DartCObject {
self.signed_duration_since(chrono::NaiveDate::MIN)
.into_dart()
}
}
impl IntoDart for chrono::NaiveDateTime {
/// on the other side of FFI, value should be reconstructed like:
///
/// - hydrate into Dart [DateTime](https://api.dart.dev/stable/2.18.0/dart-core/DateTime/DateTime.fromMicrosecondsSinceEpoch.html)
/// `DateTime.fromMicrosecondsSinceEpoch(raw, isUtc: true);`
///
/// - hydrate into Rust [NaiveDateTime](chrono::NaiveDateTime)
/// ```rust,ignore
/// let s = (raw / 1_000_000) as i64;
/// let ns = (raw.rem_euclid(1_000_000) * 1_000) as u32;
/// chrono::NaiveDateTime::from_timestamp(s, ns)
/// ```
///
/// note that it could overflow under the same conditions as of [chrono::NaiveDateTime::from_timestamp](https://docs.rs/chrono/0.4.20/chrono/naive/struct.NaiveDateTime.html#method.from_timestamp)
fn into_dart(self) -> DartCObject {
self.timestamp_micros().into_dart()
}
}
impl IntoDart for chrono::Duration {
/// on the other side of FFI, value should be reconstructed like:
///
/// - hydrate into Dart [Duration](https://api.dart.dev/stable/2.18.0/dart-core/Duration/Duration.html)
/// `Duration(microseconds: raw);`
///
/// - hydrate into Rust [Duration](chrono::Duration)
/// `chrono::Duration::microseconds(raw);`
fn into_dart(self) -> DartCObject {
self.num_microseconds().into_dart()
}
}
impl IntoDart for Vec<chrono::DateTime<chrono::Utc>> {
fn into_dart(self) -> DartCObject {
self.iter()
.map(chrono::DateTime::<chrono::Utc>::timestamp_micros)
.collect::<Vec<_>>()
.into_dart()
}
}
impl<const N: usize> IntoDart for [chrono::DateTime<chrono::Utc>; N] {
fn into_dart(self) -> DartCObject {
let vec: Vec<_> = self.into();
vec.into_dart()
}
}
impl DartTypedDataTypeTrait for chrono::DateTime<chrono::Utc> {
fn dart_typed_data_type() -> DartTypedDataType {
DartTypedDataType::Int64
}
fn function_pointer_of_free_zero_copy_buffer() -> DartHandleFinalizer {
free_zero_copy_buffer_i64
}
}
impl IntoDart for Vec<chrono::DateTime<chrono::Local>> {
fn into_dart(self) -> DartCObject {
self.iter()
.map(chrono::DateTime::<chrono::Local>::timestamp_micros)
.collect::<Vec<_>>()
.into_dart()
}
}
impl<const N: usize> IntoDart for [chrono::DateTime<chrono::Local>; N] {
fn into_dart(self) -> DartCObject {
let vec: Vec<_> = self.into();
vec.into_dart()
}
}
impl DartTypedDataTypeTrait for chrono::DateTime<chrono::Local> {
fn dart_typed_data_type() -> DartTypedDataType {
DartTypedDataType::Int64
}
fn function_pointer_of_free_zero_copy_buffer() -> DartHandleFinalizer {
free_zero_copy_buffer_i64
}
}
impl IntoDart for Vec<chrono::NaiveDate> {
fn into_dart(self) -> DartCObject {
self.iter()
.map(|lhs| lhs.signed_duration_since(chrono::NaiveDate::MIN))
.collect::<Vec<_>>()
.into_dart()
}
}
impl<const N: usize> IntoDart for [chrono::NaiveDate; N] {
fn into_dart(self) -> DartCObject {
let vec: Vec<_> = self.into();
vec.into_dart()
}
}
impl DartTypedDataTypeTrait for chrono::NaiveDate {
fn dart_typed_data_type() -> DartTypedDataType {
DartTypedDataType::Int64
}
fn function_pointer_of_free_zero_copy_buffer() -> DartHandleFinalizer {
free_zero_copy_buffer_i64
}
}
impl IntoDart for Vec<chrono::NaiveDateTime> {
fn into_dart(self) -> DartCObject {
self.iter()
.map(chrono::NaiveDateTime::timestamp_micros)
.collect::<Vec<_>>()
.into_dart()
}
}
impl<const N: usize> IntoDart for [chrono::NaiveDateTime; N] {
fn into_dart(self) -> DartCObject {
let vec: Vec<_> = self.into();
vec.into_dart()
}
}
impl DartTypedDataTypeTrait for chrono::NaiveDateTime {
fn dart_typed_data_type() -> DartTypedDataType {
DartTypedDataType::Int64
}
fn function_pointer_of_free_zero_copy_buffer() -> DartHandleFinalizer {
free_zero_copy_buffer_i64
}
}
impl IntoDart for Vec<chrono::Duration> {
fn into_dart(self) -> DartCObject {
self.iter()
.map(chrono::Duration::num_microseconds)
.collect::<Vec<_>>()
.into_dart()
}
}
impl<const N: usize> IntoDart for [chrono::Duration; N] {
fn into_dart(self) -> DartCObject {
let vec: Vec<_> = self.into();
vec.into_dart()
}
}
| rust | Apache-2.0 | 9134004487720ca3ae3457da84933c4337038f0e | 2026-01-04T20:25:25.259611Z | false |
shekohex/allo-isolate | https://github.com/shekohex/allo-isolate/blob/9134004487720ca3ae3457da84933c4337038f0e/src/ffi.rs | src/ffi.rs | #![allow(missing_docs, clippy::derive_partial_eq_without_eq)]
use std::{
ffi::{c_void, CString},
os::raw,
};
use crate::{
dart_array::DartArray,
into_dart::{
visit_dart_typed_data_type, DartTypedDataTypeTrait,
DartTypedDataTypeVisitor,
},
};
/// A port is used to send or receive inter-isolate messages
pub type DartPort = i64;
#[repr(i32)]
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum DartTypedDataType {
ByteData = 0,
Int8 = 1,
Uint8 = 2,
Uint8Clamped = 3,
Int16 = 4,
Uint16 = 5,
Int32 = 6,
Uint32 = 7,
Int64 = 8,
Uint64 = 9,
Float32 = 10,
Float64 = 11,
Float32x4 = 12,
Invalid = 13,
}
/// A Dart_CObject is used for representing Dart objects as native C
/// data outside the Dart heap. These objects are totally detached from
/// the Dart heap. Only a subset of the Dart objects have a
/// representation as a Dart_CObject.
///
/// The string encoding in the 'value.as_string' is UTF-8.
///
/// All the different types from dart:typed_data are exposed as type
/// kTypedData. The specific type from dart:typed_data is in the type
/// field of the as_typed_data structure. The length in the
/// as_typed_data structure is always in bytes.
///
/// The data for kTypedData is copied on message send and ownership remains with
/// the caller. The ownership of data for kExternalTyped is passed to the VM on
/// message send and returned when the VM invokes the
/// Dart_WeakPersistentHandleFinalizer callback; a non-NULL callback must be
/// provided.
///
/// https://github.com/dart-lang/sdk/blob/main/runtime/include/dart_native_api.h
#[repr(i32)]
#[derive(PartialEq, Debug, Clone, Copy)]
pub enum DartCObjectType {
DartNull = 0,
DartBool = 1,
DartInt32 = 2,
DartInt64 = 3,
DartDouble = 4,
DartString = 5,
DartArray = 6,
DartTypedData = 7,
DartExternalTypedData = 8,
DartSendPort = 9,
DartCapability = 10,
DartNativePointer = 11,
DartUnsupported = 12,
DartNumberOfTypes = 13,
}
#[allow(missing_debug_implementations)]
#[repr(C)]
pub struct DartCObject {
pub ty: DartCObjectType,
pub value: DartCObjectValue,
}
#[allow(missing_debug_implementations)]
#[repr(C)]
#[derive(Clone, Copy)]
pub union DartCObjectValue {
pub as_bool: bool,
pub as_int32: i32,
pub as_int64: i64,
pub as_double: f64,
pub as_string: *mut raw::c_char,
pub as_send_port: DartNativeSendPort,
pub as_capability: DartNativeCapability,
pub as_array: DartNativeArray,
pub as_typed_data: DartNativeTypedData,
pub as_external_typed_data: DartNativeExternalTypedData,
pub as_native_pointer: DartNativePointer,
_bindgen_union_align: [u64; 5usize],
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct DartNativeSendPort {
pub id: DartPort,
pub origin_id: DartPort,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct DartNativeCapability {
pub id: i64,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct DartNativeArray {
pub length: isize,
pub values: *mut *mut DartCObject,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct DartNativeTypedData {
pub ty: DartTypedDataType,
pub length: isize, // in elements, not bytes
pub values: *mut u8,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct DartNativeExternalTypedData {
pub ty: DartTypedDataType,
pub length: isize, // in elements, not bytes
pub data: *mut u8,
pub peer: *mut c_void,
pub callback: DartHandleFinalizer,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct DartNativePointer {
pub ptr: isize,
pub size: isize,
pub callback: DartHandleFinalizer,
}
/// https://github.com/dart-lang/sdk/blob/main/runtime/include/dart_api.h
pub type DartHandleFinalizer =
unsafe extern "C" fn(isolate_callback_data: *mut c_void, peer: *mut c_void);
/// Wrapping a Vec<u8> in this tuple struct will allow into_dart()
/// to send it as a DartNativeExternalTypedData buffer with no copy overhead
#[derive(Debug, Clone)]
pub struct ZeroCopyBuffer<T>(pub T);
/// Posts a message on some port. The message will contain the
/// Dart_CObject object graph rooted in 'message'.
///
/// While the message is being sent the state of the graph of
/// Dart_CObject structures rooted in 'message' should not be accessed,
/// as the message generation will make temporary modifications to the
/// data. When the message has been sent the graph will be fully
/// restored.
///
/// `port_id` The destination port.
/// `message` The message to send.
///
/// return true if the message was posted.
pub type DartPostCObjectFnType =
unsafe extern "C" fn(port_id: DartPort, message: *mut DartCObject) -> bool;
impl Drop for DartCObject {
fn drop(&mut self) {
match self.ty {
DartCObjectType::DartString => {
let _ = unsafe { CString::from_raw(self.value.as_string) };
},
DartCObjectType::DartArray => {
let _ = DartArray::from(unsafe { self.value.as_array });
},
DartCObjectType::DartTypedData => {
struct MyVisitor<'a>(&'a DartNativeTypedData);
impl DartTypedDataTypeVisitor for MyVisitor<'_> {
fn visit<T: DartTypedDataTypeTrait>(&self) {
if self.0.values.is_null() {
return;
}
let _ = unsafe {
Vec::from_raw_parts(
self.0.values as *mut T,
self.0.length as usize,
self.0.length as usize,
)
};
}
}
let v = unsafe { self.value.as_typed_data };
visit_dart_typed_data_type(v.ty, &MyVisitor(&v));
},
// write out all cases in order to be explicit - we do not want to
// leak any memory
DartCObjectType::DartNull
| DartCObjectType::DartBool
| DartCObjectType::DartInt32
| DartCObjectType::DartInt64
| DartCObjectType::DartDouble => {
// do nothing, since they are primitive types
},
DartCObjectType::DartExternalTypedData => {
// do NOT free any memory here
// see https://github.com/sunshine-protocol/allo-isolate/issues/7
},
DartCObjectType::DartSendPort
| DartCObjectType::DartCapability
| DartCObjectType::DartUnsupported
| DartCObjectType::DartNumberOfTypes => {
// not sure what to do here
},
DartCObjectType::DartNativePointer => {
// do not free the memory here, this will be done when the
// callback is called
},
}
}
}
/// Exposed only for tests.
#[doc(hidden)]
pub unsafe fn run_destructors(obj: &DartCObject) {
use DartCObjectType::*;
match obj.ty {
DartExternalTypedData => unsafe {
(obj.value.as_external_typed_data.callback)(
obj.value.as_external_typed_data.data as *mut c_void,
obj.value.as_external_typed_data.peer,
)
},
DartArray => {
let items = unsafe {
std::slice::from_raw_parts_mut(
obj.value.as_array.values,
obj.value.as_array.length as usize,
)
};
for item in items {
run_destructors(&**item)
}
},
_ => {},
}
}
| rust | Apache-2.0 | 9134004487720ca3ae3457da84933c4337038f0e | 2026-01-04T20:25:25.259611Z | false |
shekohex/allo-isolate | https://github.com/shekohex/allo-isolate/blob/9134004487720ca3ae3457da84933c4337038f0e/src/uuid.rs | src/uuid.rs | //! uuid type
use crate::{
ffi::{DartCObject, DartHandleFinalizer, DartTypedDataType},
into_dart::{free_zero_copy_buffer_u8, DartTypedDataTypeTrait},
IntoDart,
};
impl IntoDart for uuid::Uuid {
/// delegate to `Vec<u8>` implementation
///
/// on the other side of FFI, value should be reconstructed like:
///
/// - hydrate into Dart [UuidValue](https://pub.dev/documentation/uuid/latest/uuid/UuidValue-class.html)
/// `UuidValue.fromByteList(raw);`
///
/// - hydrate into Rust [Uuid](uuid::Uuid)
/// ```rust,ignore
/// uuid::Uuid::from_bytes(*<&[u8] as std::convert::TryInto<&[u8;16]>>::try_into(raw.as_slice()).expect("invalid uuid slice"));
/// ```
fn into_dart(self) -> DartCObject {
self.as_bytes().to_vec().into_dart()
}
}
impl IntoDart for Vec<uuid::Uuid> {
/// ⚠️ concatenated in a single `Vec<u8>` for performance optimization
///
/// on the other side of FFI, value should be reconstructed like:
///
/// - hydrate into Dart List<[UuidValue](https://pub.dev/documentation/uuid/latest/uuid/UuidValue-class.html)>
/// ```dart
/// return List<UuidValue>.generate(
/// raw.lengthInBytes / 16,
/// (int i) => UuidValue.fromByteList(Uint8List.view(raw.buffer, i * 16, 16)),
/// growable: false);
/// ```
///
/// - hydrate into Rust Vec<[Uuid](uuid::Uuid)>
/// ```rust,ignore
/// raw
/// .as_slice()
/// .chunks(16)
/// .map(|x: &[u8]| uuid::Uuid::from_bytes(*<&[u8] as std::convert::TryInto<&[u8;16]>>::try_into(x).expect("invalid uuid slice")))
/// .collect();
/// ```
///
/// note that buffer could end up being incomplete under the same conditions as of [std::io::Write::write](https://doc.rust-lang.org/std/io/trait.Write.html#tymethod.write).
fn into_dart(self) -> DartCObject {
use std::io::Write;
let mut buffer = Vec::<u8>::with_capacity(self.len() * 16);
for id in self {
let _ = buffer.write(id.as_bytes());
}
buffer.into_dart()
}
}
impl<const N: usize> IntoDart for [uuid::Uuid; N] {
fn into_dart(self) -> DartCObject {
let vec: Vec<_> = self.into();
vec.into_dart()
}
}
impl DartTypedDataTypeTrait for uuid::Uuid {
fn dart_typed_data_type() -> DartTypedDataType {
DartTypedDataType::Uint8
}
fn function_pointer_of_free_zero_copy_buffer() -> DartHandleFinalizer {
free_zero_copy_buffer_u8
}
}
| rust | Apache-2.0 | 9134004487720ca3ae3457da84933c4337038f0e | 2026-01-04T20:25:25.259611Z | false |
shekohex/allo-isolate | https://github.com/shekohex/allo-isolate/blob/9134004487720ca3ae3457da84933c4337038f0e/tests/vm.rs | tests/vm.rs | use allo_isolate::{
ffi::{
DartCObject, DartCObjectType, DartCObjectValue, DartNativeArray,
DartTypedDataType,
},
IntoDart,
};
use std::{
collections::HashMap,
ffi::{c_void, CStr},
sync::Mutex,
};
thread_local! {
static DART_VM: DartVM = DartVM::new();
}
struct DartVM {
ports: Mutex<HashMap<i64, VMIsolate>>,
}
impl DartVM {
fn new() -> Self {
Self {
ports: Default::default(),
}
}
/// Allocate a new port so you can post messages to
pub fn port(&self) -> i64 {
let port = fastrand::i64(1..i64::MAX);
if let Ok(mut ports) = self.ports.lock() {
ports.insert(port, VMIsolate::new());
port
} else {
-1
}
}
pub fn post(&self, port: i64, object: *mut DartCObject) -> bool {
if let Ok(mut ports) = self.ports.lock() {
if let Some(isolate) = ports.get_mut(&port) {
isolate.exec(object)
} else {
false
}
} else {
false
}
}
}
struct VMIsolate;
impl VMIsolate {
const fn new() -> Self {
Self
}
fn exec(&mut self, object: *mut DartCObject) -> bool {
use DartCObjectType::*;
assert!(!object.is_null(), "got a null object");
let o = unsafe { &mut *object };
match o.ty {
DartNull => {
DartCObject {
ty: DartNull,
value: DartCObjectValue { as_bool: false },
};
},
DartBool => {
DartCObject {
ty: DartBool,
value: DartCObjectValue {
as_bool: unsafe { o.value.as_bool },
},
};
},
DartInt32 => {
DartCObject {
ty: DartInt32,
value: DartCObjectValue {
as_int32: unsafe { o.value.as_int32 },
},
};
},
DartInt64 => {
DartCObject {
ty: DartInt64,
value: DartCObjectValue {
as_int64: unsafe { o.value.as_int64 },
},
};
},
DartDouble => {
DartCObject {
ty: DartDouble,
value: DartCObjectValue {
as_double: unsafe { o.value.as_double },
},
};
},
DartString => {
{
let s =
unsafe { CStr::from_ptr(o.value.as_string) }.to_owned();
DartCObject {
ty: DartString,
value: DartCObjectValue {
as_string: s.into_raw(),
},
}
};
},
DartArray => {
// In a real application, the Dart VM would keep the array and its elements around
// and let GC eventually reclaim it. This prevents memory leaks e.g. resulting from external
// typed arrays nested inside of arrays and hence not being cleaned up.
unsafe {
allo_isolate::ffi::run_destructors(o);
}
// do something with o
// I'm semulating that I copied some data into the VM here
let v: Vec<_> = vec![0u32; 0]
.into_iter()
.map(IntoDart::into_dart)
.map(Box::new)
.map(Box::into_raw)
.collect();
let mut v = v.into_boxed_slice();
DartCObject {
ty: DartArray,
value: DartCObjectValue {
as_array: DartNativeArray {
length: v.len() as isize,
values: v.as_mut_ptr(),
},
},
};
},
DartTypedData => {
let v = unsafe { o.value.as_typed_data };
let ty = v.ty;
unsafe {
match ty {
DartTypedDataType::Int8 => {
let _ = from_buf_raw(
v.values as *mut i8,
v.length as usize,
);
},
DartTypedDataType::Uint8 => {
let _ = from_buf_raw(
v.values as *mut u8,
v.length as usize,
);
},
DartTypedDataType::Int16 => {
let _ = from_buf_raw(
v.values as *mut i16,
v.length as usize,
);
},
DartTypedDataType::Uint16 => {
let _ = from_buf_raw(
v.values as *mut u16,
v.length as usize,
);
},
DartTypedDataType::Int32 => {
let _ = from_buf_raw(
v.values as *mut i32,
v.length as usize,
);
},
DartTypedDataType::Uint32 => {
let _ = from_buf_raw(
v.values as *mut u32,
v.length as usize,
);
},
DartTypedDataType::Int64 => {
let _ = from_buf_raw(
v.values as *mut i64,
v.length as usize,
);
},
DartTypedDataType::Uint64 => {
let _ = from_buf_raw(
v.values as *mut u64,
v.length as usize,
);
},
DartTypedDataType::Float32 => {
let _ = from_buf_raw(
v.values as *mut f32,
v.length as usize,
);
},
DartTypedDataType::Float64 => {
let _ = from_buf_raw(
v.values as *mut f64,
v.length as usize,
);
},
_ => unimplemented!(),
};
}
},
DartExternalTypedData => {
let v = unsafe { o.value.as_external_typed_data };
let ty = v.ty;
match ty {
DartTypedDataType::Int8 => {
let _ = unsafe {
let output = from_buf_raw(
v.data as *mut i8,
v.length as usize,
);
let cb = v.callback;
cb(v.length as *mut c_void, v.peer);
output
};
},
DartTypedDataType::Uint8 => {
let _ = unsafe {
let output = from_buf_raw(
v.data as *mut u8,
v.length as usize,
);
let cb = v.callback;
cb(v.length as *mut c_void, v.peer);
output
};
},
DartTypedDataType::Int16 => {
let _ = unsafe {
let output = from_buf_raw(
v.data as *mut i16,
v.length as usize,
);
let cb = v.callback;
cb(v.length as *mut c_void, v.peer);
output
};
},
DartTypedDataType::Uint16 => {
let _ = unsafe {
let output = from_buf_raw(
v.data as *mut u16,
v.length as usize,
);
let cb = v.callback;
cb(v.length as *mut c_void, v.peer);
output
};
},
DartTypedDataType::Int32 => {
let _ = unsafe {
let output = from_buf_raw(
v.data as *mut i32,
v.length as usize,
);
let cb = v.callback;
cb(v.length as *mut c_void, v.peer);
output
};
},
DartTypedDataType::Uint32 => {
let _ = unsafe {
let output = from_buf_raw(
v.data as *mut u32,
v.length as usize,
);
let cb = v.callback;
cb(v.length as *mut c_void, v.peer);
output
};
},
DartTypedDataType::Int64 => {
let _ = unsafe {
let output = from_buf_raw(
v.data as *mut i64,
v.length as usize,
);
let cb = v.callback;
cb(v.length as *mut c_void, v.peer);
output
};
},
DartTypedDataType::Uint64 => {
let _ = unsafe {
let output = from_buf_raw(
v.data as *mut u64,
v.length as usize,
);
let cb = v.callback;
cb(v.length as *mut c_void, v.peer);
output
};
},
DartTypedDataType::Float32 => {
let _ = unsafe {
let output = from_buf_raw(
v.data as *mut f32,
v.length as usize,
);
let cb = v.callback;
cb(v.length as *mut c_void, v.peer);
output
};
},
DartTypedDataType::Float64 => {
let _ = unsafe {
let output = from_buf_raw(
v.data as *mut f64,
v.length as usize,
);
let cb = v.callback;
cb(v.length as *mut c_void, v.peer);
output
};
},
_ => unimplemented!(),
};
},
_ => {
unimplemented!();
},
};
true
}
}
unsafe fn from_buf_raw<T>(ptr: *const T, elts: usize) -> Vec<T> {
let mut dst = Vec::with_capacity(elts);
dst.set_len(elts);
std::ptr::copy(ptr, dst.as_mut_ptr(), elts);
dst
}
pub extern "C" fn dart_post_cobject(port: i64, msg: *mut DartCObject) -> bool {
DART_VM.with(|vm| vm.post(port, msg))
}
pub fn port() -> i64 {
DART_VM.with(|vm| vm.port())
}
| rust | Apache-2.0 | 9134004487720ca3ae3457da84933c4337038f0e | 2026-01-04T20:25:25.259611Z | false |
shekohex/allo-isolate | https://github.com/shekohex/allo-isolate/blob/9134004487720ca3ae3457da84933c4337038f0e/tests/containers.rs | tests/containers.rs | use allo_isolate::{ffi::DartCObjectType, IntoDart, Isolate, ZeroCopyBuffer};
use std::collections::{HashMap, HashSet};
mod vm;
fn main() {
// Create a Dart VM call before we could handle sending a message back to
// Dart
let port = vm::port();
assert_ne!(port, -1);
let isolate = Isolate::new(port);
assert!(!isolate.post(vec![String::from("Rust"); 8]));
assert!(!isolate.post(vec![String::from("Dart"); 1024]));
assert!(!isolate.post(vec![42i8; 100]));
assert!(!isolate.post(vec![42u8; 100]));
assert!(!isolate.post(vec![42i16; 100]));
assert!(!isolate.post(vec![42u16; 100]));
assert!(!isolate.post(vec![42i32; 100]));
assert!(!isolate.post(vec![42u32; 100]));
assert!(!isolate.post(vec![42i64; 100]));
assert!(!isolate.post(vec![42u64; 100]));
assert!(!isolate.post(vec![42isize; 100]));
assert!(!isolate.post(vec![42usize; 100]));
assert!(!isolate.post(vec![42.0f32; 100]));
assert!(!isolate.post(vec![42.0f64; 100]));
assert!(!isolate.post(vec![true; 100]));
assert!(!isolate.post(vec![false; 100]));
assert!(!isolate.post(ZeroCopyBuffer(vec![0u8; 0])));
assert!(!isolate.post(ZeroCopyBuffer(vec![42i8; 100])));
assert!(!isolate.post(ZeroCopyBuffer(vec![42u8; 100])));
assert!(!isolate.post(ZeroCopyBuffer(vec![42i16; 100])));
assert!(!isolate.post(ZeroCopyBuffer(vec![42u16; 100])));
assert!(!isolate.post(ZeroCopyBuffer(vec![42i32; 100])));
assert!(!isolate.post(ZeroCopyBuffer(vec![42u32; 100])));
assert!(!isolate.post(ZeroCopyBuffer(vec![42i64; 100])));
assert!(!isolate.post(ZeroCopyBuffer(vec![42u64; 100])));
assert!(!isolate.post(ZeroCopyBuffer(vec![42isize; 100])));
assert!(!isolate.post(ZeroCopyBuffer(vec![42usize; 100])));
assert!(!isolate.post(ZeroCopyBuffer(vec![42.0f32; 100])));
assert!(!isolate.post(ZeroCopyBuffer(vec![42.0f64; 100])));
assert!(!isolate.post([42i8; 100]));
assert!(!isolate.post([42u8; 100]));
assert!(!isolate.post([42i16; 100]));
assert!(!isolate.post([42u16; 100]));
assert!(!isolate.post([42i32; 100]));
assert!(!isolate.post([42u32; 100]));
assert!(!isolate.post([42i64; 100]));
assert!(!isolate.post([42u64; 100]));
assert!(!isolate.post([42isize; 100]));
assert!(!isolate.post([42usize; 100]));
assert!(!isolate.post([42.0f32; 100]));
assert!(!isolate.post([42.0f64; 100]));
assert!(!isolate.post([true; 100]));
assert!(!isolate.post([false; 100]));
assert!(!isolate.post(ZeroCopyBuffer([0u8; 0])));
assert!(!isolate.post(ZeroCopyBuffer([42i8; 100])));
assert!(!isolate.post(ZeroCopyBuffer([42u8; 100])));
assert!(!isolate.post(ZeroCopyBuffer([42i16; 100])));
assert!(!isolate.post(ZeroCopyBuffer([42u16; 100])));
assert!(!isolate.post(ZeroCopyBuffer([42i32; 100])));
assert!(!isolate.post(ZeroCopyBuffer([42u32; 100])));
assert!(!isolate.post(ZeroCopyBuffer([42i64; 100])));
assert!(!isolate.post(ZeroCopyBuffer([42u64; 100])));
assert!(!isolate.post(ZeroCopyBuffer([42isize; 100])));
assert!(!isolate.post(ZeroCopyBuffer([42usize; 100])));
assert!(!isolate.post(ZeroCopyBuffer([42.0f32; 100])));
assert!(!isolate.post(ZeroCopyBuffer([42.0f64; 100])));
// Provide the pointer that allows Rust to communicate messages back to the
// Dart VM
unsafe {
allo_isolate::store_dart_post_cobject(vm::dart_post_cobject);
}
// Post some messages that will succeed
let port = vm::port();
assert_ne!(port, -1);
let isolate = Isolate::new(port);
assert!(isolate.post(42i8));
assert!(isolate.post(42u8));
assert!(isolate.post(42i16));
assert!(isolate.post(42u16));
assert!(isolate.post(42i32));
assert!(isolate.post(42u32));
assert!(isolate.post(42i64));
assert!(isolate.post(42u64));
assert!(isolate.post(42isize));
assert!(isolate.post(42usize));
assert!(isolate.post(42i128));
assert!(isolate.post(42u128));
assert!(isolate.post(42usize));
assert!(isolate.post(42isize));
assert!(isolate.post(true));
assert!(isolate.post(false));
assert!(isolate.post('🎊'));
// Create another isolate and port that still works
let port = vm::port();
assert_ne!(port, -1);
let isolate = Isolate::new(port);
assert!(isolate.post(String::new()));
assert!(isolate.post(String::from("Hello Dart")));
assert!(isolate.post("Hello Dart"));
// Create another isolate and port that still works
let port = vm::port();
assert_ne!(port, -1);
let isolate2 = Isolate::new(port);
// Send data to the new port
assert!(isolate2.post(String::new()));
assert!(isolate2.post(String::from("Hello Dart")));
assert!(isolate2.post("Hello Dart"));
assert!(isolate.post(ZeroCopyBuffer(vec![42.0f64; 100])));
// Send data to the old port
assert!(isolate.post(String::new()));
assert!(isolate.post(String::from("Hello Dart")));
assert!(isolate.post("Hello Dart"));
assert!(isolate.post(ZeroCopyBuffer(vec![42.0f64; 100])));
// Send data to the new port again
assert!(isolate2.post(String::new()));
assert!(isolate2.post(String::from("Hello Dart")));
assert!(isolate2.post("Hello Dart"));
assert!(isolate.post(ZeroCopyBuffer(vec![42.0f64; 100])));
// Create another port and send all the data successfully
let port = vm::port();
assert_ne!(port, -1);
let isolate = Isolate::new(port);
assert!(isolate.post(vec![String::from("Rust"); 8]));
assert!(isolate.post(vec![String::from("Dart"); 1024]));
assert!(isolate.post(vec![
vec![String::from("Rust"); 8],
vec![String::from("Dart"); 1024]
]));
assert!(isolate.post(vec![
vec![
vec![String::from("Rust"); 8],
vec![String::from("Dart"); 1024]
],
vec![
vec![String::from("Rust"); 8],
vec![String::from("Dart"); 1024]
]
]));
assert!(isolate.post(vec![42i8; 100]));
assert!(isolate.post(vec![42u8; 100]));
assert!(isolate.post(vec![42i16; 100]));
assert!(isolate.post(vec![42u16; 100]));
assert!(isolate.post(vec![42i32; 100]));
assert!(isolate.post(vec![42u32; 100]));
assert!(isolate.post(vec![42i64; 100]));
assert!(isolate.post(vec![42u64; 100]));
assert!(isolate.post(vec![42isize; 100]));
assert!(isolate.post(vec![42usize; 100]));
assert!(isolate.post(vec![42.0f32; 100]));
assert!(isolate.post(vec![42.0f64; 100]));
assert!(isolate.post(vec![true; 100]));
assert!(isolate.post(vec![false; 100]));
assert!(isolate.post(ZeroCopyBuffer(vec![42i8; 100])));
assert!(isolate.post(ZeroCopyBuffer(vec![42u8; 100])));
assert!(isolate.post(ZeroCopyBuffer(vec![42i16; 100])));
assert!(isolate.post(ZeroCopyBuffer(vec![42u16; 100])));
assert!(isolate.post(ZeroCopyBuffer(vec![42i32; 100])));
assert!(isolate.post(ZeroCopyBuffer(vec![42u32; 100])));
assert!(isolate.post(ZeroCopyBuffer(vec![42i64; 100])));
assert!(isolate.post(ZeroCopyBuffer(vec![42u64; 100])));
assert!(isolate.post(ZeroCopyBuffer(vec![42isize; 100])));
assert!(isolate.post(ZeroCopyBuffer(vec![42usize; 100])));
assert!(isolate.post(ZeroCopyBuffer(vec![42.0f32; 100])));
assert!(isolate.post(ZeroCopyBuffer(vec![42.0f64; 100])));
assert!(isolate.post([42i8; 100]));
assert!(isolate.post([42u8; 100]));
assert!(isolate.post([42i16; 100]));
assert!(isolate.post([42u16; 100]));
assert!(isolate.post([42i32; 100]));
assert!(isolate.post([42u32; 100]));
assert!(isolate.post([42i64; 100]));
assert!(isolate.post([42u64; 100]));
assert!(isolate.post([42i64; 100]));
assert!(isolate.post([42usize; 100]));
assert!(isolate.post([42.0f32; 100]));
assert!(isolate.post([42.0f64; 100]));
assert!(isolate.post([true; 100]));
assert!(isolate.post([false; 100]));
assert!(isolate.post(ZeroCopyBuffer([42i8; 100])));
assert!(isolate.post(ZeroCopyBuffer([42u8; 100])));
assert!(isolate.post(ZeroCopyBuffer([42i16; 100])));
assert!(isolate.post(ZeroCopyBuffer([42u16; 100])));
assert!(isolate.post(ZeroCopyBuffer([42i32; 100])));
assert!(isolate.post(ZeroCopyBuffer([42u32; 100])));
assert!(isolate.post(ZeroCopyBuffer([42i64; 100])));
assert!(isolate.post(ZeroCopyBuffer([42u64; 100])));
assert!(isolate.post(ZeroCopyBuffer([42isize; 100])));
assert!(isolate.post(ZeroCopyBuffer([42usize; 100])));
assert!(isolate.post(ZeroCopyBuffer([42.0f32; 100])));
assert!(isolate.post(ZeroCopyBuffer([42.0f64; 100])));
{
// https://github.com/sunshine-protocol/allo-isolate/pull/17
let u32_into_dart = 0xfe112233_u32.into_dart();
assert_eq!(DartCObjectType::DartInt64, u32_into_dart.ty);
unsafe {
assert_eq!(0xfe112233_i64, u32_into_dart.value.as_int64);
}
}
#[cfg(feature = "anyhow")]
assert!(isolate.post(return_anyhow_error()));
assert!(isolate.post(std::backtrace::Backtrace::capture()));
#[cfg(feature = "backtrace")]
assert!(isolate.post(return_backtrace()));
#[cfg(feature = "chrono")]
{
assert!(isolate.post(return_chrono_naive_date()));
assert!(isolate.post(return_chrono_naive_date_time()));
assert!(isolate.post(return_chrono_date_time_utc()));
assert!(isolate.post(return_chrono_date_time_local()));
assert!(isolate.post(return_chrono_duration()));
}
#[cfg(feature = "uuid")]
{
assert!(isolate.post(return_uuid()));
assert!(isolate.post(return_uuids()))
}
assert!(isolate.post(("asd", "asd".to_string(), 123)));
assert!(isolate.post(((true,), (123,))));
assert!(isolate.post((ZeroCopyBuffer(vec![-1]), vec![-1], 1.1)));
assert!(isolate.post((1, 2, 3, 4, 5, 6, 7, 8, 9, (10, 11))));
assert!(
isolate.post(HashMap::from([("key".to_owned(), "value".to_owned())]))
);
assert!(isolate.post(HashMap::from([(100, 200)])));
assert!(isolate.post(HashMap::from([(100, 200u8)])));
assert!(isolate.post(HashMap::from([(100, vec![42u8])])));
assert!(isolate.post(HashSet::from(["value".to_owned()])));
assert!(isolate.post(HashSet::from([200])));
assert!(isolate.post(HashSet::from([200u8])));
assert!(isolate.post(vec![vec![10u8]]));
// Test 2D array support - this is what PR #66 enables
let arr_2d: [[bool; 3]; 2] = [[true, false, true], [false, true, false]];
assert!(isolate.post(arr_2d));
// Test case to verify that dropping vectors using ZeroCopyBuffer no longer causes a panic
let a: ZeroCopyBuffer<Vec<u64>> = ZeroCopyBuffer(vec![]);
let b = a.into_dart();
drop(b);
println!("all done!");
}
#[cfg(feature = "anyhow")]
fn return_anyhow_error() -> anyhow::Result<()> {
Err(anyhow::anyhow!("sample error"))
}
#[cfg(feature = "backtrace")]
fn return_backtrace() -> backtrace::Backtrace {
backtrace::Backtrace::new()
}
#[cfg(feature = "chrono")]
fn return_chrono_naive_date() -> chrono::NaiveDate {
chrono::NaiveDate::from_ymd_opt(1776, 7, 4)
.expect("The input date for testing is required to be valid")
}
#[cfg(feature = "chrono")]
fn return_chrono_naive_date_time() -> chrono::NaiveDateTime {
chrono::NaiveDate::from_ymd_opt(2016, 7, 8)
.map(|nd| nd.and_hms_micro_opt(9, 10, 11, 123_456))
.flatten()
.expect("The input date and time for testing are required to be valid")
}
#[cfg(feature = "chrono")]
fn return_chrono_date_time_utc() -> chrono::DateTime<chrono::Utc> {
chrono::Utc::now()
}
#[cfg(feature = "chrono")]
fn return_chrono_date_time_local() -> chrono::DateTime<chrono::Local> {
chrono::Local::now()
}
#[cfg(feature = "chrono")]
fn return_chrono_duration() -> chrono::Duration {
chrono::Duration::hours(24)
}
#[cfg(feature = "uuid")]
fn return_uuid() -> uuid::Uuid {
uuid::Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap()
}
#[cfg(feature = "uuid")]
fn return_uuids() -> Vec<uuid::Uuid> {
vec![
uuid::Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap(),
uuid::Uuid::parse_str("a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8").unwrap(),
]
}
#[cfg(test)]
mod tests {
#[test]
fn can_run_valgrind_main() {
super::main();
}
}
| rust | Apache-2.0 | 9134004487720ca3ae3457da84933c4337038f0e | 2026-01-04T20:25:25.259611Z | false |
shekohex/allo-isolate | https://github.com/shekohex/allo-isolate/blob/9134004487720ca3ae3457da84933c4337038f0e/benches/uuid.rs | benches/uuid.rs | use std::io::Write;
use allo_isolate::{ffi::DartCObject, IntoDart};
use criterion::{
black_box, criterion_group, criterion_main, BenchmarkId, Criterion,
};
fn simple(uuids: Vec<uuid::Uuid>) -> DartCObject {
uuids
.into_iter()
.map(<uuid::Uuid as IntoDart>::into_dart)
.collect::<Vec<DartCObject>>()
.into_dart()
}
fn packed(uuids: Vec<uuid::Uuid>) -> DartCObject {
let mut buffer = Vec::<u8>::with_capacity(uuids.len() * 16);
for id in uuids {
let _ = buffer.write(id.as_bytes());
}
buffer.into_dart()
}
fn uuids(count: usize) -> Vec<uuid::Uuid> {
let mut buffer = Vec::with_capacity(count);
for _ in 0..count {
buffer.push(uuid::Uuid::new_v4());
}
buffer
}
fn criterion_benchmark(c: &mut Criterion) {
let mut group = c.benchmark_group("uuid into dart");
for i in [100, 1000, 100_000, 1000_000].iter() {
let input = uuids(*i);
group.bench_with_input(
BenchmarkId::new("Delegate to inner type", i),
i,
|b, _| b.iter(|| simple(black_box(input.clone()))),
);
group.bench_with_input(
BenchmarkId::new("Pack all in one", i),
i,
|b, _| b.iter(|| packed(black_box(input.clone()))),
);
}
group.finish();
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
| rust | Apache-2.0 | 9134004487720ca3ae3457da84933c4337038f0e | 2026-01-04T20:25:25.259611Z | false |
HuakunShen/tauri-plugin-network | https://github.com/HuakunShen/tauri-plugin-network/blob/6f14e18294d389a167b041eed74e112064e00c00/build.rs | build.rs | const COMMANDS: &[&str] = &[
"get_interfaces",
"get_non_empty_interfaces",
"find_available_port",
"is_port_taken",
"is_http_port_open",
"scan_online_ip_port_pairs",
"scan_online_ips_by_port",
"non_localhost_networks",
"local_server_is_running",
"scan_local_network_online_hosts_by_port",
];
fn main() {
tauri_plugin::Builder::new(COMMANDS)
.android_path("android")
.ios_path("ios")
.build();
}
| rust | MIT | 6f14e18294d389a167b041eed74e112064e00c00 | 2026-01-04T20:25:28.969475Z | false |
HuakunShen/tauri-plugin-network | https://github.com/HuakunShen/tauri-plugin-network/blob/6f14e18294d389a167b041eed74e112064e00c00/src/lib.rs | src/lib.rs | use tauri::{
plugin::{Builder, TauriPlugin},
Manager, Runtime,
};
mod commands;
mod error;
mod model;
mod network;
pub use error::{Error, Result};
/// Initializes the plugin.
pub fn init<R: Runtime>() -> TauriPlugin<R> {
Builder::new("network")
.invoke_handler(tauri::generate_handler![
commands::interface::get_interfaces,
commands::interface::get_non_empty_interfaces,
commands::scan::find_available_port,
commands::scan::is_port_taken,
commands::scan::is_http_port_open,
commands::scan::scan_online_ip_port_pairs,
commands::scan::scan_online_ips_by_port,
commands::scan::non_localhost_networks,
commands::scan::local_server_is_running,
commands::scan::scan_local_network_online_hosts_by_port,
])
.build()
}
| rust | MIT | 6f14e18294d389a167b041eed74e112064e00c00 | 2026-01-04T20:25:28.969475Z | false |
HuakunShen/tauri-plugin-network | https://github.com/HuakunShen/tauri-plugin-network/blob/6f14e18294d389a167b041eed74e112064e00c00/src/error.rs | src/error.rs | use serde::{ser::Serializer, Serialize};
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error(transparent)]
Io(#[from] std::io::Error),
#[cfg(mobile)]
#[error(transparent)]
PluginInvoke(#[from] tauri::plugin::mobile::PluginInvokeError),
}
impl Serialize for Error {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.to_string().as_ref())
}
}
| rust | MIT | 6f14e18294d389a167b041eed74e112064e00c00 | 2026-01-04T20:25:28.969475Z | false |
HuakunShen/tauri-plugin-network | https://github.com/HuakunShen/tauri-plugin-network/blob/6f14e18294d389a167b041eed74e112064e00c00/src/model/interface.rs | src/model/interface.rs | use ipnetwork::{ipv4_mask_to_prefix, ipv6_mask_to_prefix, Ipv4Network, Ipv6Network};
use network_interface as niface;
use serde::{Deserialize, Serialize};
use std::net::{Ipv4Addr, Ipv6Addr};
#[derive(Debug, Serialize, Deserialize)]
pub struct MacAddr(pub [u8; 6]);
#[derive(Debug, Serialize, Deserialize)]
pub struct V4IfAddr {
pub ip: Ipv4Addr,
pub ip_octets: [u8; 4],
pub broadcast: Option<Ipv4Addr>,
pub broadcast_octets: Option<[u8; 4]>,
pub netmask: Option<Ipv4Addr>,
pub netmask_octets: Option<[u8; 4]>,
pub prefix: Option<u8>,
pub network: Option<Ipv4Network>,
// pub size: Option<u32>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct V6IfAddr {
pub ip: Ipv6Addr,
pub ip_octets: [u8; 16],
pub broadcast: Option<Ipv6Addr>,
pub broadcast_octets: Option<[u8; 16]>,
pub netmask: Option<Ipv6Addr>,
pub netmask_octets: Option<[u8; 16]>,
pub prefix: Option<u8>,
pub network: Option<Ipv6Network>,
// pub size: Option<u128>, // u128 is too large for JavaScript and will result in error
}
#[derive(Debug, Serialize, Deserialize)]
pub struct NetworkInterface {
pub name: String,
pub v4_addrs: Vec<V4IfAddr>,
pub v6_addrs: Vec<V6IfAddr>,
pub mac_addr: Option<String>,
pub index: u32,
}
pub fn v4_iface_to_network(addr: &niface::V4IfAddr) -> Option<Ipv4Network> {
match addr.netmask {
Some(netmask) => match Ipv4Network::with_netmask(addr.ip, netmask) {
Ok(network) => Some(network),
Err(_) => None,
},
None => None,
}
}
pub fn v6_iface_to_network(addr: &niface::V6IfAddr) -> Option<Ipv6Network> {
match addr.netmask {
Some(netmask) => match Ipv6Network::with_netmask(addr.ip, netmask) {
Ok(network) => Some(network),
Err(_) => None,
},
None => None,
}
}
impl From<&niface::NetworkInterface> for NetworkInterface {
fn from(iface: &niface::NetworkInterface) -> Self {
NetworkInterface {
name: iface.name.clone(),
v4_addrs: iface
.addr
.iter()
.filter_map(|addr| {
if let niface::Addr::V4(addr) = addr {
let network = v4_iface_to_network(addr);
Some(V4IfAddr {
ip: addr.ip,
ip_octets: addr.ip.octets(),
broadcast: addr.broadcast,
broadcast_octets: addr.broadcast.map(|broadcast| broadcast.octets()),
netmask: addr.netmask,
netmask_octets: addr.netmask.map(|netmask| netmask.octets()),
prefix: match addr.netmask {
Some(netmask) => match ipv4_mask_to_prefix(netmask) {
Ok(prefix) => Some(prefix),
Err(_) => None,
},
None => None,
},
network,
// size: match network {
// Some(net) => Some(net.size()),
// None => None,
// },
})
} else {
None
}
})
.collect(),
v6_addrs: iface
.addr
.iter()
.filter_map(|addr| {
if let niface::Addr::V6(addr) = addr {
let network = v6_iface_to_network(addr);
Some(V6IfAddr {
ip: addr.ip,
ip_octets: addr.ip.octets(),
broadcast: addr.broadcast,
broadcast_octets: addr.broadcast.map(|broadcast| broadcast.octets()),
netmask: addr.netmask,
netmask_octets: addr.netmask.map(|netmask| netmask.octets()),
prefix: match addr.netmask {
Some(netmask) => match ipv6_mask_to_prefix(netmask) {
Ok(prefix) => Some(prefix),
Err(_) => None,
},
None => None,
},
network,
// size: match network {
// Some(net) => Some(net.size()),
// None => None,
// },
})
} else {
None
}
})
.collect(),
mac_addr: iface.mac_addr.clone(),
index: iface.index,
}
}
}
| rust | MIT | 6f14e18294d389a167b041eed74e112064e00c00 | 2026-01-04T20:25:28.969475Z | false |
HuakunShen/tauri-plugin-network | https://github.com/HuakunShen/tauri-plugin-network/blob/6f14e18294d389a167b041eed74e112064e00c00/src/model/mod.rs | src/model/mod.rs | pub mod interface;
| rust | MIT | 6f14e18294d389a167b041eed74e112064e00c00 | 2026-01-04T20:25:28.969475Z | false |
HuakunShen/tauri-plugin-network | https://github.com/HuakunShen/tauri-plugin-network/blob/6f14e18294d389a167b041eed74e112064e00c00/src/commands/interface.rs | src/commands/interface.rs | use crate::{model::interface::NetworkInterface, network};
#[tauri::command]
pub fn get_interfaces() -> Result<Vec<NetworkInterface>, String> {
network::utils::get_interfaces().map_err(|e| e.to_string())
}
#[tauri::command]
pub fn get_non_empty_interfaces() -> Result<Vec<NetworkInterface>, String> {
network::utils::get_non_empty_interfaces().map_err(|e| e.to_string())
}
| rust | MIT | 6f14e18294d389a167b041eed74e112064e00c00 | 2026-01-04T20:25:28.969475Z | false |
HuakunShen/tauri-plugin-network | https://github.com/HuakunShen/tauri-plugin-network/blob/6f14e18294d389a167b041eed74e112064e00c00/src/commands/mod.rs | src/commands/mod.rs | pub mod interface;
pub mod scan;
| rust | MIT | 6f14e18294d389a167b041eed74e112064e00c00 | 2026-01-04T20:25:28.969475Z | false |
HuakunShen/tauri-plugin-network | https://github.com/HuakunShen/tauri-plugin-network/blob/6f14e18294d389a167b041eed74e112064e00c00/src/commands/scan.rs | src/commands/scan.rs | use std::net::Ipv4Addr;
use ipnetwork::Ipv4Network;
use crate::network::{self, model::Ipv4NetworkSerialize, scan::IpPortPair};
#[tauri::command]
pub fn find_available_port() -> Result<u16, String> {
network::scan::find_available_port().map_err(|e| e.to_string())
}
#[tauri::command]
pub fn is_port_taken(port: u16) -> Result<bool, String> {
Ok(network::scan::is_port_taken(port))
}
#[tauri::command]
pub async fn is_http_port_open(
ip: String,
port: u16,
keyword: Option<String>,
) -> Result<bool, String> {
Ok(network::scan::is_http_port_open(ip, port, keyword).await)
}
#[tauri::command]
pub async fn scan_online_ip_port_pairs(
ip_port_pairs: Vec<IpPortPair>,
keyword: Option<String>,
) -> Result<Vec<IpPortPair>, String> {
Ok(network::scan::scan_online_ip_port_pairs(&ip_port_pairs, keyword).await)
}
#[tauri::command]
pub async fn scan_online_ips_by_port(
ips: Vec<Ipv4Addr>,
port: u16,
keyword: Option<String>,
) -> Result<Vec<Ipv4Addr>, String> {
Ok(network::scan::scan_online_ips(ips, port, keyword).await)
}
#[tauri::command]
pub async fn non_localhost_networks() -> Result<Vec<Ipv4NetworkSerialize>, String> {
network::scan::non_localhost_networks()
.map_err(|err| err.to_string())
.map(|networks| networks.into_iter().map(|network| network.into()).collect())
}
#[tauri::command]
pub async fn local_server_is_running(port: u16, keyword: Option<String>) -> Result<bool, String> {
Ok(network::scan::local_server_is_running(port, keyword).await)
}
#[tauri::command]
pub async fn scan_local_network_online_hosts_by_port(
port: u16,
keyword: Option<String>,
) -> Result<Vec<IpPortPair>, String> {
network::scan::scan_local_network_online_hosts_by_port(port, keyword)
.await
.map_err(|err| err.to_string())
}
| rust | MIT | 6f14e18294d389a167b041eed74e112064e00c00 | 2026-01-04T20:25:28.969475Z | false |
HuakunShen/tauri-plugin-network | https://github.com/HuakunShen/tauri-plugin-network/blob/6f14e18294d389a167b041eed74e112064e00c00/src/network/utils.rs | src/network/utils.rs | use crate::model::interface::NetworkInterface;
use network_interface as niface;
use network_interface::NetworkInterfaceConfig;
/// ```ignore
/// let prefix = octets_to_prefix([255, 255, 224, 0]);
/// assert_eq!(prefix, 19);
/// ```
pub fn octets_to_prefix(octets: [u8; 4]) -> u8 {
let mut prefix_len = 0;
// each octet is a u8 ranging from 0 to 255 (0x00 to 0xff)
for octet in &octets {
// 0x80 is 10000000 in binary
let mut bit_mask = 0x80; // Start with the leftmost bit
for _ in 0..8 {
if octet & bit_mask != 0 {
prefix_len += 1;
} else {
// when 8 bits of each byte match completely
break; // Break if a zero is encountered
}
bit_mask >>= 1; // Move to the next bit
}
}
prefix_len
}
pub fn get_interfaces() -> niface::Result<Vec<NetworkInterface>> {
let ifaces = niface::NetworkInterface::show()?
.iter()
.map(|iface| iface.into())
.collect();
Ok(ifaces)
}
pub fn get_interface_by_name(name: &str) -> niface::Result<NetworkInterface> {
let ifaces = get_interfaces()?;
let iface = ifaces.into_iter().find(|iface| iface.name == name).unwrap();
Ok(iface)
}
pub fn get_non_empty_interfaces() -> niface::Result<Vec<NetworkInterface>> {
let ifaces = get_interfaces()?;
let non_ifaces: Vec<NetworkInterface> = ifaces
.into_iter()
.filter(|iface| !iface.v4_addrs.is_empty())
.collect();
Ok(non_ifaces)
}
#[cfg(test)]
mod tests {
use super::super::constant::IPV4_MAPPING;
#[test]
// generate tests with a bunch of common netmask values
fn test_octets_to_prefix() {
// iterate IPV4_MAPPING and test each value
for (octets, prefix) in IPV4_MAPPING.iter() {
let prefix2 = super::octets_to_prefix(*octets);
assert_eq!(prefix, &prefix2);
}
}
}
| rust | MIT | 6f14e18294d389a167b041eed74e112064e00c00 | 2026-01-04T20:25:28.969475Z | false |
HuakunShen/tauri-plugin-network | https://github.com/HuakunShen/tauri-plugin-network/blob/6f14e18294d389a167b041eed74e112064e00c00/src/network/model.rs | src/network/model.rs | use ipnetwork::Ipv4Network;
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
pub struct Ipv4NetworkSerialize {
addr: String,
prefix: u8,
}
impl From<Ipv4Network> for Ipv4NetworkSerialize {
fn from(network: Ipv4Network) -> Self {
Ipv4NetworkSerialize {
addr: network.ip().to_string(),
prefix: network.prefix(),
}
}
} | rust | MIT | 6f14e18294d389a167b041eed74e112064e00c00 | 2026-01-04T20:25:28.969475Z | false |
HuakunShen/tauri-plugin-network | https://github.com/HuakunShen/tauri-plugin-network/blob/6f14e18294d389a167b041eed74e112064e00c00/src/network/mod.rs | src/network/mod.rs | pub mod constant;
pub mod scan;
pub mod utils;
pub mod model; | rust | MIT | 6f14e18294d389a167b041eed74e112064e00c00 | 2026-01-04T20:25:28.969475Z | false |
HuakunShen/tauri-plugin-network | https://github.com/HuakunShen/tauri-plugin-network/blob/6f14e18294d389a167b041eed74e112064e00c00/src/network/constant.rs | src/network/constant.rs | use lazy_static::lazy_static;
use std::collections::HashMap;
lazy_static! {
pub static ref IPV4_MAPPING: HashMap<[u8; 4], u8> = {
let mut map = HashMap::new();
map.insert([255, 255, 255, 255], 32);
map.insert([255, 255, 255, 254], 31);
map.insert([255, 255, 255, 252], 30);
map.insert([255, 255, 255, 248], 29);
map.insert([255, 255, 255, 240], 28);
map.insert([255, 255, 255, 224], 27);
map.insert([255, 255, 255, 192], 26);
map.insert([255, 255, 255, 128], 25);
map.insert([255, 255, 255, 0], 24);
map.insert([255, 255, 254, 0], 23);
map.insert([255, 255, 252, 0], 22);
map.insert([255, 255, 248, 0], 21);
map.insert([255, 255, 240, 0], 20);
map.insert([255, 255, 224, 0], 19);
map.insert([255, 255, 192, 0], 18);
map.insert([255, 255, 128, 0], 17);
map.insert([255, 255, 0, 0], 16);
map.insert([255, 254, 0, 0], 15);
map.insert([255, 252, 0, 0], 14);
map.insert([255, 248, 0, 0], 13);
map.insert([255, 240, 0, 0], 12);
map.insert([255, 224, 0, 0], 11);
map.insert([255, 192, 0, 0], 10);
map.insert([255, 128, 0, 0], 9);
map.insert([255, 0, 0, 0], 8);
map
};
}
| rust | MIT | 6f14e18294d389a167b041eed74e112064e00c00 | 2026-01-04T20:25:28.969475Z | false |
HuakunShen/tauri-plugin-network | https://github.com/HuakunShen/tauri-plugin-network/blob/6f14e18294d389a167b041eed74e112064e00c00/src/network/scan.rs | src/network/scan.rs | use futures::future::join_all;
use if_addrs::{get_if_addrs, IfAddr, Ifv4Addr, Ifv6Addr, Interface};
use ipnetwork::{IpNetworkError, Ipv4Network};
use reqwest;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::net::{Ipv4Addr, TcpListener};
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
use super::utils::{get_interfaces, octets_to_prefix};
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct IpPortPair {
pub ip: Ipv4Addr,
pub port: u16,
}
/// Find an available port
/// ```
/// use tauri_plugin_network::network::scan::find_available_port;
/// let port = find_available_port().unwrap();
/// assert!(port > 0);
/// ```
pub fn find_available_port() -> Result<u16, std::io::Error> {
// Try binding to port 0 to let the OS choose an available port.
let listener = TcpListener::bind("127.0.0.1:0")?;
let local_addr = listener.local_addr()?;
Ok(local_addr.port())
}
/// check if a port is occupied
/// ```
/// use tauri_plugin_network::network::scan::{is_port_taken};
/// let taken = is_port_taken(9876);
/// assert!(!taken);
/// ```
pub fn is_port_taken(port: u16) -> bool {
TcpListener::bind(("0.0.0.0", port)).is_err()
}
/// use multiple threads to find an available port from a list of candidate ports
/// ```
/// use tauri_plugin_network::network::scan::{find_available_port_from_list};
/// let candidate_ports = vec![80, 8081, 8082, 8083, 8084];
/// if let Some(port) = find_available_port_from_list(candidate_ports) {
/// println!("port {} is available", port);
/// assert!(port > 0);
/// } else {
/// println!("no available port");
/// }
/// ```
pub fn find_available_port_from_list(candidate_ports: Vec<u16>) -> Option<u16> {
let (tx, rx) = mpsc::channel();
let mut handles = vec![];
for port in candidate_ports {
let tx = tx.clone();
let handle = thread::spawn(move || {
let is_port_taken = is_port_taken(port);
tx.send((port, is_port_taken)).unwrap();
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
drop(tx);
for (port, is_port_taken) in rx {
if !is_port_taken {
return Some(port);
}
}
None
}
/// Verify is a port is open by checking the keyword. Check if returned text match exactly with the keyword
/// ```ignore
/// use tauri_plugin_network::network::scan::is_http_port_open_by_keyword;
/// let online = is_http_port_open("localhost".to_string(), 8000, None).await;
/// let online = is_http_port_open("localhost".to_string(), 8000, Some("CrossCopy".to_string())).await;
/// assert!(!online);
/// ```
pub async fn is_http_port_open(ip: String, port: u16, keyword: Option<String>) -> bool {
let scan_addr: String = format!("{}:{}", ip, port);
let url = format!("http://{}", scan_addr);
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(1))
.build()
.unwrap();
// let result = client.get(&url).send().await?;
// let response_text = result.text().await?;
// let is_open = match keyword {
// Some(keyword) => response_text == keyword,
// None => true,
// };
// Ok(false)
match client.get(&url).send().await {
Ok(result) => match result.text().await {
Ok(text) => match keyword {
Some(keyword) => text == keyword,
None => true,
},
Err(_) => false,
},
Err(_) => false,
}
}
/// Scan for online ips with given ip port pairs. If keyword is specified, check returned text; otherwise, only check if port is open
/// ```ignore
/// let ip = Ipv4Addr::new(127, 0, 0, 1);
/// let online_ips = scan_online_ip_port_pairs(
/// vec![(ip, 8000), (Ipv4Addr::new(192, 168, 1, 13), 9000)],
/// None,
/// ).await;
/// ```
pub async fn scan_online_ip_port_pairs(
ip_port_pairs: &[IpPortPair],
keyword: Option<String>,
) -> Vec<IpPortPair> {
let mut ret: Vec<IpPortPair> = Vec::new();
let mut handles = Vec::new();
for port_pair in ip_port_pairs.iter().copied() {
let c = tauri::async_runtime::spawn({
let keyword3 = keyword.clone();
async move {
is_http_port_open(port_pair.ip.clone().to_string(), port_pair.port, keyword3).await
}
});
handles.push(c);
}
let results = join_all(handles).await;
let results_list: Vec<_> = results.into_iter().map(|res| res.unwrap()).collect();
for (i, online) in results_list.iter().enumerate() {
if *online {
ret.push(ip_port_pairs[i]);
}
}
ret
}
/// Scan online ips with optional keyword and a fixed port. If keyword is specified, check returned text; otherwise, only check if port is open
pub async fn scan_online_ips(
ips: Vec<Ipv4Addr>,
port: u16,
keyword: Option<String>,
) -> Vec<Ipv4Addr> {
// construct ip port pairs
let ip_port_pairs: Vec<IpPortPair> = ips
.to_vec()
.iter()
.map(|ip| IpPortPair { ip: *ip, port })
.collect();
scan_online_ip_port_pairs(&ip_port_pairs, keyword)
.await
.into_iter()
.map(|pair| pair.ip)
.collect()
}
pub fn interface_to_network(ifv4_addr: Ifv4Addr) -> Result<Ipv4Network, IpNetworkError> {
let prefix = octets_to_prefix(ifv4_addr.netmask.octets());
let network = Ipv4Network::new(ifv4_addr.ip, prefix)?;
Ok(network)
}
pub fn ipv4_network_to_ips(network: Ipv4Network) -> Vec<Ipv4Addr> {
network.iter().collect::<Vec<Ipv4Addr>>()
}
pub fn get_network_interfaces() -> std::io::Result<Vec<if_addrs::Interface>> {
get_if_addrs()
}
pub fn is_ipv4_interface(if_addr: &if_addrs::Interface) -> bool {
is_ipv4_addr(&if_addr.addr)
}
pub fn is_ipv4_addr(addr: &IfAddr) -> bool {
match addr {
IfAddr::V4(_) => true,
IfAddr::V6(_) => false,
}
}
/// IfAddr can be either IfAddr::V4 ir IfAddr::V6, we return None if it's V6 and Some(V4) if it's V4
pub fn get_ipv4_addr(addr: IfAddr) -> Option<Ifv4Addr> {
match addr {
IfAddr::V4(ifv4_addr) => Some(ifv4_addr),
IfAddr::V6(_) => None,
}
}
pub fn get_ipv6_addr(addr: IfAddr) -> Option<Ifv6Addr> {
match addr {
IfAddr::V6(ifv6_addr) => Some(ifv6_addr),
IfAddr::V4(_) => None,
}
}
pub fn get_ipv4_interfaces() -> Vec<if_addrs::Interface> {
if let Ok(if_addrs) = get_network_interfaces() {
if_addrs
.iter()
.filter(|if_addr| is_ipv4_interface(if_addr))
.cloned()
.collect()
} else {
Vec::new()
}
}
/// Returns a HashMap of interface names and their corresponding Ipv4Network
pub fn get_ipv4_interface_networks_map() -> HashMap<String, Ipv4Network> {
let ipv4_interfaces = get_ipv4_interfaces();
let mut networks = HashMap::new();
for if_addr in ipv4_interfaces {
if let Some(ifv4_addr) = get_ipv4_addr(if_addr.addr) {
let network = interface_to_network(ifv4_addr).unwrap();
networks.insert(if_addr.name, network);
}
}
networks
}
/// ```
/// use tauri_plugin_network::network::scan::{get_ipv4_interface_networks};
/// let networks = get_ipv4_interface_networks();
/// for network in networks {
/// println!("Network: {}", network);
/// println!("\tNetwork Mask: {}", network.mask());
/// println!("\tNetwork IP: {}", network.ip());
/// println!("\tPrefix: {}", network.prefix());
/// }
/// ```
pub fn get_ipv4_interface_networks() -> Vec<Ipv4Network> {
let networks_map = get_ipv4_interface_networks_map();
networks_map.into_values().collect()
}
pub fn is_localhost(ip: &Ipv4Addr) -> bool {
ip.is_loopback()
}
pub fn is_loopback_interface(interface: &Interface) -> bool {
interface.is_loopback()
}
pub fn is_loopback_network(network: &Ipv4Network) -> bool {
network.ip().is_loopback()
}
pub fn filter_out_loopback_interfaces(interfaces: Vec<Interface>) -> Vec<Interface> {
interfaces
.into_iter()
.filter(|interface| !interface.is_loopback())
.collect()
}
/// Find all non-localhost IPV4 networks in all network interfaces
/// The interface without any IPV4 address is ignored
pub fn non_localhost_networks() -> Result<Vec<Ipv4Network>, network_interface::Error> {
let interfaces = get_interfaces()?;
let mut networks = Vec::new();
for iface in interfaces {
if !iface.v4_addrs.is_empty() {
let v4_addrs = iface.v4_addrs;
for ifaddr in v4_addrs {
if let Some(net) = ifaddr.network {
if !is_loopback_network(&net) {
networks.push(net);
}
}
}
}
}
Ok(networks)
}
pub async fn scan_local_network_online_hosts_by_port(
port: u16,
keyword: Option<String>,
) -> Result<Vec<IpPortPair>, network_interface::Error> {
let networks = non_localhost_networks()?;
let mut ip_port_pairs_to_scan: Vec<IpPortPair> = Vec::new();
for network in networks {
let ips = ipv4_network_to_ips(network);
for ip in ips {
ip_port_pairs_to_scan.push(IpPortPair { ip, port });
}
}
let online_ip_port_pairs = scan_online_ip_port_pairs(&ip_port_pairs_to_scan, keyword).await;
Ok(online_ip_port_pairs)
}
pub async fn local_server_is_running(port: u16, keyword: Option<String>) -> bool {
is_http_port_open("localhost".to_string(), port, keyword).await
}
/// ```
/// use tauri_plugin_network::network::scan::{get_ipv4_interface_networks, filter_out_loopback_networks};
/// let networks = get_ipv4_interface_networks();
/// let networks = filter_out_loopback_networks(networks);
/// ```
pub fn filter_out_loopback_networks(networks: Vec<Ipv4Network>) -> Vec<Ipv4Network> {
networks
.into_iter()
.filter(|network| !is_loopback_network(network))
.collect()
}
| rust | MIT | 6f14e18294d389a167b041eed74e112064e00c00 | 2026-01-04T20:25:28.969475Z | false |
HuakunShen/tauri-plugin-network | https://github.com/HuakunShen/tauri-plugin-network/blob/6f14e18294d389a167b041eed74e112064e00c00/examples/sveltekit/src-tauri/build.rs | examples/sveltekit/src-tauri/build.rs | fn main() {
tauri_build::build()
}
| rust | MIT | 6f14e18294d389a167b041eed74e112064e00c00 | 2026-01-04T20:25:28.969475Z | false |
HuakunShen/tauri-plugin-network | https://github.com/HuakunShen/tauri-plugin-network/blob/6f14e18294d389a167b041eed74e112064e00c00/examples/sveltekit/src-tauri/src/lib.rs | examples/sveltekit/src-tauri/src/lib.rs | use tauri::Manager;
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.plugin(tauri_plugin_network::init())
.setup(|app| {
#[cfg(debug_assertions)] // only inclupde this code on debug builds
{
let window = app.get_webview_window("main").unwrap();
window.open_devtools();
}
Ok(())
})
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
| rust | MIT | 6f14e18294d389a167b041eed74e112064e00c00 | 2026-01-04T20:25:28.969475Z | false |
HuakunShen/tauri-plugin-network | https://github.com/HuakunShen/tauri-plugin-network/blob/6f14e18294d389a167b041eed74e112064e00c00/examples/sveltekit/src-tauri/src/main.rs | examples/sveltekit/src-tauri/src/main.rs | // Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
app_lib::run();
}
| rust | MIT | 6f14e18294d389a167b041eed74e112064e00c00 | 2026-01-04T20:25:28.969475Z | false |
efernau/rot8 | https://github.com/efernau/rot8/blob/428221ea0990d90a2fce1f29be6d09af48d1874d/src/main.rs | src/main.rs | extern crate clap;
extern crate glob;
extern crate regex;
use std::fs;
use std::path::Path;
use std::process::Command;
use std::thread;
use std::time::Duration;
use clap::{App, Arg};
use glob::glob;
use wayland_client::protocol::wl_output::Transform;
mod backends;
use backends::{sway::SwayBackend, wlroots::WaylandBackend, xorg::XorgBackend, DisplayManager};
const ROT8_VERSION: &str = env!("CARGO_PKG_VERSION");
pub struct Orientation {
vector: (f32, f32),
wayland_state: Transform,
x_state: &'static str,
matrix: [&'static str; 9],
}
fn main() -> Result<(), String> {
let mut path_x: String = "".to_string();
let mut path_y: String = "".to_string();
let mut path_z: String = "".to_string();
let args = vec![
Arg::with_name("oneshot")
.long("oneshot")
.short('O')
.help("Instead of running continuously, just check the accelerometer and perform screen rotation if necessary once")
.takes_value(false),
Arg::with_name("sleep")
.default_value("500")
.long("sleep")
.short('s')
.value_name("SLEEP")
.help("Set sleep millis")
.takes_value(true),
Arg::with_name("display")
.default_value("eDP-1")
.long("display")
.short('d')
.value_name("DISPLAY")
.help("Set Display Device")
.takes_value(true),
Arg::with_name("touchscreen")
.default_value("ELAN0732:00 04F3:22E1")
.long("touchscreen")
.short('i')
.value_name("TOUCHSCREEN")
.help("Set Touchscreen input Device (X11 only)")
.min_values(1)
.takes_value(true),
Arg::with_name("threshold")
.default_value("0.5")
.long("threshold")
.short('t')
.value_name("THRESHOLD")
.help("Set a rotation threshold between 0 and 1")
.takes_value(true),
Arg::with_name("invert-x")
.long("invert-x")
.short('X')
.help("Invert readings from the HW x axis")
.takes_value(false),
Arg::with_name("invert-y")
.long("invert-y")
.short('Y')
.help("Invert readings from the HW y axis")
.takes_value(false),
Arg::with_name("invert-z")
.long("invert-z")
.short('Z')
.help("Invert readings from the HW z axis")
.takes_value(false),
Arg::with_name("invert-xy")
.default_value("xy")
.long("invert-xy")
.value_name("XY")
.help("Map hardware accelerometer axes to internal x and y respectively")
.possible_values(["xy", "yx", "zy", "yz", "xz", "zx"])
.takes_value(true),
Arg::with_name("normalization-factor")
.long("normalization-factor")
.short('n')
.value_name("NORMALIZATION_FACTOR")
.help("Set factor for sensor value normalization manually. By default this factor is calculated dynamically using the sensor's data.")
.takes_value(true),
Arg::with_name("keyboard")
.long("disable-keyboard")
.short('k')
.help("Disable keyboard for tablet modes (Sway only)")
.takes_value(false),
Arg::with_name("version")
.long("version")
.short('V')
.value_name("VERSION")
.help("Displays rot8 version")
.takes_value(false),
Arg::with_name("beforehooks")
.long("beforehooks")
.short('b')
.value_name("BEFOREHOOKS")
.help("Run hook(s) before screen rotation. Passes $ORIENTATION and $PREV_ORIENTATION to hooks. Comma-seperated.")
.takes_value(true)
.use_value_delimiter(true)
.require_value_delimiter(true),
Arg::with_name("hooks")
.long("hooks")
.short('h')
.value_name("HOOKS")
.help("Run hook(s) after screen rotation. Passes $ORIENTATION and $PREV_ORIENTATION to hooks. Comma-seperated.")
.takes_value(true)
.use_value_delimiter(true)
.require_value_delimiter(true)
];
let cmd_lines = App::new("rot8").version(ROT8_VERSION).args(&args);
let matches = cmd_lines.get_matches();
if matches.is_present("version") {
println!("{}", ROT8_VERSION);
return Ok(());
}
let oneshot = matches.is_present("oneshot");
let sleep = matches.value_of("sleep").unwrap_or("default.conf");
let display = matches.value_of("display").unwrap_or("default.conf");
let touchscreens: Vec<String> = matches.get_many("touchscreen").unwrap().cloned().collect();
let hooks: Vec<&str> = matches.values_of("hooks").unwrap_or_default().collect();
let beforehooks: Vec<&str> = matches
.values_of("beforehooks")
.unwrap_or_default()
.collect();
let disable_keyboard = matches.is_present("keyboard");
let threshold = matches.value_of("threshold").unwrap_or("default.conf");
let flip_x = matches.is_present("invert-x");
let flip_y = matches.is_present("invert-y");
let flip_z = matches.is_present("invert-z");
let mut xy = matches.value_of("invert-xy").unwrap_or("xy").chars();
let x_source = xy.next().unwrap();
let y_source = xy.next().unwrap();
let mut normalization_factor: Option<f32> = None;
if let Some(v) = matches.value_of("normalization-factor") {
match v.parse::<f32>() {
Ok(p) => normalization_factor = Some(p),
Err(_) => {
return Err(
"The argument 'normalization-factor' is no valid float literal".to_string(),
);
}
}
}
let mut backend: Box<dyn DisplayManager> = match WaylandBackend::new(display) {
Ok(wayland_backend) => {
if process_exists("sway") {
Box::new(SwayBackend::new(wayland_backend, disable_keyboard))
} else {
Box::new(wayland_backend)
}
}
Err(e) => {
if process_exists("Xorg") || process_exists("X") {
Box::new(XorgBackend::new(display, touchscreens))
} else {
return Err(format!(
"Unable to find supported Xorg process or wayland compositor: {}.",
e
));
}
}
};
for entry in glob("/sys/bus/iio/devices/iio:device*/in_accel_*_raw").unwrap() {
match entry {
Ok(path) => {
if path.to_str().unwrap().contains("x_raw") {
path_x = path.to_str().unwrap().to_owned();
} else if path.to_str().unwrap().contains("y_raw") {
path_y = path.to_str().unwrap().to_owned();
} else if path.to_str().unwrap().contains("z_raw") {
path_z = path.to_str().unwrap().to_owned();
}
}
Err(e) => println!("{:?}", e),
}
}
if !Path::new(&path_x).exists() && !Path::new(&path_y).exists() && !Path::new(&path_z).exists()
{
Err("Unknown Accelerometer Device".to_string())
} else {
let orientations = [
Orientation {
vector: (0.0, -1.0),
wayland_state: Transform::Normal,
x_state: "normal",
matrix: ["1", "0", "0", "0", "1", "0", "0", "0", "1"],
},
Orientation {
vector: (0.0, 1.0),
wayland_state: Transform::_180,
x_state: "inverted",
matrix: ["-1", "0", "1", "0", "-1", "1", "0", "0", "1"],
},
Orientation {
vector: (-1.0, 0.0),
wayland_state: Transform::_270,
x_state: "right",
matrix: ["0", "1", "0", "-1", "0", "1", "0", "0", "1"],
},
Orientation {
vector: (1.0, 0.0),
wayland_state: Transform::_90,
x_state: "left",
matrix: ["0", "-1", "1", "1", "0", "0", "0", "0", "1"],
},
];
let mut old_state = backend.get_rotation_state()?;
let mut current_orient: &Orientation = &orientations[0];
loop {
let x_raw = fs::read_to_string(path_x.as_str()).unwrap();
let y_raw = fs::read_to_string(path_y.as_str()).unwrap();
let z_raw = fs::read_to_string(path_z.as_str()).unwrap();
let x_clean = x_raw.trim_end_matches('\n').parse::<f32>().unwrap_or(0.);
let y_clean = y_raw.trim_end_matches('\n').parse::<f32>().unwrap_or(0.);
let z_clean = z_raw.trim_end_matches('\n').parse::<f32>().unwrap_or(0.);
// Normalize vectors
let norm_factor = normalization_factor.unwrap_or_else(|| {
f32::sqrt(x_clean * x_clean + y_clean * y_clean + z_clean * z_clean)
});
let mut mut_x: f32 = x_clean / norm_factor;
let mut mut_y: f32 = y_clean / norm_factor;
let mut mut_z: f32 = z_clean / norm_factor;
// Apply inversions
if flip_x {
mut_x = -mut_x;
}
if flip_y {
mut_y = -mut_y;
}
if flip_z {
mut_z = -mut_z;
}
// Switch axes as requested
let x = match x_source {
'y' => mut_y,
'z' => mut_z,
_ => mut_x,
};
let y = match y_source {
'x' => mut_x,
'z' => mut_z,
_ => mut_y,
};
for orient in orientations.iter() {
let d = (x - orient.vector.0).powf(2.0) + (y - orient.vector.1).powf(2.0);
if d < threshold.parse::<f32>().unwrap_or(0.5) {
current_orient = orient;
break;
}
}
if current_orient.wayland_state != old_state {
let old_env = transform_to_env(&old_state);
let new_env = transform_to_env(¤t_orient.wayland_state);
for bhook in beforehooks.iter() {
Command::new("bash")
.arg("-c")
.arg(bhook)
.env("ORIENTATION", new_env)
.env("PREV_ORIENTATION", old_env)
.spawn()
.expect("A hook failed to start.")
.wait()
.expect("Waiting for a hook failed.");
}
backend.change_rotation_state(current_orient);
for hook in hooks.iter() {
Command::new("bash")
.arg("-c")
.arg(hook)
.env("ORIENTATION", new_env)
.env("PREV_ORIENTATION", old_env)
.spawn()
.expect("A hook failed to start.")
.wait()
.expect("Waiting for a hook failed.");
}
old_state = current_orient.wayland_state;
}
if oneshot {
return Ok(());
}
thread::sleep(Duration::from_millis(sleep.parse::<u64>().unwrap_or(0)));
}
}
}
fn process_exists(proc_name: &str) -> bool {
!String::from_utf8(
Command::new("pidof")
.arg(proc_name)
.output()
.unwrap()
.stdout,
)
.unwrap()
.is_empty()
}
fn transform_to_env(transform: &Transform) -> &str {
match transform {
Transform::Normal => "normal",
Transform::_90 => "270",
Transform::_180 => "inverted",
Transform::_270 => "90",
_ => "normal",
}
}
| rust | MIT | 428221ea0990d90a2fce1f29be6d09af48d1874d | 2026-01-04T20:25:27.674044Z | false |
efernau/rot8 | https://github.com/efernau/rot8/blob/428221ea0990d90a2fce1f29be6d09af48d1874d/src/backends/wlroots.rs | src/backends/wlroots.rs | use wayland_client::{
event_created_child,
protocol::{wl_output::Transform, wl_registry},
Connection, Dispatch, EventQueue, QueueHandle,
};
use wayland_protocols_wlr::output_management::v1::client::{
zwlr_output_configuration_head_v1::{self, ZwlrOutputConfigurationHeadV1},
zwlr_output_configuration_v1::{self, ZwlrOutputConfigurationV1},
zwlr_output_head_v1::{self, ZwlrOutputHeadV1},
zwlr_output_manager_v1::{self, ZwlrOutputManagerV1},
zwlr_output_mode_v1::{self, ZwlrOutputModeV1},
};
use crate::Orientation;
use super::DisplayManager;
pub struct WaylandBackend {
state: AppData,
event_queue: EventQueue<AppData>,
}
impl WaylandBackend {
pub fn new(target_display: &str) -> Result<WaylandBackend, String> {
let conn = wayland_client::Connection::connect_to_env()
.map_err(|_| "Could not connect to wayland socket.")?;
let wl_display = conn.display();
let mut event_queue = conn.new_event_queue();
let _registry = wl_display.get_registry(&event_queue.handle(), ());
let mut state = AppData::new(&mut event_queue, target_display.to_string());
// Roundtrip twice to sync the outputs
for _ in 0..2 {
event_queue
.roundtrip(&mut state)
.map_err(|e| format!("Failed to communicate with the wayland socket: {}", e))?;
}
state
.output_manager
.as_ref()
.ok_or("Compositor does not support wlr_output_management_v1.")?;
Ok(WaylandBackend { state, event_queue })
}
/// Receive (and send) all buffered messages across the wayland socket.
fn read_socket(&mut self) {
self.event_queue
.roundtrip(&mut self.state)
.expect("Failed to read display changes.");
}
/// Send all buffered messages across the wayland socket.
/// Slightly cheaper than `read_socket`.
fn write_socket(&self) {
self.event_queue
.flush()
.expect("Failed to apply display changes.");
}
}
impl DisplayManager for WaylandBackend {
fn change_rotation_state(&mut self, new_state: &Orientation) {
self.read_socket();
self.state.update_configuration(new_state.wayland_state);
self.write_socket();
}
fn get_rotation_state(&mut self) -> Result<Transform, String> {
self.read_socket();
self.state
.current_transform
.ok_or("Failed to get current display rotation".into())
}
}
struct AppData {
target_display_name: String,
target_head: Option<ZwlrOutputHeadV1>,
output_manager: Option<ZwlrOutputManagerV1>,
current_config_serial: Option<u32>,
current_transform: Option<Transform>,
queue_handle: QueueHandle<AppData>,
}
/// Public interface
impl AppData {
pub fn new(event_queue: &mut EventQueue<AppData>, target_display_name: String) -> Self {
AppData {
target_display_name,
queue_handle: event_queue.handle(),
target_head: None,
output_manager: None,
current_config_serial: None,
current_transform: None,
}
}
pub fn update_configuration(&mut self, new_transform: Transform) {
if let (Some(output_manager), Some(serial), Some(head)) = (
&self.output_manager,
self.current_config_serial,
&self.target_head,
) {
let configuration = output_manager.create_configuration(serial, &self.queue_handle, ());
let head_config = configuration.enable_head(head, &self.queue_handle, ());
head_config.set_transform(new_transform);
configuration.apply();
}
}
}
/// Event handlers
impl Dispatch<wl_registry::WlRegistry, ()> for AppData {
fn event(
state: &mut Self,
registry: &wl_registry::WlRegistry,
event: wl_registry::Event,
_: &(),
_: &Connection,
qh: &QueueHandle<AppData>,
) {
if let wl_registry::Event::Global {
name,
interface,
version,
} = event
{
// println!("[{}] {} v{}", name, interface, version);
if interface == "zwlr_output_manager_v1" {
state.output_manager =
Some(registry.bind::<ZwlrOutputManagerV1, (), AppData>(name, version, qh, ()));
}
}
}
}
impl Dispatch<ZwlrOutputManagerV1, ()> for AppData {
fn event(
state: &mut Self,
_: &ZwlrOutputManagerV1,
event: zwlr_output_manager_v1::Event,
_: &(),
_: &Connection,
_: &QueueHandle<AppData>,
) {
if let zwlr_output_manager_v1::Event::Done { serial } = event {
// println!("Current config: {}", serial);
state.current_config_serial = Some(serial);
}
}
event_created_child!(AppData, ZwlrOutputHeadV1, [
zwlr_output_manager_v1::EVT_HEAD_OPCODE => (ZwlrOutputHeadV1, ()),
]);
}
impl Dispatch<ZwlrOutputHeadV1, ()> for AppData {
fn event(
state: &mut Self,
head: &ZwlrOutputHeadV1,
event: zwlr_output_head_v1::Event,
_: &(),
_: &Connection,
_: &QueueHandle<AppData>,
) {
match event {
zwlr_output_head_v1::Event::Name { name } => {
if name == state.target_display_name {
// println!("Found target display: {}", name);
state.target_head = Some(head.clone());
}
}
zwlr_output_head_v1::Event::Transform { transform } => {
state.current_transform = Some(transform.into_result().unwrap())
}
_ => {}
}
}
event_created_child!(AppData, ZwlrOutputModeV1, [
zwlr_output_head_v1::EVT_CURRENT_MODE_OPCODE => (ZwlrOutputModeV1, ()),
zwlr_output_head_v1::EVT_MODE_OPCODE => (ZwlrOutputModeV1, ()),
]);
}
impl Dispatch<ZwlrOutputModeV1, ()> for AppData {
fn event(
_state: &mut Self,
_: &ZwlrOutputModeV1,
_: zwlr_output_mode_v1::Event,
_: &(),
_: &Connection,
_: &QueueHandle<AppData>,
) {
}
}
impl Dispatch<ZwlrOutputConfigurationV1, ()> for AppData {
fn event(
_state: &mut Self,
config: &ZwlrOutputConfigurationV1,
event: zwlr_output_configuration_v1::Event,
_: &(),
_: &Connection,
_: &QueueHandle<AppData>,
) {
match event {
zwlr_output_configuration_v1::Event::Succeeded => {
// println!("Config applied successfully.");
config.destroy();
}
zwlr_output_configuration_v1::Event::Failed => {
// println!("Failed to apply new config.");
config.destroy();
}
zwlr_output_configuration_v1::Event::Cancelled => {
// println!("Config application cancelled.");
config.destroy();
}
_ => {}
}
}
}
impl Dispatch<ZwlrOutputConfigurationHeadV1, ()> for AppData {
fn event(
_state: &mut Self,
_: &ZwlrOutputConfigurationHeadV1,
_: zwlr_output_configuration_head_v1::Event,
_: &(),
_: &Connection,
_: &QueueHandle<AppData>,
) {
}
}
| rust | MIT | 428221ea0990d90a2fce1f29be6d09af48d1874d | 2026-01-04T20:25:27.674044Z | false |
efernau/rot8 | https://github.com/efernau/rot8/blob/428221ea0990d90a2fce1f29be6d09af48d1874d/src/backends/mod.rs | src/backends/mod.rs | use crate::Orientation;
use wayland_client::protocol::wl_output::Transform;
pub trait DisplayManager {
/// Change the orientation of the target display.
fn change_rotation_state(&mut self, new_state: &Orientation);
/// Get the current transformation of the target display.
fn get_rotation_state(&mut self) -> Result<Transform, String>;
}
pub mod sway;
pub mod wlroots;
pub mod xorg;
| rust | MIT | 428221ea0990d90a2fce1f29be6d09af48d1874d | 2026-01-04T20:25:27.674044Z | false |
efernau/rot8 | https://github.com/efernau/rot8/blob/428221ea0990d90a2fce1f29be6d09af48d1874d/src/backends/xorg.rs | src/backends/xorg.rs | use std::process::Command;
use wayland_client::protocol::wl_output::Transform;
use super::DisplayManager;
use crate::Orientation;
pub struct XorgBackend {
touchscreens: Vec<String>,
target_display: String,
}
impl XorgBackend {
pub fn new(display: &str, touchscreens: Vec<String>) -> Self {
XorgBackend {
target_display: display.into(),
touchscreens,
}
}
}
impl DisplayManager for XorgBackend {
fn change_rotation_state(&mut self, new_state: &Orientation) {
Command::new("xrandr")
.arg("-o")
.arg(new_state.x_state)
.spawn()
.expect("Xrandr rotate command failed to start")
.wait()
.expect("Xrandr rotate command wait failed");
// Support Touchscreen and Styli on some 2-in-1 devices
for touchscreen in &self.touchscreens {
Command::new("xinput")
.arg("set-prop")
.arg(touchscreen)
.arg("Coordinate Transformation Matrix")
.args(new_state.matrix)
.spawn()
.expect("Xinput rotate command failed to start")
.wait()
.expect("Xinput rotate command wait failed");
}
}
fn get_rotation_state(&mut self) -> Result<Transform, String> {
let raw_rotation_state = String::from_utf8(
Command::new("xrandr")
.output()
.expect("Xrandr get outputs command failed to start")
.stdout,
)
.unwrap();
let xrandr_output_pattern = regex::Regex::new(format!(
r"^{} connected .+? .*? (normal |inverted |left |right )?\(normal left inverted right x axis y axis\) .+$",
regex::escape(&self.target_display),
).as_str()).unwrap();
for xrandr_output_line in raw_rotation_state.split('\n') {
if !xrandr_output_pattern.is_match(xrandr_output_line) {
continue;
}
let xrandr_output_captures =
xrandr_output_pattern.captures(xrandr_output_line).unwrap();
if let Some(transform) = xrandr_output_captures.get(1) {
return Ok(match transform.as_str() {
"inverted" => Transform::_180,
"right" => Transform::_270,
"left" => Transform::_90,
_ => Transform::Normal,
});
} else {
return Ok(Transform::Normal);
}
}
Err(format!(
"Unable to determine rotation state: display {} not found in xrandr output",
self.target_display
))
}
}
| rust | MIT | 428221ea0990d90a2fce1f29be6d09af48d1874d | 2026-01-04T20:25:27.674044Z | false |
efernau/rot8 | https://github.com/efernau/rot8/blob/428221ea0990d90a2fce1f29be6d09af48d1874d/src/backends/sway.rs | src/backends/sway.rs | use std::process::Command;
use serde_json::Value;
use wayland_client::protocol::wl_output::Transform;
use crate::Orientation;
use super::{wlroots::WaylandBackend, DisplayManager};
pub struct SwayBackend {
wayland_backend: WaylandBackend,
manage_keyboard: bool,
}
impl SwayBackend {
pub fn new(wayland_backend: WaylandBackend, manage_keyboard: bool) -> Self {
SwayBackend {
wayland_backend,
manage_keyboard,
}
}
fn get_keyboards() -> Vec<String> {
let raw_inputs = String::from_utf8(
Command::new("swaymsg")
.arg("-t")
.arg("get_inputs")
.arg("--raw")
.output()
.expect("Swaymsg get inputs command failed")
.stdout,
)
.unwrap();
let mut keyboards = vec![];
let deserialized: Vec<Value> =
serde_json::from_str(&raw_inputs).expect("Unable to deserialize swaymsg JSON output");
for output in deserialized {
let input_type = output["type"].as_str().unwrap();
if input_type == "keyboard" {
keyboards.push(output["identifier"].to_string());
}
}
keyboards
}
}
impl DisplayManager for SwayBackend {
fn change_rotation_state(&mut self, new_state: &Orientation) {
self.wayland_backend.change_rotation_state(new_state);
if !self.manage_keyboard {
return;
}
let keyboard_state = if new_state.wayland_state == Transform::Normal {
"enabled"
} else {
"disabled"
};
for keyboard in &SwayBackend::get_keyboards() {
Command::new("swaymsg")
.arg("input")
.arg(keyboard)
.arg("events")
.arg(keyboard_state)
.spawn()
.expect("Swaymsg keyboard command failed to start")
.wait()
.expect("Swaymsg keyboard command wait failed");
}
}
fn get_rotation_state(&mut self) -> Result<Transform, String> {
self.wayland_backend.get_rotation_state()
}
}
| rust | MIT | 428221ea0990d90a2fce1f29be6d09af48d1874d | 2026-01-04T20:25:27.674044Z | false |
toshi0383/cmdshelf | https://github.com/toshi0383/cmdshelf/blob/590ec80b1e4c55b3d801cb4deafd379391d23f7b/src/corecli.rs | src/corecli.rs | use std::process::Command;
pub fn spawn(command: &str) -> Result<i32, ()> {
let child = if cfg!(target_os = "windows") {
Command::new("cmd")
.args(&["/C", command])
.spawn()
} else {
Command::new("sh")
.arg("-c")
.arg(command)
.spawn()
};
if let Ok(mut child) = child {
match child.wait() {
Ok(status) => Ok(status.code().unwrap()),
Err(_) => Ok(256),
}
} else {
Err(())
}
}
// TODO: read lines progressively
// https://doc.rust-lang.org/std/io/trait.BufRead.html
// https://doc.rust-lang.org/std/io/struct.Lines.html
pub fn get_stdout(command: &str) -> Result<String, String> {
let output = if cfg!(target_os = "windows") {
Command::new("cmd")
.args(&["/C", command])
.output()
} else {
Command::new("sh")
.arg("-c")
.arg(command)
.output()
};
output
.map(|output| format!("{}", String::from_utf8_lossy(&output.stdout)))
.map_err(|err| err.to_string())
}
| rust | Apache-2.0 | 590ec80b1e4c55b3d801cb4deafd379391d23f7b | 2026-01-04T20:25:28.323553Z | false |
toshi0383/cmdshelf | https://github.com/toshi0383/cmdshelf/blob/590ec80b1e4c55b3d801cb4deafd379391d23f7b/src/lib.rs | src/lib.rs | #[macro_use]
extern crate serde_derive;
extern crate toml;
pub mod reporter;
pub mod corecli;
pub mod commands;
pub mod context;
pub mod git;
| rust | Apache-2.0 | 590ec80b1e4c55b3d801cb4deafd379391d23f7b | 2026-01-04T20:25:28.323553Z | false |
toshi0383/cmdshelf | https://github.com/toshi0383/cmdshelf/blob/590ec80b1e4c55b3d801cb4deafd379391d23f7b/src/git.rs | src/git.rs | use context::Context;
use corecli::{ get_stdout };
use reporter;
use std::io::stdout;
use std::io::Write;
pub fn clone_remotes_if_needed(ctx: &Context) {
for r in &ctx.remotes {
let remote_dir = ctx.remote_alias_path(&r.alias);
let remote_dir_path = remote_dir.as_path();
if !remote_dir_path.exists() {
print!("[{}] Cloning ...", r.alias);
stdout().flush().expect("stdout().flush() failed.");
let cmd = format!("git clone {} {}", r.url, remote_dir_path.to_str().unwrap());
match get_stdout(&cmd) {
Ok(_) => reporter::successful("success".to_owned()),
Err(msg) => {
reporter::error("failed".to_owned());
println!("{}", msg);
},
}
}
}
}
pub fn update_or_clone_remotes(ctx: &Context) {
clone_remotes_if_needed(ctx);
for r in &ctx.remotes {
let remote_dir = ctx.remote_alias_path(&r.alias);
let remote_dir_path = remote_dir.as_path();
if remote_dir_path.exists() {
print!("[{}] Updating ...", r.alias);
stdout().flush().expect("stdout().flush() failed.");
let cmd = format!("cd {} && git fetch origin master && git checkout origin/master", remote_dir.to_str().unwrap());
match get_stdout(&cmd) {
Ok(_) => reporter::successful("success".to_owned()),
Err(msg) => {
reporter::error("failed".to_owned());
println!("{}", msg);
},
}
}
}
}
| rust | Apache-2.0 | 590ec80b1e4c55b3d801cb4deafd379391d23f7b | 2026-01-04T20:25:28.323553Z | false |
toshi0383/cmdshelf | https://github.com/toshi0383/cmdshelf/blob/590ec80b1e4c55b3d801cb4deafd379391d23f7b/src/reporter.rs | src/reporter.rs | use std::fmt;
use std::io::Write;
enum Color {
Red,
Green,
Yellow,
Reset,
}
impl fmt::Display for Color {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let s: &str = match self {
Color::Red => "\u{001B}[0;31m",
Color::Green => "\u{001B}[0;32m",
Color::Yellow => "\u{001B}[0;33m",
Color::Reset => "\u{001B}[0;0m",
};
write!(f, "{}", s)
}
}
fn _println<O>(out: &mut O, color: Color, message: String) where O: Write {
writeln!(
out,
"{}{}{}",
color,
message,
Color::Reset
).expect("Failed writing to stderr");
}
pub fn successful(message: String) {
_println(&mut ::std::io::stdout(), Color::Green, message);
}
pub fn error(message: String) {
_println(&mut ::std::io::stderr(), Color::Red, message);
}
pub fn warning(message: String) {
_println(&mut ::std::io::stdout(), Color::Yellow, message);
}
#[cfg(test)]
mod tests {
use super::{Color, _println};
#[test]
fn _println_with_color_red() {
let mut v: Vec<u8> = Vec::new();
_println(&mut v, Color::Red, "__test__".to_string());
assert_eq!(String::from_utf8(v).unwrap(), "\u{1b}[0;31m__test__\u{1b}[0;0m\n");
}
#[test]
fn _println_with_color_green() {
let mut v: Vec<u8> = Vec::new();
_println(&mut v, Color::Green, "__test__".to_string());
assert_eq!(String::from_utf8(v).unwrap(), "\u{1b}[0;32m__test__\u{1b}[0;0m\n");
}
#[test]
fn _println_with_color_yellow() {
let mut v: Vec<u8> = Vec::new();
_println(&mut v, Color::Yellow, "__test__".to_string());
assert_eq!(String::from_utf8(v).unwrap(), "\u{1b}[0;33m__test__\u{1b}[0;0m\n");
}
#[test]
fn _println_with_color_reset() {
let mut v: Vec<u8> = Vec::new();
_println(&mut v, Color::Reset, "__test__".to_string());
assert_eq!(String::from_utf8(v).unwrap(), "\u{1b}[0;0m__test__\u{1b}[0;0m\n");
}
} | rust | Apache-2.0 | 590ec80b1e4c55b3d801cb4deafd379391d23f7b | 2026-01-04T20:25:28.323553Z | false |
toshi0383/cmdshelf | https://github.com/toshi0383/cmdshelf/blob/590ec80b1e4c55b3d801cb4deafd379391d23f7b/src/main.rs | src/main.rs | extern crate cmdshelf;
use std::process::{ exit };
use std::env;
use cmdshelf::reporter;
use cmdshelf::commands::Runnable;
use cmdshelf::commands;
const VERSION: &str = "2.0.2";
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
commands::help_command().run([].to_vec()).ok();
return
}
if args[1] == "--help" {
commands::help_command().run([].to_vec()).ok();
return
}
if args[1] == "--version" {
println!("{}", VERSION);
return
}
let mut _args = args;
let args_remainder = _args.split_off(2);
let status = commands::sub_command(&_args[1])
.and_then(|mut sub_command: Box<dyn Runnable + 'static>| -> Result<i32, String> {
sub_command.run(args_remainder)
.or_else(|msg| {
reporter::error(format!("cmdshelf {}: {} ", sub_command.name(), msg));
Ok(1)
})
})
.or_else(|msg: String| -> Result<i32, String> {
reporter::error(format!("cmdshelf: {}", msg));
Ok(1)
})
.unwrap();
exit(status)
}
| rust | Apache-2.0 | 590ec80b1e4c55b3d801cb4deafd379391d23f7b | 2026-01-04T20:25:28.323553Z | false |
toshi0383/cmdshelf | https://github.com/toshi0383/cmdshelf/blob/590ec80b1e4c55b3d801cb4deafd379391d23f7b/src/context.rs | src/context.rs | extern crate is_executable;
extern crate walkdir;
use self::walkdir::{ WalkDir, DirEntry };
use self::is_executable::IsExecutable;
use std::path::{ Path, PathBuf, MAIN_SEPARATOR };
use std::error::Error;
use std::fmt;
use std::fs;
use toml;
pub struct Context {
pub remotes: Vec<RemoteConfig>,
pub workspace_dir: String,
}
pub struct CommandEntry<'a> {
pub remote: &'a str,
pub fullpath: String,
}
impl<'a> CommandEntry<'a> {
pub fn new(remote: &'a str, fullpath: String) -> Self {
CommandEntry {
remote: remote,
fullpath: fullpath,
}
}
pub fn path(&self) -> &str {
let s = format!("{}{}", self.remote, MAIN_SEPARATOR);
let paths = self.fullpath.split(&s).collect::<Vec<&str>>();
let command_path = paths.last();
command_path.unwrap()
}
}
impl<'a> Context {
pub fn new() -> Self {
let toml = default_toml_path();
let config = read_or_create_config(toml.as_path());
let mut remotes = Vec::new();
for r in config.remotes {
remotes.push(r.clone());
}
let mut workspace_dir = get_homedir_path().expect("");
workspace_dir.push(".cmdshelf");
Context {
remotes: remotes,
workspace_dir: workspace_dir.as_path().to_str().unwrap().to_owned(),
}
}
pub fn remote_alias_path(&self, alias: &str) -> PathBuf {
let mut remote_dir = Path::new(&self.workspace_dir).join("remote");
remote_dir.push(alias);
remote_dir
}
/// returns: command's fullpath
/// Err if not exists or not an executable
pub fn command_path(&self, arg: &str) -> Result<PathBuf, String> {
let vec: Vec<&str> = arg.split(":").collect();
match vec.len() {
1 => {
for remote in &self.remotes {
let result: Option<Result<PathBuf, String>> = match self.get_path(&remote.alias, &vec[0]) {
Ok(path) => Option::Some(Ok(path)),
Err(err) => {
match &err {
FileError::NotFound(_) => None,
FileError::NotExecutable(_) => Option::Some(Err(err.description_())),
FileError::NoHomeDir => Option::Some(Err(err.description_())),
}
},
};
if let Some(result) = result {
return result;
}
}
Err(format!("No such command: {}", arg))
},
2 => {
self.get_path(&vec[0], &vec[1])
.map_err(|e| e.description_())
},
_ => panic!(),
}
}
pub fn all_commandentries(&'a self) -> Vec<CommandEntry<'a>> {
// TODO: use flat_map. Did not compile.
let mut arr = Vec::new();
for remote in self.remotes.iter() {
let mut remote_base = Path::new(&self.workspace_dir)
.join("remote");
remote_base.push(&remote.alias);
//
// recursive children using walkdir lib.
//
fn is_hidden(entry: &DirEntry) -> bool {
entry.file_name()
.to_str()
.map(|s| s.starts_with("."))
.unwrap_or(false)
}
for entry in WalkDir::new(remote_base)
.follow_links(true)
.into_iter()
.filter_entry(|e| !is_hidden(e)) {
let tmp = entry.unwrap();
let fullpath = tmp.path();
let is_git = {
let tmp = fullpath.to_str().unwrap();
let components: Vec<&str> = tmp.split(MAIN_SEPARATOR).collect();
components.contains(&".git")
};
if is_git || !fullpath.is_file() || !fullpath.is_executable() {
continue;
}
let fullpath_string = fullpath.to_str().unwrap().to_owned();
let commandentry = CommandEntry::new(&remote.alias, fullpath_string);
arr.push(commandentry);
}
}
arr
}
fn get_path(&self, remote: &str, path: &str) -> Result<PathBuf, FileError> {
let result = get_homedir_path()
.map(|home| {
let mut buf = home.join(".cmdshelf");
buf.push("remote");
buf.push(remote);
buf.push(path);
return buf
});
self.validate_path(result)
}
fn validate_path(&self, result: Result<PathBuf, FileError>) -> Result<PathBuf, FileError> {
match result {
Ok(p) => {
let path = p.as_path();
if path.exists() {
let s = path.to_str().unwrap().to_owned();
if p.is_executable() {
return Ok(path.to_path_buf());
} else {
return Err(FileError::NotExecutable(s));
}
}
Err(FileError::NotFound(path.to_str().unwrap().to_owned()))
},
result @ Err(_) => result
}
}
pub fn remove_remote(&self, alias: &str) -> Result<(), String> {
let toml = default_toml_path();
let mut config = read_or_create_config(toml.as_path());
let mut remotes = config.remotes.to_vec();
let mut index: Option<usize> = None;
for (i, r) in remotes.iter().enumerate() {
if r.alias == alias {
index = Some(i);
break;
}
}
if let Some(i) = index {
remotes.remove(i);
}
config.remotes = remotes;
let s = toml::to_string(&config).unwrap();
fs::write(&toml, s)
.map_err(|_| format!("failed to write toml at: {}", toml.as_path().to_str().unwrap()))
}
pub fn add_or_update_remote(&self, alias: &str, url: &str) -> Result<(), String> {
let toml = default_toml_path();
let mut config = read_or_create_config(toml.as_path());
// check for duplicate
{
let remotes = config.remotes.clone().to_vec();
for r in remotes {
if r.alias.as_str() == alias {
return Err(format!("remote alias '{}' already exists.", alias).to_owned());
}
}
}
let remote = RemoteConfig {
alias: alias.to_owned(),
url: url.to_owned(),
};
let mut remotes = config.remotes.to_vec();
remotes.push(remote);
config.remotes = remotes;
let s = toml::to_string(&config).unwrap();
fs::write(&toml, s)
.map_err(|_| format!("failed to write toml at: {}", toml.as_path().to_str().unwrap()))
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct Config {
remotes: Vec<RemoteConfig>,
}
impl Config {
fn new() -> Self {
Config {
remotes: vec![],
}
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct RemoteConfig {
pub alias: String,
pub url: String,
}
impl Clone for RemoteConfig {
fn clone(&self) -> RemoteConfig {
RemoteConfig {
alias: self.alias.clone(),
url: self.url.clone(),
}
}
}
#[derive(Debug)]
enum FileError {
NotFound(String),
NotExecutable(String),
NoHomeDir,
}
impl Error for FileError {
fn description(&self) -> &str {
""
}
}
impl FileError {
fn description_(&self) -> String {
match self {
FileError::NotFound(string) => format!("No such command: {}", string),
FileError::NotExecutable(string) => format!("Permission denied: {}", string),
FileError::NoHomeDir => "No HOME directory specified".to_owned(),
}
}
}
impl fmt::Display for FileError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "invalid first item to double")
}
}
fn get_homedir_path() -> Result<PathBuf, FileError> {
dirs::home_dir()
.map(|p| p.canonicalize().expect("failed to canonizalize"))
.ok_or(FileError::NoHomeDir)
}
fn read_or_create_config(path: &Path) -> Config {
let config: Config = match fs::read_to_string(path) {
Ok(contents) => {
toml::from_str(&contents)
.unwrap_or_else(|_| create_new_config(path))
},
Err(_) => {
create_new_config(path)
},
};
config
}
fn create_new_config(path: &Path) -> Config {
let config = Config::new();
let s = toml::to_string(&config).unwrap();
fs::write(path.to_str().unwrap(), s).expect("failed to write toml");
config
}
fn default_toml_path() -> PathBuf {
let mut home = get_homedir_path().expect("");
home.push(".cmdshelf.toml");
home
}
| rust | Apache-2.0 | 590ec80b1e4c55b3d801cb4deafd379391d23f7b | 2026-01-04T20:25:28.323553Z | false |
toshi0383/cmdshelf | https://github.com/toshi0383/cmdshelf/blob/590ec80b1e4c55b3d801cb4deafd379391d23f7b/src/commands/update.rs | src/commands/update.rs | use super::Runnable;
use context::Context;
use git;
pub struct Update {
}
impl Runnable for Update {
fn name(&self) -> String {
return "update".to_owned()
}
fn run(&mut self, _: Vec<String>) -> Result<i32, String> {
let ctx = Context::new();
git::update_or_clone_remotes(&ctx);
Ok(0)
}
}
| rust | Apache-2.0 | 590ec80b1e4c55b3d801cb4deafd379391d23f7b | 2026-01-04T20:25:28.323553Z | false |
toshi0383/cmdshelf | https://github.com/toshi0383/cmdshelf/blob/590ec80b1e4c55b3d801cb4deafd379391d23f7b/src/commands/list.rs | src/commands/list.rs | use super::Runnable;
use context::Context;
use git;
pub struct List {
}
impl Runnable for List {
fn name(&self) -> String {
return "list".to_owned()
}
fn run(&mut self, args: Vec<String>) -> Result<i32, String> {
let is_fullpath = args.contains(&"--path".to_owned());
let ctx = Context::new();
git::clone_remotes_if_needed(&ctx);
for command_entry in &ctx.all_commandentries() {
let path_str: String = if is_fullpath {
command_entry.fullpath.to_owned()
} else {
format!("{}:{}", command_entry.remote, command_entry.path())
};
println!("{}", path_str);
}
Ok(0)
}
}
| rust | Apache-2.0 | 590ec80b1e4c55b3d801cb4deafd379391d23f7b | 2026-01-04T20:25:28.323553Z | false |
toshi0383/cmdshelf | https://github.com/toshi0383/cmdshelf/blob/590ec80b1e4c55b3d801cb4deafd379391d23f7b/src/commands/help.rs | src/commands/help.rs | use super::Runnable;
use corecli::spawn;
use std::fmt;
#[derive(Copy,Clone)]
enum HelpPage {
Run,
Cat,
List,
Remote,
Update,
Default,
}
impl HelpPage {
fn from(arg: &str) -> HelpPage {
match arg {
"run" => HelpPage::Run,
"cat" => HelpPage::Cat,
"list" => HelpPage::List,
"ls" => HelpPage::List,
"remote" => HelpPage::Remote,
"update" => HelpPage::Update,
_ => HelpPage::Default,
}
}
fn manpage(&self) -> String {
format!("cmdshelf-{}", self)
}
}
impl fmt::Display for HelpPage {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let printable = match *self {
HelpPage::Default => "default",
HelpPage::Run => "run",
HelpPage::Cat => "cat",
HelpPage::List => "list",
HelpPage::Remote => "remote",
HelpPage::Update => "update",
};
write!(f, "{}", printable)
}
}
pub struct Help {
}
impl Runnable for Help {
fn name(&self) -> String {
return "help".to_owned()
}
fn run(&mut self, args: Vec<String>) -> Result<i32, String> {
let helppage = {
if args.len() < 1 {
HelpPage::Default
} else {
HelpPage::from(&args[0])
}
};
let manpage = match helppage {
HelpPage::Default => "cmdshelf".to_owned(),
_ => helppage.manpage(),
};
println!("{}", manpage);
let cmd = format!("man {} | ${{PAGER:-more}}", manpage);
spawn(&cmd)
.map_err(|_| "Failed to spawn man-page process.".to_owned())
}
}
| rust | Apache-2.0 | 590ec80b1e4c55b3d801cb4deafd379391d23f7b | 2026-01-04T20:25:28.323553Z | false |
toshi0383/cmdshelf | https://github.com/toshi0383/cmdshelf/blob/590ec80b1e4c55b3d801cb4deafd379391d23f7b/src/commands/remote.rs | src/commands/remote.rs | use super::Runnable;
use context::Context;
use std::path::MAIN_SEPARATOR;
pub struct Remote {
}
impl Runnable for Remote {
fn name(&self) -> String {
return "remote".to_owned()
}
fn run(&mut self, args: Vec<String>) -> Result<i32, String> {
if args.len() < 1 {
return Err("missing arguments".to_owned())
}
let mut _args = args;
let args_remainder = _args.split_off(1);
sub_command(&_args[0])
.and_then(|mut c| c.run(args_remainder))
}
}
fn sub_command(arg: &str) -> Result<Box<dyn Runnable + 'static>, String> {
match arg {
"add" => Ok(Box::new(Add { })),
"remove" => Ok(Box::new(Remove { })),
"list" => Ok(Box::new(List { })),
"ls" => Ok(Box::new(List { })),
_ => Err(format!("invalid argument: {}", arg)),
}
}
struct Add {
}
impl Runnable for Add {
fn name(&self) -> String {
return "add".to_owned()
}
fn run(&mut self, args: Vec<String>) -> Result<i32, String> {
if args.len() < 2 {
return Err("add: missing arguments".to_owned());
}
let alias = &args[0];
let a = &args[1];
let url =
if !(a.starts_with("https") || a.starts_with("git"))
&& a.split(MAIN_SEPARATOR).collect::<Vec<&str>>().len() == 2 {
format!("git@github.com:{}.git", a)
} else {
format!("{}", a)
};
let ctx = Context::new();
ctx.add_or_update_remote(alias, &url)
.and(Ok(0))
}
}
struct Remove {
}
impl Runnable for Remove {
fn name(&self) -> String {
return "remove".to_owned()
}
fn run(&mut self, args: Vec<String>) -> Result<i32, String> {
if args.len() < 1 {
return Err("remove: missing arguments".to_owned());
}
let alias = &args[0];
let ctx = Context::new();
ctx.remove_remote(alias)
.and(Ok(0))
}
}
struct List {
}
impl Runnable for List {
fn name(&self) -> String {
return "list".to_owned()
}
fn run(&mut self, _: Vec<String>) -> Result<i32, String> {
let ctx = Context::new();
for r in ctx.remotes {
println!("{}:{}", &r.alias, &r.url);
}
Ok(0)
}
}
| rust | Apache-2.0 | 590ec80b1e4c55b3d801cb4deafd379391d23f7b | 2026-01-04T20:25:28.323553Z | false |
toshi0383/cmdshelf | https://github.com/toshi0383/cmdshelf/blob/590ec80b1e4c55b3d801cb4deafd379391d23f7b/src/commands/mod.rs | src/commands/mod.rs | mod cat;
mod help;
mod list;
mod remote;
mod run;
mod update;
use self::cat::Cat;
use self::help::Help;
use self::list::List;
use self::remote::Remote;
use self::run::Run;
use self::update::Update;
pub trait Runnable {
fn name(&self) -> String;
fn run(&mut self, args: Vec<String>) -> Result<i32, String>;
}
pub fn help_command() -> Box<dyn Runnable + 'static> {
Box::new(Help { })
}
pub fn sub_command(string: &str) -> Result<Box<dyn Runnable + 'static>, String> {
match string.as_ref() {
"cat" => Ok(Box::new(Cat { })),
"list" => Ok(Box::new(List { })),
"ls" => Ok(Box::new(List { })),
"remote" => Ok(Box::new(Remote { })),
"run" => Ok(Box::new(Run { })),
"update" => Ok(Box::new(Update { })),
"help" => Ok(Box::new(Help { })),
_ => Err(format!("no such command: {}", string)),
}
}
| rust | Apache-2.0 | 590ec80b1e4c55b3d801cb4deafd379391d23f7b | 2026-01-04T20:25:28.323553Z | false |
toshi0383/cmdshelf | https://github.com/toshi0383/cmdshelf/blob/590ec80b1e4c55b3d801cb4deafd379391d23f7b/src/commands/run.rs | src/commands/run.rs | use super::Runnable;
use context::Context;
use corecli::spawn;
use git;
pub struct Run {
}
impl Runnable for Run {
fn name(&self) -> String {
return "run".to_owned()
}
fn run(&mut self, args: Vec<String>) -> Result<i32, String> {
if args.len() == 0 {
return Err("missing argument".to_owned());
}
let arg = &args[0];
let ctx = Context::new();
git::clone_remotes_if_needed(&ctx);
ctx.command_path(arg)
.and_then(|executable_fullpath| {
let args = &args[1..];
let mut args: Vec<String> = args.into_iter().map(|x| format!("'{}'", x)).collect();
let executable_fullpath = executable_fullpath.as_path().to_str().unwrap();
args.insert(0, executable_fullpath.to_owned());
let command = args.join(" ");
spawn(&command)
.map_err(|()| "failed to execute command".to_owned())
})
}
}
| rust | Apache-2.0 | 590ec80b1e4c55b3d801cb4deafd379391d23f7b | 2026-01-04T20:25:28.323553Z | false |
toshi0383/cmdshelf | https://github.com/toshi0383/cmdshelf/blob/590ec80b1e4c55b3d801cb4deafd379391d23f7b/src/commands/cat.rs | src/commands/cat.rs | use super::Runnable;
use context::Context;
use corecli::spawn;
use git;
pub struct Cat {
}
impl Runnable for Cat {
fn name(&self) -> String {
return "cat".to_owned()
}
fn run(&mut self, args: Vec<String>) -> Result<i32, String> {
if args.len() == 0 {
return Err("missing argument".to_owned());
}
let arg = &args[0];
let ctx = Context::new();
git::clone_remotes_if_needed(&ctx);
ctx.command_path(arg)
.and_then(|executable_fullpath| {
let executable_fullpath = executable_fullpath.as_path().to_str().unwrap();
let cmd = format!("cat {}", executable_fullpath.to_owned());
spawn(&cmd)
.map_err(|()| "failed to execute command".to_owned())
})
}
}
| rust | Apache-2.0 | 590ec80b1e4c55b3d801cb4deafd379391d23f7b | 2026-01-04T20:25:28.323553Z | false |
CurrySoftware/rust-stemmers | https://github.com/CurrySoftware/rust-stemmers/blob/1fde09dfa08fb0fb07fbd6570aba8ecc98174edb/src/lib.rs | src/lib.rs | //! This library provides rust implementations for some stemmer algorithms
//! written in the [snowball language](https://snowballstem.org/).
//!
//!
//! All algorithms expect the input to already be lowercased.
//!
//! # Usage
//! ```toml
//! [dependencies]
//! rust-stemmers = "^1.0"
//! ```
//!
//! ```rust
//! extern crate rust_stemmers;
//!
//! use rust_stemmers::{Algorithm, Stemmer};
//!
//! fn main() {
//! let en_stemmer = Stemmer::create(Algorithm::English);
//! assert_eq!(en_stemmer.stem("fruitlessly"), "fruitless");
//! }
//! ```
extern crate serde;
#[macro_use]
extern crate serde_derive;
use std::borrow::Cow;
mod snowball;
use snowball::SnowballEnv;
use snowball::algorithms;
/// Enum of all supported algorithms.
/// Check the [Snowball-Website](https://snowballstem.org/) for details.
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Copy, Clone)]
pub enum Algorithm {
Arabic,
Armenian,
Danish,
Dutch,
English,
Finnish,
French,
German,
Greek,
Hungarian,
Italian,
Norwegian,
Portuguese,
Romanian,
Russian,
Spanish,
Swedish,
Tamil,
Turkish
}
/// Wrapps a usable interface around the actual stemmer implementation
pub struct Stemmer {
stemmer: fn(&mut SnowballEnv) -> bool,
}
impl Stemmer {
/// Create a new stemmer from an algorithm
pub fn create(lang: Algorithm) -> Self {
match lang {
Algorithm::Arabic => Stemmer { stemmer: algorithms::arabic::stem },
Algorithm::Armenian => Stemmer { stemmer: algorithms::armenian::stem },
Algorithm::Danish => Stemmer { stemmer: algorithms::danish::stem },
Algorithm::Dutch => Stemmer { stemmer: algorithms::dutch::stem },
Algorithm::English => Stemmer { stemmer: algorithms::english::stem },
Algorithm::Finnish => Stemmer { stemmer: algorithms::finnish::stem },
Algorithm::French => Stemmer { stemmer: algorithms::french::stem },
Algorithm::German => Stemmer { stemmer: algorithms::german::stem },
Algorithm::Greek => Stemmer { stemmer: algorithms::greek::stem },
Algorithm::Hungarian => Stemmer { stemmer: algorithms::hungarian::stem },
Algorithm::Italian => Stemmer { stemmer: algorithms::italian::stem },
Algorithm::Norwegian => Stemmer { stemmer: algorithms::norwegian::stem },
Algorithm::Portuguese => Stemmer { stemmer: algorithms::portuguese::stem },
Algorithm::Romanian => Stemmer { stemmer: algorithms::romanian::stem },
Algorithm::Russian => Stemmer { stemmer: algorithms::russian::stem },
Algorithm::Spanish => Stemmer { stemmer: algorithms::spanish::stem },
Algorithm::Swedish => Stemmer { stemmer: algorithms::swedish::stem },
Algorithm::Tamil => Stemmer { stemmer: algorithms::tamil::stem },
Algorithm::Turkish => Stemmer { stemmer: algorithms::turkish::stem },
}
}
/// Stem a single word
/// Please note, that the input is expected to be all lowercase (if that is applicable).
pub fn stem<'a>(&self, input: &'a str) -> Cow<'a, str> {
let mut env = SnowballEnv::create(input);
(self.stemmer)(&mut env);
env.get_current()
}
}
#[cfg(test)]
mod tests {
use super::{Stemmer, Algorithm};
fn stemms_to(lhs: &str, rhs: &str, stemmer: Algorithm) {
assert_eq!(Stemmer::create(stemmer).stem(lhs), rhs);
}
#[test]
fn german_test() {
use std::fs;
use std::io;
use std::io::BufRead;
let vocab = io::BufReader::new(fs::File::open("test_data/voc_ger.txt").unwrap());
let result = io::BufReader::new(fs::File::open("test_data/res_ger.txt").unwrap());
let lines = vocab.lines().zip(result.lines());
for (voc, res) in lines {
stemms_to(voc.unwrap().as_str(),
res.unwrap().as_str(),
Algorithm::German);
}
}
#[test]
fn english_test() {
use std::fs;
use std::io;
use std::io::BufRead;
let vocab = io::BufReader::new(fs::File::open("test_data/voc_en.txt").unwrap());
let result = io::BufReader::new(fs::File::open("test_data/res_en.txt").unwrap());
let lines = vocab.lines().zip(result.lines());
for (voc, res) in lines {
stemms_to(voc.unwrap().as_str(),
res.unwrap().as_str(),
Algorithm::English);
}
}
#[test]
fn french_test() {
use std::fs;
use std::io;
use std::io::BufRead;
let vocab = io::BufReader::new(fs::File::open("test_data/voc_fr.txt").unwrap());
let result = io::BufReader::new(fs::File::open("test_data/res_fr.txt").unwrap());
let lines = vocab.lines().zip(result.lines());
for (voc, res) in lines {
stemms_to(voc.unwrap().as_str(),
res.unwrap().as_str(),
Algorithm::French);
}
}
#[test]
fn spanish_test() {
use std::fs;
use std::io;
use std::io::BufRead;
let vocab = io::BufReader::new(fs::File::open("test_data/voc_es.txt").unwrap());
let result = io::BufReader::new(fs::File::open("test_data/res_es.txt").unwrap());
let lines = vocab.lines().zip(result.lines());
for (voc, res) in lines {
stemms_to(voc.unwrap().as_str(),
res.unwrap().as_str(),
Algorithm::Spanish);
}
}
#[test]
fn portuguese_test() {
use std::fs;
use std::io;
use std::io::BufRead;
let vocab = io::BufReader::new(fs::File::open("test_data/voc_pt.txt").unwrap());
let result = io::BufReader::new(fs::File::open("test_data/res_pt.txt").unwrap());
let lines = vocab.lines().zip(result.lines());
for (voc, res) in lines {
stemms_to(voc.unwrap().as_str(),
res.unwrap().as_str(),
Algorithm::Portuguese);
}
}
#[test]
fn italian_test() {
use std::fs;
use std::io;
use std::io::BufRead;
let vocab = io::BufReader::new(fs::File::open("test_data/voc_it.txt").unwrap());
let result = io::BufReader::new(fs::File::open("test_data/res_it.txt").unwrap());
let lines = vocab.lines().zip(result.lines());
for (voc, res) in lines {
stemms_to(voc.unwrap().as_str(),
res.unwrap().as_str(),
Algorithm::Italian);
}
}
#[test]
fn romanian_test() {
use std::fs;
use std::io;
use std::io::BufRead;
let vocab = io::BufReader::new(fs::File::open("test_data/voc_ro.txt").unwrap());
let result = io::BufReader::new(fs::File::open("test_data/res_ro.txt").unwrap());
let lines = vocab.lines().zip(result.lines());
for (voc, res) in lines {
stemms_to(voc.unwrap().as_str(),
res.unwrap().as_str(),
Algorithm::Romanian);
}
}
#[test]
fn russian_test() {
use std::fs;
use std::io;
use std::io::BufRead;
let vocab = io::BufReader::new(fs::File::open("test_data/voc_ru.txt").unwrap());
let result = io::BufReader::new(fs::File::open("test_data/res_ru.txt").unwrap());
let lines = vocab.lines().zip(result.lines());
for (voc, res) in lines {
stemms_to(voc.unwrap().as_str(),
res.unwrap().as_str(),
Algorithm::Russian);
}
}
#[test]
fn arabic_test() {
use std::fs;
use std::io;
use std::io::BufRead;
let vocab = io::BufReader::new(fs::File::open("test_data/voc_ar.txt").unwrap());
let result = io::BufReader::new(fs::File::open("test_data/res_ar.txt").unwrap());
let lines = vocab.lines().zip(result.lines());
for (voc, res) in lines {
stemms_to(voc.unwrap().as_str(),
res.unwrap().as_str(),
Algorithm::Arabic);
}
}
#[test]
fn finnish_test() {
use std::fs;
use std::io;
use std::io::BufRead;
let vocab = io::BufReader::new(fs::File::open("test_data/voc_fi.txt").unwrap());
let result = io::BufReader::new(fs::File::open("test_data/res_fi.txt").unwrap());
let lines = vocab.lines().zip(result.lines());
for (voc, res) in lines {
stemms_to(voc.unwrap().as_str(),
res.unwrap().as_str(),
Algorithm::Finnish);
}
}
#[test]
fn greek_test() {
use std::fs;
use std::io;
use std::io::BufRead;
let vocab = io::BufReader::new(fs::File::open("test_data/voc_el.txt").unwrap());
let result = io::BufReader::new(fs::File::open("test_data/res_el.txt").unwrap());
let lines = vocab.lines().zip(result.lines());
for (voc, res) in lines {
stemms_to(voc.unwrap().as_str(),
res.unwrap().as_str(),
Algorithm::Greek);
}
}
#[test]
fn norwegian_test() {
use std::fs;
use std::io;
use std::io::BufRead;
let vocab = io::BufReader::new(fs::File::open("test_data/voc_no.txt").unwrap());
let result = io::BufReader::new(fs::File::open("test_data/res_no.txt").unwrap());
let lines = vocab.lines().zip(result.lines());
for (voc, res) in lines {
stemms_to(voc.unwrap().as_str(),
res.unwrap().as_str(),
Algorithm::Norwegian);
}
}
}
| rust | MIT | 1fde09dfa08fb0fb07fbd6570aba8ecc98174edb | 2026-01-04T20:25:20.053159Z | false |
CurrySoftware/rust-stemmers | https://github.com/CurrySoftware/rust-stemmers/blob/1fde09dfa08fb0fb07fbd6570aba8ecc98174edb/src/snowball/among.rs | src/snowball/among.rs | use snowball::SnowballEnv;
pub struct Among<T: 'static>(pub &'static str,
pub i32,
pub i32,
pub Option<&'static (dyn Fn(&mut SnowballEnv, &mut T) -> bool + Sync)>);
| rust | MIT | 1fde09dfa08fb0fb07fbd6570aba8ecc98174edb | 2026-01-04T20:25:20.053159Z | false |
CurrySoftware/rust-stemmers | https://github.com/CurrySoftware/rust-stemmers/blob/1fde09dfa08fb0fb07fbd6570aba8ecc98174edb/src/snowball/snowball_env.rs | src/snowball/snowball_env.rs | use std::borrow::Cow;
use snowball::Among;
#[derive(Debug, Clone)]
pub struct SnowballEnv<'a> {
pub current: Cow<'a, str>,
pub cursor: usize,
pub limit: usize,
pub limit_backward: usize,
pub bra: usize,
pub ket: usize,
}
impl<'a> SnowballEnv<'a> {
pub fn create(value: &'a str) -> Self {
let len = value.len();
SnowballEnv {
current: Cow::from(value),
cursor: 0,
limit: len,
limit_backward: 0,
bra: 0,
ket: len,
}
}
pub fn get_current(self) -> Cow<'a, str> {
self.current
}
fn replace_s(&mut self, bra: usize, ket: usize, s: &str) -> i32 {
let adjustment = s.len() as i32 - (ket as i32 - bra as i32);
let mut result = String::with_capacity(self.current.len());
{
let (lhs, _) = self.current.split_at(bra);
let (_, rhs) = self.current.split_at(ket);
result.push_str(lhs);
result.push_str(s);
result.push_str(rhs);
}
// ... not very nice...
let new_lim = self.limit as i32 + adjustment;
self.limit = new_lim as usize;
if self.cursor >= ket {
let new_cur = self.cursor as i32 + adjustment;
self.cursor = new_cur as usize;
} else if self.cursor > bra {
self.cursor = bra
}
self.current = Cow::from(result);
adjustment
}
/// Check if s is after cursor.
/// If so, move cursor to the end of s
pub fn eq_s(&mut self, s: &str) -> bool {
if self.cursor >= self.limit {
return false;
}
if self.current[self.cursor..].starts_with(s) {
self.cursor += s.len();
while !self.current.is_char_boundary(self.cursor) {
self.cursor += 1;
}
true
} else {
false
}
}
/// Check if 's' is before cursor
/// If so, move cursor to the beginning of s
pub fn eq_s_b(&mut self, s: &str) -> bool {
if (self.cursor as i32 - self.limit_backward as i32) < s.len() as i32 {
false
// Check if cursor -s.len is a char boundry. if not well... return false obv
} else if !self.current.is_char_boundary(self.cursor - s.len()) ||
!self.current[self.cursor - s.len()..].starts_with(s) {
false
} else {
self.cursor -= s.len();
true
}
}
/// Replace string between `bra` and `ket` with s
pub fn slice_from(&mut self, s: &str) -> bool {
let (bra, ket) = (self.bra, self.ket);
self.replace_s(bra, ket, s);
true
}
/// Move cursor to next charater
pub fn next_char(&mut self) {
self.cursor += 1;
while !self.current.is_char_boundary(self.cursor) {
self.cursor += 1;
}
}
/// Move cursor to previous character
pub fn previous_char(&mut self) {
self.cursor -= 1;
while !self.current.is_char_boundary(self.cursor) {
self.cursor -= 1;
}
}
pub fn byte_index_for_hop(&self, mut delta: i32) -> i32 {
if delta > 0 {
let mut res = self.cursor;
while delta > 0 {
res += 1;
delta -= 1;
while res <= self.current.len() && !self.current.is_char_boundary(res) {
res += 1;
}
}
return res as i32;
} else if delta < 0 {
let mut res: i32 = self.cursor as i32;
while delta < 0 {
res -= 1;
delta += 1;
while res >= 0 && !self.current.is_char_boundary(res as usize) {
res -= 1;
}
}
return res as i32;
} else {
return self.cursor as i32;
}
}
// A grouping is represented by a minimum code point, a maximum code point,
// and a bitfield of which code points in that range are in the grouping.
// For example, in english.sbl, valid_LI is 'cdeghkmnrt'.
// The minimum and maximum code points are 99 and 116,
// so every time one of these grouping functions is called for g_valid_LI,
// min must be 99 and max must be 116. There are 18 code points within that
// range (inclusive) so the grouping is represented with 18 bits, plus 6 bits of padding:
//
// cdefghij klmnopqr st
// 11101100 10110001 01000000
//
// The first bit is the least significant.
// Those three bytes become &[0b00110111, 0b10001101, 0b00000010],
// which is &[55, 141, 2], which is how g_valid_LI is defined in english.rs.
/// Check if the char the cursor points to is in the grouping
pub fn in_grouping(&mut self, chars: &[u8], min: u32, max: u32) -> bool {
if self.cursor >= self.limit {
return false;
}
if let Some(chr) = self.current[self.cursor..].chars().next() {
let mut ch = chr as u32; //codepoint as integer
if ch > max || ch < min {
return false;
}
ch -= min;
if (chars[(ch >> 3) as usize] & (0x1 << (ch & 0x7))) == 0 {
return false;
}
self.next_char();
return true;
}
return false;
}
pub fn in_grouping_b(&mut self, chars: &[u8], min: u32, max: u32) -> bool {
if self.cursor <= self.limit_backward {
return false;
}
self.previous_char();
if let Some(chr) = self.current[self.cursor..].chars().next() {
let mut ch = chr as u32; //codepoint as integer
self.next_char();
if ch > max || ch < min {
return false;
}
ch -= min;
if (chars[(ch >> 3) as usize] & (0x1 << (ch & 0x7))) == 0 {
return false;
}
self.previous_char();
return true;
}
return false;
}
pub fn out_grouping(&mut self, chars: &[u8], min: u32, max: u32) -> bool {
if self.cursor >= self.limit {
return false;
}
if let Some(chr) = self.current[self.cursor..].chars().next() {
let mut ch = chr as u32; //codepoint as integer
if ch > max || ch < min {
self.next_char();
return true;
}
ch -= min;
if (chars[(ch >> 3) as usize] & (0x1 << (ch & 0x7))) == 0 {
self.next_char();
return true;
}
}
return false;
}
pub fn out_grouping_b(&mut self, chars: &[u8], min: u32, max: u32) -> bool {
if self.cursor <= self.limit_backward {
return false;
}
self.previous_char();
if let Some(chr) = self.current[self.cursor..].chars().next() {
let mut ch = chr as u32; //codepoint as integer
self.next_char();
if ch > max || ch < min {
self.previous_char();
return true;
}
ch -= min;
if (chars[(ch >> 3) as usize] & (0x1 << (ch & 0x7))) == 0 {
self.previous_char();
return true;
}
}
return false;
}
/// Helper function that removes the string slice between `bra` and `ket`
pub fn slice_del(&mut self) -> bool {
self.slice_from("")
}
pub fn insert(&mut self, bra: usize, ket: usize, s: &str) {
let adjustment = self.replace_s(bra, ket, s);
if bra <= self.bra {
self.bra = (self.bra as i32 + adjustment) as usize;
}
if bra <= self.ket {
self.ket = (self.ket as i32 + adjustment) as usize;
}
}
pub fn slice_to(&mut self) -> String {
self.current[self.bra..self.ket].to_string()
}
pub fn find_among<T>(&mut self, amongs: &[Among<T>], context: &mut T) -> i32 {
use std::cmp::min;
let mut i: i32 = 0;
let mut j: i32 = amongs.len() as i32;
let c = self.cursor;
let l = self.limit;
let mut common_i = 0;
let mut common_j = 0;
let mut first_key_inspected = false;
loop {
let k = i + ((j - i) >> 1);
let mut diff: i32 = 0;
let mut common = min(common_i, common_j);
let w = &amongs[k as usize];
for lvar in common..w.0.len() {
if c + common == l {
diff = -1;
break;
}
diff = self.current.as_bytes()[c + common] as i32 - w.0.as_bytes()[lvar] as i32;
if diff != 0 {
break;
}
common += 1;
}
if diff < 0 {
j = k;
common_j = common;
} else {
i = k;
common_i = common;
}
if j - i <= 1 {
if i > 0 {
break;
}
if j == i {
break;
}
if first_key_inspected {
break;
}
first_key_inspected = true;
}
}
loop {
let w = &amongs[i as usize];
if common_i >= w.0.len() {
self.cursor = c + w.0.len();
if let Some(ref method) = w.3 {
let res = method(self, context);
self.cursor = c + w.0.len();
if res {
return w.2;
}
} else {
return w.2;
}
}
i = w.1;
if i < 0 {
return 0;
}
}
}
pub fn find_among_b<T>(&mut self, amongs: &[Among<T>], context: &mut T) -> i32 {
let mut i: i32 = 0;
let mut j: i32 = amongs.len() as i32;
let c = self.cursor;
let lb = self.limit_backward;
let mut common_i = 0;
let mut common_j = 0;
let mut first_key_inspected = false;
loop {
let k = i + ((j - i) >> 1);
let mut diff: i32 = 0;
let mut common = if common_i < common_j {
common_i
} else {
common_j
};
let w = &amongs[k as usize];
for lvar in (0..w.0.len() - common).rev() {
if c - common == lb {
diff = -1;
break;
}
diff = self.current.as_bytes()[c - common - 1] as i32 - w.0.as_bytes()[lvar] as i32;
if diff != 0 {
break;
}
common += 1;
}
if diff < 0 {
j = k;
common_j = common;
} else {
i = k;
common_i = common;
}
if j - i <= 1 {
if i > 0 {
break;
}
if j == i {
break;
}
if first_key_inspected {
break;
}
first_key_inspected = true;
}
}
loop {
let w = &amongs[i as usize];
if common_i >= w.0.len() {
self.cursor = c - w.0.len();
if let Some(ref method) = w.3 {
let res = method(self, context);
self.cursor = c - w.0.len();
if res {
return w.2;
}
} else {
return w.2;
}
}
i = w.1;
if i < 0 {
return 0;
}
}
}
}
| rust | MIT | 1fde09dfa08fb0fb07fbd6570aba8ecc98174edb | 2026-01-04T20:25:20.053159Z | false |
CurrySoftware/rust-stemmers | https://github.com/CurrySoftware/rust-stemmers/blob/1fde09dfa08fb0fb07fbd6570aba8ecc98174edb/src/snowball/mod.rs | src/snowball/mod.rs | pub mod algorithms;
mod among;
mod snowball_env;
pub use snowball::among::Among;
pub use snowball::snowball_env::SnowballEnv;
| rust | MIT | 1fde09dfa08fb0fb07fbd6570aba8ecc98174edb | 2026-01-04T20:25:20.053159Z | false |
CurrySoftware/rust-stemmers | https://github.com/CurrySoftware/rust-stemmers/blob/1fde09dfa08fb0fb07fbd6570aba8ecc98174edb/src/snowball/algorithms/armenian.rs | src/snowball/algorithms/armenian.rs | //! Generated by Snowball 2.1.0 - https://snowballstem.org/
#![allow(non_upper_case_globals)]
#![allow(non_snake_case)]
#![allow(unused_variables)]
#![allow(unused_mut)]
use snowball::SnowballEnv;
use snowball::Among;
static A_0: &'static [Among<Context>; 23] = &[
Among("\u{0562}\u{0561}\u{0580}", -1, 1, None),
Among("\u{0580}\u{0578}\u{0580}\u{0564}", -1, 1, None),
Among("\u{0565}\u{0580}\u{0578}\u{0580}\u{0564}", 1, 1, None),
Among("\u{0561}\u{056C}\u{056B}", -1, 1, None),
Among("\u{0561}\u{056F}\u{056B}", -1, 1, None),
Among("\u{0578}\u{0580}\u{0561}\u{056F}", -1, 1, None),
Among("\u{0565}\u{0572}", -1, 1, None),
Among("\u{057E}\u{0578}\u{0582}\u{0576}", -1, 1, None),
Among("\u{0561}\u{0580}\u{0561}\u{0576}", -1, 1, None),
Among("\u{0561}\u{056F}\u{0561}\u{0576}", -1, 1, None),
Among("\u{0565}\u{0576}", -1, 1, None),
Among("\u{0565}\u{0580}\u{0565}\u{0576}", 10, 1, None),
Among("\u{0565}\u{056F}\u{0565}\u{0576}", 10, 1, None),
Among("\u{0578}\u{0580}\u{0567}\u{0576}", -1, 1, None),
Among("\u{056B}\u{0576}", -1, 1, None),
Among("\u{0563}\u{056B}\u{0576}", 14, 1, None),
Among("\u{0578}\u{057E}\u{056B}\u{0576}", 14, 1, None),
Among("\u{056C}\u{0561}\u{0575}\u{0576}", -1, 1, None),
Among("\u{057A}\u{0565}\u{057D}", -1, 1, None),
Among("\u{056B}\u{057E}", -1, 1, None),
Among("\u{0561}\u{057F}", -1, 1, None),
Among("\u{0561}\u{057E}\u{0565}\u{057F}", -1, 1, None),
Among("\u{056F}\u{0578}\u{057F}", -1, 1, None),
];
static A_1: &'static [Among<Context>; 71] = &[
Among("\u{0561}\u{0580}", -1, 1, None),
Among("\u{0561}\u{0581}\u{0561}\u{0580}", 0, 1, None),
Among("\u{0565}\u{0581}\u{0561}\u{0580}", 0, 1, None),
Among("\u{0561}\u{0581}\u{0580}\u{056B}\u{0580}", -1, 1, None),
Among("\u{0561}\u{0581}\u{056B}\u{0580}", -1, 1, None),
Among("\u{0565}\u{0581}\u{056B}\u{0580}", -1, 1, None),
Among("\u{057E}\u{0565}\u{0581}\u{056B}\u{0580}", 5, 1, None),
Among("\u{0561}\u{056C}\u{0578}\u{0582}\u{0581}", -1, 1, None),
Among("\u{0565}\u{056C}\u{0578}\u{0582}\u{0581}", -1, 1, None),
Among("\u{0561}\u{0581}", -1, 1, None),
Among("\u{0565}\u{0581}", -1, 1, None),
Among("\u{0561}\u{0581}\u{0580}\u{0565}\u{0581}", 10, 1, None),
Among("\u{0561}\u{056C}\u{0578}\u{0582}", -1, 1, None),
Among("\u{0565}\u{056C}\u{0578}\u{0582}", -1, 1, None),
Among("\u{0561}\u{0584}", -1, 1, None),
Among("\u{0581}\u{0561}\u{0584}", 14, 1, None),
Among("\u{0561}\u{0581}\u{0561}\u{0584}", 15, 1, None),
Among("\u{0561}\u{0581}\u{0580}\u{056B}\u{0584}", -1, 1, None),
Among("\u{0561}\u{0581}\u{056B}\u{0584}", -1, 1, None),
Among("\u{0565}\u{0581}\u{056B}\u{0584}", -1, 1, None),
Among("\u{057E}\u{0565}\u{0581}\u{056B}\u{0584}", 19, 1, None),
Among("\u{0561}\u{0576}\u{0584}", -1, 1, None),
Among("\u{0581}\u{0561}\u{0576}\u{0584}", 21, 1, None),
Among("\u{0561}\u{0581}\u{0561}\u{0576}\u{0584}", 22, 1, None),
Among("\u{0561}\u{0581}\u{0580}\u{056B}\u{0576}\u{0584}", -1, 1, None),
Among("\u{0561}\u{0581}\u{056B}\u{0576}\u{0584}", -1, 1, None),
Among("\u{0565}\u{0581}\u{056B}\u{0576}\u{0584}", -1, 1, None),
Among("\u{057E}\u{0565}\u{0581}\u{056B}\u{0576}\u{0584}", 26, 1, None),
Among("\u{0561}", -1, 1, None),
Among("\u{0561}\u{0581}\u{0561}", 28, 1, None),
Among("\u{0565}\u{0581}\u{0561}", 28, 1, None),
Among("\u{057E}\u{0565}", -1, 1, None),
Among("\u{0561}\u{0581}\u{0580}\u{056B}", -1, 1, None),
Among("\u{0561}\u{0581}\u{056B}", -1, 1, None),
Among("\u{0565}\u{0581}\u{056B}", -1, 1, None),
Among("\u{057E}\u{0565}\u{0581}\u{056B}", 34, 1, None),
Among("\u{0561}\u{056C}", -1, 1, None),
Among("\u{0568}\u{0561}\u{056C}", 36, 1, None),
Among("\u{0561}\u{0581}\u{0576}\u{0561}\u{056C}", 36, 1, None),
Among("\u{0561}\u{0576}\u{0561}\u{056C}", 36, 1, None),
Among("\u{0565}\u{0576}\u{0561}\u{056C}", 36, 1, None),
Among("\u{0565}\u{056C}", -1, 1, None),
Among("\u{0568}\u{0565}\u{056C}", 41, 1, None),
Among("\u{0576}\u{0565}\u{056C}", 41, 1, None),
Among("\u{0581}\u{0576}\u{0565}\u{056C}", 43, 1, None),
Among("\u{0565}\u{0581}\u{0576}\u{0565}\u{056C}", 44, 1, None),
Among("\u{0579}\u{0565}\u{056C}", 41, 1, None),
Among("\u{057E}\u{0565}\u{056C}", 41, 1, None),
Among("\u{0561}\u{0581}\u{057E}\u{0565}\u{056C}", 47, 1, None),
Among("\u{0565}\u{0581}\u{057E}\u{0565}\u{056C}", 47, 1, None),
Among("\u{057F}\u{0565}\u{056C}", 41, 1, None),
Among("\u{0561}\u{057F}\u{0565}\u{056C}", 50, 1, None),
Among("\u{0578}\u{057F}\u{0565}\u{056C}", 50, 1, None),
Among("\u{056F}\u{0578}\u{057F}\u{0565}\u{056C}", 52, 1, None),
Among("\u{057E}\u{0561}\u{056E}", -1, 1, None),
Among("\u{0578}\u{0582}\u{0574}", -1, 1, None),
Among("\u{057E}\u{0578}\u{0582}\u{0574}", 55, 1, None),
Among("\u{0561}\u{0576}", -1, 1, None),
Among("\u{0581}\u{0561}\u{0576}", 57, 1, None),
Among("\u{0561}\u{0581}\u{0561}\u{0576}", 58, 1, None),
Among("\u{0561}\u{0581}\u{0580}\u{056B}\u{0576}", -1, 1, None),
Among("\u{0561}\u{0581}\u{056B}\u{0576}", -1, 1, None),
Among("\u{0565}\u{0581}\u{056B}\u{0576}", -1, 1, None),
Among("\u{057E}\u{0565}\u{0581}\u{056B}\u{0576}", 62, 1, None),
Among("\u{0561}\u{056C}\u{056B}\u{057D}", -1, 1, None),
Among("\u{0565}\u{056C}\u{056B}\u{057D}", -1, 1, None),
Among("\u{0561}\u{057E}", -1, 1, None),
Among("\u{0561}\u{0581}\u{0561}\u{057E}", 66, 1, None),
Among("\u{0565}\u{0581}\u{0561}\u{057E}", 66, 1, None),
Among("\u{0561}\u{056C}\u{0578}\u{057E}", -1, 1, None),
Among("\u{0565}\u{056C}\u{0578}\u{057E}", -1, 1, None),
];
static A_2: &'static [Among<Context>; 40] = &[
Among("\u{0563}\u{0561}\u{0580}", -1, 1, None),
Among("\u{057E}\u{0578}\u{0580}", -1, 1, None),
Among("\u{0561}\u{057E}\u{0578}\u{0580}", 1, 1, None),
Among("\u{0561}\u{0576}\u{0585}\u{0581}", -1, 1, None),
Among("\u{0578}\u{0581}", -1, 1, None),
Among("\u{0578}\u{0582}", -1, 1, None),
Among("\u{0584}", -1, 1, None),
Among("\u{0561}\u{0580}\u{0584}", 6, 1, None),
Among("\u{0579}\u{0565}\u{0584}", 6, 1, None),
Among("\u{056B}\u{0584}", 6, 1, None),
Among("\u{0561}\u{056C}\u{056B}\u{0584}", 9, 1, None),
Among("\u{0561}\u{0576}\u{056B}\u{0584}", 9, 1, None),
Among("\u{057E}\u{0561}\u{056E}\u{0584}", 6, 1, None),
Among("\u{0578}\u{0582}\u{0575}\u{0584}", 6, 1, None),
Among("\u{0578}\u{0582}\u{0576}\u{0584}", 6, 1, None),
Among("\u{0574}\u{0578}\u{0582}\u{0576}\u{0584}", 14, 1, None),
Among("\u{0565}\u{0576}\u{0584}", 6, 1, None),
Among("\u{0578}\u{0576}\u{0584}", 6, 1, None),
Among("\u{056B}\u{0579}\u{0584}", 6, 1, None),
Among("\u{0578}\u{0580}\u{0564}", -1, 1, None),
Among("\u{0578}\u{0582}\u{0575}\u{0569}", -1, 1, None),
Among("\u{0581}\u{056B}", -1, 1, None),
Among("\u{0578}\u{0582}\u{0570}\u{056B}", -1, 1, None),
Among("\u{056B}\u{056C}", -1, 1, None),
Among("\u{0578}\u{0582}\u{056F}", -1, 1, None),
Among("\u{0561}\u{056F}", -1, 1, None),
Among("\u{0575}\u{0561}\u{056F}", 25, 1, None),
Among("\u{0561}\u{0576}\u{0561}\u{056F}", 25, 1, None),
Among("\u{056B}\u{056F}", -1, 1, None),
Among("\u{0575}\u{0578}\u{0582}\u{0576}", -1, 1, None),
Among("\u{0578}\u{0582}\u{0569}\u{0575}\u{0578}\u{0582}\u{0576}", 29, 1, None),
Among("\u{0561}\u{0576}", -1, 1, None),
Among("\u{0561}\u{0580}\u{0561}\u{0576}", 31, 1, None),
Among("\u{057A}\u{0561}\u{0576}", 31, 1, None),
Among("\u{057D}\u{057F}\u{0561}\u{0576}", 31, 1, None),
Among("\u{0565}\u{0572}\u{0567}\u{0576}", -1, 1, None),
Among("\u{0561}\u{056E}\u{0578}", -1, 1, None),
Among("\u{056B}\u{0579}", -1, 1, None),
Among("\u{0578}\u{0582}\u{057D}", -1, 1, None),
Among("\u{0578}\u{0582}\u{057D}\u{057F}", -1, 1, None),
];
static A_3: &'static [Among<Context>; 57] = &[
Among("\u{0565}\u{0580}", -1, 1, None),
Among("\u{0576}\u{0565}\u{0580}", 0, 1, None),
Among("\u{0581}", -1, 1, None),
Among("\u{0578}\u{0582}\u{0581}", 2, 1, None),
Among("\u{056B}\u{0581}", 2, 1, None),
Among("\u{0565}\u{0580}\u{056B}\u{0581}", 4, 1, None),
Among("\u{0576}\u{0565}\u{0580}\u{056B}\u{0581}", 5, 1, None),
Among("\u{0581}\u{056B}\u{0581}", 4, 1, None),
Among("\u{057E}\u{0561}\u{0576}\u{056B}\u{0581}", 4, 1, None),
Among("\u{0578}\u{057B}\u{056B}\u{0581}", 4, 1, None),
Among("\u{057E}\u{056B}\u{0581}", 4, 1, None),
Among("\u{0578}\u{0581}", 2, 1, None),
Among("\u{057D}\u{0561}", -1, 1, None),
Among("\u{057E}\u{0561}", -1, 1, None),
Among("\u{0561}\u{0574}\u{0562}", -1, 1, None),
Among("\u{0564}", -1, 1, None),
Among("\u{0565}\u{0580}\u{0564}", 15, 1, None),
Among("\u{0576}\u{0565}\u{0580}\u{0564}", 16, 1, None),
Among("\u{0578}\u{0582}\u{0564}", 15, 1, None),
Among("\u{0561}\u{0576}\u{0564}", 15, 1, None),
Among("\u{0578}\u{0582}\u{0569}\u{0575}\u{0561}\u{0576}\u{0564}", 19, 1, None),
Among("\u{057E}\u{0561}\u{0576}\u{0564}", 19, 1, None),
Among("\u{0578}\u{057B}\u{0564}", 15, 1, None),
Among("\u{0568}", -1, 1, None),
Among("\u{0565}\u{0580}\u{0568}", 23, 1, None),
Among("\u{0576}\u{0565}\u{0580}\u{0568}", 24, 1, None),
Among("\u{0561}\u{0576}\u{0568}", 23, 1, None),
Among("\u{0578}\u{0582}\u{0569}\u{0575}\u{0561}\u{0576}\u{0568}", 26, 1, None),
Among("\u{057E}\u{0561}\u{0576}\u{0568}", 26, 1, None),
Among("\u{0578}\u{057B}\u{0568}", 23, 1, None),
Among("\u{056B}", -1, 1, None),
Among("\u{0565}\u{0580}\u{056B}", 30, 1, None),
Among("\u{0576}\u{0565}\u{0580}\u{056B}", 31, 1, None),
Among("\u{057E}\u{056B}", 30, 1, None),
Among("\u{0565}\u{0580}\u{0578}\u{0582}\u{0574}", -1, 1, None),
Among("\u{0576}\u{0565}\u{0580}\u{0578}\u{0582}\u{0574}", 34, 1, None),
Among("\u{0561}\u{0576}\u{0578}\u{0582}\u{0574}", -1, 1, None),
Among("\u{0576}", -1, 1, None),
Among("\u{0565}\u{0580}\u{0576}", 37, 1, None),
Among("\u{0576}\u{0565}\u{0580}\u{0576}", 38, 1, None),
Among("\u{0578}\u{0582}\u{0576}", 37, 1, None),
Among("\u{0561}\u{0576}", 37, 1, None),
Among("\u{0578}\u{0582}\u{0569}\u{0575}\u{0561}\u{0576}", 41, 1, None),
Among("\u{057E}\u{0561}\u{0576}", 41, 1, None),
Among("\u{056B}\u{0576}", 37, 1, None),
Among("\u{0565}\u{0580}\u{056B}\u{0576}", 44, 1, None),
Among("\u{0576}\u{0565}\u{0580}\u{056B}\u{0576}", 45, 1, None),
Among("\u{0578}\u{0582}\u{0569}\u{0575}\u{0561}\u{0576}\u{0576}", 37, 1, None),
Among("\u{0578}\u{057B}", -1, 1, None),
Among("\u{0578}\u{0582}\u{0569}\u{0575}\u{0561}\u{0576}\u{057D}", -1, 1, None),
Among("\u{057E}\u{0561}\u{0576}\u{057D}", -1, 1, None),
Among("\u{0578}\u{057B}\u{057D}", -1, 1, None),
Among("\u{0578}\u{057E}", -1, 1, None),
Among("\u{0565}\u{0580}\u{0578}\u{057E}", 52, 1, None),
Among("\u{0576}\u{0565}\u{0580}\u{0578}\u{057E}", 53, 1, None),
Among("\u{0561}\u{0576}\u{0578}\u{057E}", 52, 1, None),
Among("\u{057E}\u{0578}\u{057E}", 52, 1, None),
];
static G_v: &'static [u8; 5] = &[209, 4, 128, 0, 18];
#[derive(Clone)]
struct Context {
i_p2: i32,
i_pV: i32,
}
fn r_mark_regions(env: &mut SnowballEnv, context: &mut Context) -> bool {
context.i_pV = env.limit;
context.i_p2 = env.limit;
let v_1 = env.cursor;
'lab0: loop {
'golab1: loop {
'lab2: loop {
if !env.in_grouping(G_v, 1377, 1413) {
break 'lab2;
}
break 'golab1;
}
if env.cursor >= env.limit {
break 'lab0;
}
env.next_char();
}
context.i_pV = env.cursor;
'golab3: loop {
'lab4: loop {
if !env.out_grouping(G_v, 1377, 1413) {
break 'lab4;
}
break 'golab3;
}
if env.cursor >= env.limit {
break 'lab0;
}
env.next_char();
}
'golab5: loop {
'lab6: loop {
if !env.in_grouping(G_v, 1377, 1413) {
break 'lab6;
}
break 'golab5;
}
if env.cursor >= env.limit {
break 'lab0;
}
env.next_char();
}
'golab7: loop {
'lab8: loop {
if !env.out_grouping(G_v, 1377, 1413) {
break 'lab8;
}
break 'golab7;
}
if env.cursor >= env.limit {
break 'lab0;
}
env.next_char();
}
context.i_p2 = env.cursor;
break 'lab0;
}
env.cursor = v_1;
return true;
}
fn r_R2(env: &mut SnowballEnv, context: &mut Context) -> bool {
if !(context.i_p2 <= env.cursor){
return false;
}
return true;
}
fn r_adjective(env: &mut SnowballEnv, context: &mut Context) -> bool {
env.ket = env.cursor;
if env.find_among_b(A_0, context) == 0 {
return false;
}
env.bra = env.cursor;
if !env.slice_del() {
return false;
}
return true;
}
fn r_verb(env: &mut SnowballEnv, context: &mut Context) -> bool {
env.ket = env.cursor;
if env.find_among_b(A_1, context) == 0 {
return false;
}
env.bra = env.cursor;
if !env.slice_del() {
return false;
}
return true;
}
fn r_noun(env: &mut SnowballEnv, context: &mut Context) -> bool {
env.ket = env.cursor;
if env.find_among_b(A_2, context) == 0 {
return false;
}
env.bra = env.cursor;
if !env.slice_del() {
return false;
}
return true;
}
fn r_ending(env: &mut SnowballEnv, context: &mut Context) -> bool {
env.ket = env.cursor;
if env.find_among_b(A_3, context) == 0 {
return false;
}
env.bra = env.cursor;
if !r_R2(env, context) {
return false;
}
if !env.slice_del() {
return false;
}
return true;
}
pub fn stem(env: &mut SnowballEnv) -> bool {
let mut context = &mut Context {
i_p2: 0,
i_pV: 0,
};
r_mark_regions(env, context);
env.limit_backward = env.cursor;
env.cursor = env.limit;
if env.cursor < context.i_pV {
return false;
}
let v_3 = env.limit_backward;
env.limit_backward = context.i_pV;
let v_4 = env.limit - env.cursor;
r_ending(env, context);
env.cursor = env.limit - v_4;
let v_5 = env.limit - env.cursor;
r_verb(env, context);
env.cursor = env.limit - v_5;
let v_6 = env.limit - env.cursor;
r_adjective(env, context);
env.cursor = env.limit - v_6;
let v_7 = env.limit - env.cursor;
r_noun(env, context);
env.cursor = env.limit - v_7;
env.limit_backward = v_3;
env.cursor = env.limit_backward;
return true;
}
| rust | MIT | 1fde09dfa08fb0fb07fbd6570aba8ecc98174edb | 2026-01-04T20:25:20.053159Z | false |
CurrySoftware/rust-stemmers | https://github.com/CurrySoftware/rust-stemmers/blob/1fde09dfa08fb0fb07fbd6570aba8ecc98174edb/src/snowball/algorithms/german.rs | src/snowball/algorithms/german.rs | //! This file was generated automatically by the Snowball to Rust compiler
//! http://snowballstem.org/
#![allow(non_upper_case_globals)]
#![allow(non_snake_case)]
#![allow(unused_variables)]
#![allow(unused_mut)]
use snowball::SnowballEnv;
use snowball::Among;
static A_0: &'static [Among<Context>; 6] = &[
Among("", -1, 6, None),
Among("U", 0, 2, None),
Among("Y", 0, 1, None),
Among("\u{00E4}", 0, 3, None),
Among("\u{00F6}", 0, 4, None),
Among("\u{00FC}", 0, 5, None),
];
static A_1: &'static [Among<Context>; 7] = &[
Among("e", -1, 2, None),
Among("em", -1, 1, None),
Among("en", -1, 2, None),
Among("ern", -1, 1, None),
Among("er", -1, 1, None),
Among("s", -1, 3, None),
Among("es", 5, 2, None),
];
static A_2: &'static [Among<Context>; 4] = &[
Among("en", -1, 1, None),
Among("er", -1, 1, None),
Among("st", -1, 2, None),
Among("est", 2, 1, None),
];
static A_3: &'static [Among<Context>; 2] = &[
Among("ig", -1, 1, None),
Among("lich", -1, 1, None),
];
static A_4: &'static [Among<Context>; 8] = &[
Among("end", -1, 1, None),
Among("ig", -1, 2, None),
Among("ung", -1, 1, None),
Among("lich", -1, 3, None),
Among("isch", -1, 2, None),
Among("ik", -1, 2, None),
Among("heit", -1, 3, None),
Among("keit", -1, 4, None),
];
static G_v: &'static [u8; 20] = &[17, 65, 16, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 32, 8];
static G_s_ending: &'static [u8; 3] = &[117, 30, 5];
static G_st_ending: &'static [u8; 3] = &[117, 30, 4];
#[derive(Clone)]
struct Context {
i_x: usize,
i_p2: usize,
i_p1: usize,
}
fn r_prelude(env: &mut SnowballEnv, context: &mut Context) -> bool {
// (, line 32
// test, line 34
let v_1 = env.cursor;
// repeat, line 34
'replab0: loop{
let v_2 = env.cursor;
'lab1: for _ in 0..1 {
// (, line 34
// or, line 37
'lab2: loop {
let v_3 = env.cursor;
'lab3: loop {
// (, line 35
// [, line 36
env.bra = env.cursor;
// literal, line 36
if !env.eq_s(&"\u{00DF}") {
break 'lab3;
}
// ], line 36
env.ket = env.cursor;
// <-, line 36
if !env.slice_from("ss") {
return false;
}
break 'lab2;
}
env.cursor = v_3;
// next, line 37
if env.cursor >= env.limit {
break 'lab1;
}
env.next_char();
break 'lab2;
}
continue 'replab0;
}
env.cursor = v_2;
break 'replab0;
}
env.cursor = v_1;
// repeat, line 40
'replab4: loop{
let v_4 = env.cursor;
'lab5: for _ in 0..1 {
// goto, line 40
'golab6: loop {
let v_5 = env.cursor;
'lab7: loop {
// (, line 40
if !env.in_grouping(G_v, 97, 252) {
break 'lab7;
}
// [, line 41
env.bra = env.cursor;
// or, line 41
'lab8: loop {
let v_6 = env.cursor;
'lab9: loop {
// (, line 41
// literal, line 41
if !env.eq_s(&"u") {
break 'lab9;
}
// ], line 41
env.ket = env.cursor;
if !env.in_grouping(G_v, 97, 252) {
break 'lab9;
}
// <-, line 41
if !env.slice_from("U") {
return false;
}
break 'lab8;
}
env.cursor = v_6;
// (, line 42
// literal, line 42
if !env.eq_s(&"y") {
break 'lab7;
}
// ], line 42
env.ket = env.cursor;
if !env.in_grouping(G_v, 97, 252) {
break 'lab7;
}
// <-, line 42
if !env.slice_from("Y") {
return false;
}
break 'lab8;
}
env.cursor = v_5;
break 'golab6;
}
env.cursor = v_5;
if env.cursor >= env.limit {
break 'lab5;
}
env.next_char();
}
continue 'replab4;
}
env.cursor = v_4;
break 'replab4;
}
return true;
}
fn r_mark_regions(env: &mut SnowballEnv, context: &mut Context) -> bool {
// (, line 46
context.i_p1 = env.limit;
context.i_p2 = env.limit;
// test, line 51
let v_1 = env.cursor;
// (, line 51
// hop, line 51
let c = env.byte_index_for_hop(3);
if 0 as i32 > c || c > env.limit as i32 {
return false;
}
env.cursor = c as usize;
// setmark x, line 51
context.i_x = env.cursor;
env.cursor = v_1;
// gopast, line 53
'golab0: loop {
'lab1: loop {
if !env.in_grouping(G_v, 97, 252) {
break 'lab1;
}
break 'golab0;
}
if env.cursor >= env.limit {
return false;
}
env.next_char();
}
// gopast, line 53
'golab2: loop {
'lab3: loop {
if !env.out_grouping(G_v, 97, 252) {
break 'lab3;
}
break 'golab2;
}
if env.cursor >= env.limit {
return false;
}
env.next_char();
}
// setmark p1, line 53
context.i_p1 = env.cursor;
// try, line 54
'lab4: loop {
// (, line 54
if !(context.i_p1 < context.i_x){
break 'lab4;
}
context.i_p1 = context.i_x;
break 'lab4;
}
// gopast, line 55
'golab5: loop {
'lab6: loop {
if !env.in_grouping(G_v, 97, 252) {
break 'lab6;
}
break 'golab5;
}
if env.cursor >= env.limit {
return false;
}
env.next_char();
}
// gopast, line 55
'golab7: loop {
'lab8: loop {
if !env.out_grouping(G_v, 97, 252) {
break 'lab8;
}
break 'golab7;
}
if env.cursor >= env.limit {
return false;
}
env.next_char();
}
// setmark p2, line 55
context.i_p2 = env.cursor;
return true;
}
fn r_postlude(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// repeat, line 59
'replab0: loop{
let v_1 = env.cursor;
'lab1: for _ in 0..1 {
// (, line 59
// [, line 61
env.bra = env.cursor;
// substring, line 61
among_var = env.find_among(A_0, context);
if among_var == 0 {
break 'lab1;
}
// ], line 61
env.ket = env.cursor;
if among_var == 0 {
break 'lab1;
} else if among_var == 1 {
// (, line 62
// <-, line 62
if !env.slice_from("y") {
return false;
}
} else if among_var == 2 {
// (, line 63
// <-, line 63
if !env.slice_from("u") {
return false;
}
} else if among_var == 3 {
// (, line 64
// <-, line 64
if !env.slice_from("a") {
return false;
}
} else if among_var == 4 {
// (, line 65
// <-, line 65
if !env.slice_from("o") {
return false;
}
} else if among_var == 5 {
// (, line 66
// <-, line 66
if !env.slice_from("u") {
return false;
}
} else if among_var == 6 {
// (, line 67
// next, line 67
if env.cursor >= env.limit {
break 'lab1;
}
env.next_char();
}
continue 'replab0;
}
env.cursor = v_1;
break 'replab0;
}
return true;
}
fn r_R1(env: &mut SnowballEnv, context: &mut Context) -> bool {
if !(context.i_p1 <= env.cursor){
return false;
}
return true;
}
fn r_R2(env: &mut SnowballEnv, context: &mut Context) -> bool {
if !(context.i_p2 <= env.cursor){
return false;
}
return true;
}
fn r_standard_suffix(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 77
// do, line 78
let v_1 = env.limit - env.cursor;
'lab0: loop {
// (, line 78
// [, line 79
env.ket = env.cursor;
// substring, line 79
among_var = env.find_among_b(A_1, context);
if among_var == 0 {
break 'lab0;
}
// ], line 79
env.bra = env.cursor;
// call R1, line 79
if !r_R1(env, context) {
break 'lab0;
}
if among_var == 0 {
break 'lab0;
} else if among_var == 1 {
// (, line 81
// delete, line 81
if !env.slice_del() {
return false;
}
} else if among_var == 2 {
// (, line 84
// delete, line 84
if !env.slice_del() {
return false;
}
// try, line 85
let v_2 = env.limit - env.cursor;
'lab1: loop {
// (, line 85
// [, line 85
env.ket = env.cursor;
// literal, line 85
if !env.eq_s_b(&"s") {
env.cursor = env.limit - v_2;
break 'lab1;
}
// ], line 85
env.bra = env.cursor;
// literal, line 85
if !env.eq_s_b(&"nis") {
env.cursor = env.limit - v_2;
break 'lab1;
}
// delete, line 85
if !env.slice_del() {
return false;
}
break 'lab1;
}
} else if among_var == 3 {
// (, line 88
if !env.in_grouping_b(G_s_ending, 98, 116) {
break 'lab0;
}
// delete, line 88
if !env.slice_del() {
return false;
}
}
break 'lab0;
}
env.cursor = env.limit - v_1;
// do, line 92
let v_3 = env.limit - env.cursor;
'lab2: loop {
// (, line 92
// [, line 93
env.ket = env.cursor;
// substring, line 93
among_var = env.find_among_b(A_2, context);
if among_var == 0 {
break 'lab2;
}
// ], line 93
env.bra = env.cursor;
// call R1, line 93
if !r_R1(env, context) {
break 'lab2;
}
if among_var == 0 {
break 'lab2;
} else if among_var == 1 {
// (, line 95
// delete, line 95
if !env.slice_del() {
return false;
}
} else if among_var == 2 {
// (, line 98
if !env.in_grouping_b(G_st_ending, 98, 116) {
break 'lab2;
}
// hop, line 98
let c = env.byte_index_for_hop(-3);
if env.limit_backward as i32 > c || c > env.limit as i32 {
break 'lab2;
}
env.cursor = c as usize;
// delete, line 98
if !env.slice_del() {
return false;
}
}
break 'lab2;
}
env.cursor = env.limit - v_3;
// do, line 102
let v_4 = env.limit - env.cursor;
'lab3: loop {
// (, line 102
// [, line 103
env.ket = env.cursor;
// substring, line 103
among_var = env.find_among_b(A_4, context);
if among_var == 0 {
break 'lab3;
}
// ], line 103
env.bra = env.cursor;
// call R2, line 103
if !r_R2(env, context) {
break 'lab3;
}
if among_var == 0 {
break 'lab3;
} else if among_var == 1 {
// (, line 105
// delete, line 105
if !env.slice_del() {
return false;
}
// try, line 106
let v_5 = env.limit - env.cursor;
'lab4: loop {
// (, line 106
// [, line 106
env.ket = env.cursor;
// literal, line 106
if !env.eq_s_b(&"ig") {
env.cursor = env.limit - v_5;
break 'lab4;
}
// ], line 106
env.bra = env.cursor;
// not, line 106
let v_6 = env.limit - env.cursor;
'lab5: loop {
// literal, line 106
if !env.eq_s_b(&"e") {
break 'lab5;
}
env.cursor = env.limit - v_5;
break 'lab4;
}
env.cursor = env.limit - v_6;
// call R2, line 106
if !r_R2(env, context) {
env.cursor = env.limit - v_5;
break 'lab4;
}
// delete, line 106
if !env.slice_del() {
return false;
}
break 'lab4;
}
} else if among_var == 2 {
// (, line 109
// not, line 109
let v_7 = env.limit - env.cursor;
'lab6: loop {
// literal, line 109
if !env.eq_s_b(&"e") {
break 'lab6;
}
break 'lab3;
}
env.cursor = env.limit - v_7;
// delete, line 109
if !env.slice_del() {
return false;
}
} else if among_var == 3 {
// (, line 112
// delete, line 112
if !env.slice_del() {
return false;
}
// try, line 113
let v_8 = env.limit - env.cursor;
'lab7: loop {
// (, line 113
// [, line 114
env.ket = env.cursor;
// or, line 114
'lab8: loop {
let v_9 = env.limit - env.cursor;
'lab9: loop {
// literal, line 114
if !env.eq_s_b(&"er") {
break 'lab9;
}
break 'lab8;
}
env.cursor = env.limit - v_9;
// literal, line 114
if !env.eq_s_b(&"en") {
env.cursor = env.limit - v_8;
break 'lab7;
}
break 'lab8;
}
// ], line 114
env.bra = env.cursor;
// call R1, line 114
if !r_R1(env, context) {
env.cursor = env.limit - v_8;
break 'lab7;
}
// delete, line 114
if !env.slice_del() {
return false;
}
break 'lab7;
}
} else if among_var == 4 {
// (, line 118
// delete, line 118
if !env.slice_del() {
return false;
}
// try, line 119
let v_10 = env.limit - env.cursor;
'lab10: loop {
// (, line 119
// [, line 120
env.ket = env.cursor;
// substring, line 120
among_var = env.find_among_b(A_3, context);
if among_var == 0 {
env.cursor = env.limit - v_10;
break 'lab10;
}
// ], line 120
env.bra = env.cursor;
// call R2, line 120
if !r_R2(env, context) {
env.cursor = env.limit - v_10;
break 'lab10;
}
if among_var == 0 {
env.cursor = env.limit - v_10;
break 'lab10;
} else if among_var == 1 {
// (, line 122
// delete, line 122
if !env.slice_del() {
return false;
}
}
break 'lab10;
}
}
break 'lab3;
}
env.cursor = env.limit - v_4;
return true;
}
pub fn stem(env: &mut SnowballEnv) -> bool {
let mut context = &mut Context {
i_x: 0,
i_p2: 0,
i_p1: 0,
};
// (, line 132
// do, line 133
let v_1 = env.cursor;
'lab0: loop {
// call prelude, line 133
if !r_prelude(env, context) {
break 'lab0;
}
break 'lab0;
}
env.cursor = v_1;
// do, line 134
let v_2 = env.cursor;
'lab1: loop {
// call mark_regions, line 134
if !r_mark_regions(env, context) {
break 'lab1;
}
break 'lab1;
}
env.cursor = v_2;
// backwards, line 135
env.limit_backward = env.cursor;
env.cursor = env.limit;
// do, line 136
let v_3 = env.limit - env.cursor;
'lab2: loop {
// call standard_suffix, line 136
if !r_standard_suffix(env, context) {
break 'lab2;
}
break 'lab2;
}
env.cursor = env.limit - v_3;
env.cursor = env.limit_backward;
// do, line 137
let v_4 = env.cursor;
'lab3: loop {
// call postlude, line 137
if !r_postlude(env, context) {
break 'lab3;
}
break 'lab3;
}
env.cursor = v_4;
return true;
}
| rust | MIT | 1fde09dfa08fb0fb07fbd6570aba8ecc98174edb | 2026-01-04T20:25:20.053159Z | false |
CurrySoftware/rust-stemmers | https://github.com/CurrySoftware/rust-stemmers/blob/1fde09dfa08fb0fb07fbd6570aba8ecc98174edb/src/snowball/algorithms/spanish.rs | src/snowball/algorithms/spanish.rs | //! This file was generated automatically by the Snowball to Rust compiler
//! http://snowballstem.org/
#![allow(non_upper_case_globals)]
#![allow(non_snake_case)]
#![allow(unused_variables)]
#![allow(unused_mut)]
use snowball::SnowballEnv;
use snowball::Among;
static A_0: &'static [Among<Context>; 6] = &[
Among("", -1, 6, None),
Among("\u{00E1}", 0, 1, None),
Among("\u{00E9}", 0, 2, None),
Among("\u{00ED}", 0, 3, None),
Among("\u{00F3}", 0, 4, None),
Among("\u{00FA}", 0, 5, None),
];
static A_1: &'static [Among<Context>; 13] = &[
Among("la", -1, -1, None),
Among("sela", 0, -1, None),
Among("le", -1, -1, None),
Among("me", -1, -1, None),
Among("se", -1, -1, None),
Among("lo", -1, -1, None),
Among("selo", 5, -1, None),
Among("las", -1, -1, None),
Among("selas", 7, -1, None),
Among("les", -1, -1, None),
Among("los", -1, -1, None),
Among("selos", 10, -1, None),
Among("nos", -1, -1, None),
];
static A_2: &'static [Among<Context>; 11] = &[
Among("ando", -1, 6, None),
Among("iendo", -1, 6, None),
Among("yendo", -1, 7, None),
Among("\u{00E1}ndo", -1, 2, None),
Among("i\u{00E9}ndo", -1, 1, None),
Among("ar", -1, 6, None),
Among("er", -1, 6, None),
Among("ir", -1, 6, None),
Among("\u{00E1}r", -1, 3, None),
Among("\u{00E9}r", -1, 4, None),
Among("\u{00ED}r", -1, 5, None),
];
static A_3: &'static [Among<Context>; 4] = &[
Among("ic", -1, -1, None),
Among("ad", -1, -1, None),
Among("os", -1, -1, None),
Among("iv", -1, 1, None),
];
static A_4: &'static [Among<Context>; 3] = &[
Among("able", -1, 1, None),
Among("ible", -1, 1, None),
Among("ante", -1, 1, None),
];
static A_5: &'static [Among<Context>; 3] = &[
Among("ic", -1, 1, None),
Among("abil", -1, 1, None),
Among("iv", -1, 1, None),
];
static A_6: &'static [Among<Context>; 46] = &[
Among("ica", -1, 1, None),
Among("ancia", -1, 2, None),
Among("encia", -1, 5, None),
Among("adora", -1, 2, None),
Among("osa", -1, 1, None),
Among("ista", -1, 1, None),
Among("iva", -1, 9, None),
Among("anza", -1, 1, None),
Among("log\u{00ED}a", -1, 3, None),
Among("idad", -1, 8, None),
Among("able", -1, 1, None),
Among("ible", -1, 1, None),
Among("ante", -1, 2, None),
Among("mente", -1, 7, None),
Among("amente", 13, 6, None),
Among("aci\u{00F3}n", -1, 2, None),
Among("uci\u{00F3}n", -1, 4, None),
Among("ico", -1, 1, None),
Among("ismo", -1, 1, None),
Among("oso", -1, 1, None),
Among("amiento", -1, 1, None),
Among("imiento", -1, 1, None),
Among("ivo", -1, 9, None),
Among("ador", -1, 2, None),
Among("icas", -1, 1, None),
Among("ancias", -1, 2, None),
Among("encias", -1, 5, None),
Among("adoras", -1, 2, None),
Among("osas", -1, 1, None),
Among("istas", -1, 1, None),
Among("ivas", -1, 9, None),
Among("anzas", -1, 1, None),
Among("log\u{00ED}as", -1, 3, None),
Among("idades", -1, 8, None),
Among("ables", -1, 1, None),
Among("ibles", -1, 1, None),
Among("aciones", -1, 2, None),
Among("uciones", -1, 4, None),
Among("adores", -1, 2, None),
Among("antes", -1, 2, None),
Among("icos", -1, 1, None),
Among("ismos", -1, 1, None),
Among("osos", -1, 1, None),
Among("amientos", -1, 1, None),
Among("imientos", -1, 1, None),
Among("ivos", -1, 9, None),
];
static A_7: &'static [Among<Context>; 12] = &[
Among("ya", -1, 1, None),
Among("ye", -1, 1, None),
Among("yan", -1, 1, None),
Among("yen", -1, 1, None),
Among("yeron", -1, 1, None),
Among("yendo", -1, 1, None),
Among("yo", -1, 1, None),
Among("yas", -1, 1, None),
Among("yes", -1, 1, None),
Among("yais", -1, 1, None),
Among("yamos", -1, 1, None),
Among("y\u{00F3}", -1, 1, None),
];
static A_8: &'static [Among<Context>; 96] = &[
Among("aba", -1, 2, None),
Among("ada", -1, 2, None),
Among("ida", -1, 2, None),
Among("ara", -1, 2, None),
Among("iera", -1, 2, None),
Among("\u{00ED}a", -1, 2, None),
Among("ar\u{00ED}a", 5, 2, None),
Among("er\u{00ED}a", 5, 2, None),
Among("ir\u{00ED}a", 5, 2, None),
Among("ad", -1, 2, None),
Among("ed", -1, 2, None),
Among("id", -1, 2, None),
Among("ase", -1, 2, None),
Among("iese", -1, 2, None),
Among("aste", -1, 2, None),
Among("iste", -1, 2, None),
Among("an", -1, 2, None),
Among("aban", 16, 2, None),
Among("aran", 16, 2, None),
Among("ieran", 16, 2, None),
Among("\u{00ED}an", 16, 2, None),
Among("ar\u{00ED}an", 20, 2, None),
Among("er\u{00ED}an", 20, 2, None),
Among("ir\u{00ED}an", 20, 2, None),
Among("en", -1, 1, None),
Among("asen", 24, 2, None),
Among("iesen", 24, 2, None),
Among("aron", -1, 2, None),
Among("ieron", -1, 2, None),
Among("ar\u{00E1}n", -1, 2, None),
Among("er\u{00E1}n", -1, 2, None),
Among("ir\u{00E1}n", -1, 2, None),
Among("ado", -1, 2, None),
Among("ido", -1, 2, None),
Among("ando", -1, 2, None),
Among("iendo", -1, 2, None),
Among("ar", -1, 2, None),
Among("er", -1, 2, None),
Among("ir", -1, 2, None),
Among("as", -1, 2, None),
Among("abas", 39, 2, None),
Among("adas", 39, 2, None),
Among("idas", 39, 2, None),
Among("aras", 39, 2, None),
Among("ieras", 39, 2, None),
Among("\u{00ED}as", 39, 2, None),
Among("ar\u{00ED}as", 45, 2, None),
Among("er\u{00ED}as", 45, 2, None),
Among("ir\u{00ED}as", 45, 2, None),
Among("es", -1, 1, None),
Among("ases", 49, 2, None),
Among("ieses", 49, 2, None),
Among("abais", -1, 2, None),
Among("arais", -1, 2, None),
Among("ierais", -1, 2, None),
Among("\u{00ED}ais", -1, 2, None),
Among("ar\u{00ED}ais", 55, 2, None),
Among("er\u{00ED}ais", 55, 2, None),
Among("ir\u{00ED}ais", 55, 2, None),
Among("aseis", -1, 2, None),
Among("ieseis", -1, 2, None),
Among("asteis", -1, 2, None),
Among("isteis", -1, 2, None),
Among("\u{00E1}is", -1, 2, None),
Among("\u{00E9}is", -1, 1, None),
Among("ar\u{00E9}is", 64, 2, None),
Among("er\u{00E9}is", 64, 2, None),
Among("ir\u{00E9}is", 64, 2, None),
Among("ados", -1, 2, None),
Among("idos", -1, 2, None),
Among("amos", -1, 2, None),
Among("\u{00E1}bamos", 70, 2, None),
Among("\u{00E1}ramos", 70, 2, None),
Among("i\u{00E9}ramos", 70, 2, None),
Among("\u{00ED}amos", 70, 2, None),
Among("ar\u{00ED}amos", 74, 2, None),
Among("er\u{00ED}amos", 74, 2, None),
Among("ir\u{00ED}amos", 74, 2, None),
Among("emos", -1, 1, None),
Among("aremos", 78, 2, None),
Among("eremos", 78, 2, None),
Among("iremos", 78, 2, None),
Among("\u{00E1}semos", 78, 2, None),
Among("i\u{00E9}semos", 78, 2, None),
Among("imos", -1, 2, None),
Among("ar\u{00E1}s", -1, 2, None),
Among("er\u{00E1}s", -1, 2, None),
Among("ir\u{00E1}s", -1, 2, None),
Among("\u{00ED}s", -1, 2, None),
Among("ar\u{00E1}", -1, 2, None),
Among("er\u{00E1}", -1, 2, None),
Among("ir\u{00E1}", -1, 2, None),
Among("ar\u{00E9}", -1, 2, None),
Among("er\u{00E9}", -1, 2, None),
Among("ir\u{00E9}", -1, 2, None),
Among("i\u{00F3}", -1, 2, None),
];
static A_9: &'static [Among<Context>; 8] = &[
Among("a", -1, 1, None),
Among("e", -1, 2, None),
Among("o", -1, 1, None),
Among("os", -1, 1, None),
Among("\u{00E1}", -1, 1, None),
Among("\u{00E9}", -1, 2, None),
Among("\u{00ED}", -1, 1, None),
Among("\u{00F3}", -1, 1, None),
];
static G_v: &'static [u8; 20] = &[17, 65, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 17, 4, 10];
#[derive(Clone)]
struct Context {
i_p2: usize,
i_p1: usize,
i_pV: usize,
}
fn r_mark_regions(env: &mut SnowballEnv, context: &mut Context) -> bool {
// (, line 31
context.i_pV = env.limit;
context.i_p1 = env.limit;
context.i_p2 = env.limit;
// do, line 37
let v_1 = env.cursor;
'lab0: loop {
// (, line 37
// or, line 39
'lab1: loop {
let v_2 = env.cursor;
'lab2: loop {
// (, line 38
if !env.in_grouping(G_v, 97, 252) {
break 'lab2;
}
// or, line 38
'lab3: loop {
let v_3 = env.cursor;
'lab4: loop {
// (, line 38
if !env.out_grouping(G_v, 97, 252) {
break 'lab4;
}
// gopast, line 38
'golab5: loop {
'lab6: loop {
if !env.in_grouping(G_v, 97, 252) {
break 'lab6;
}
break 'golab5;
}
if env.cursor >= env.limit {
break 'lab4;
}
env.next_char();
}
break 'lab3;
}
env.cursor = v_3;
// (, line 38
if !env.in_grouping(G_v, 97, 252) {
break 'lab2;
}
// gopast, line 38
'golab7: loop {
'lab8: loop {
if !env.out_grouping(G_v, 97, 252) {
break 'lab8;
}
break 'golab7;
}
if env.cursor >= env.limit {
break 'lab2;
}
env.next_char();
}
break 'lab3;
}
break 'lab1;
}
env.cursor = v_2;
// (, line 40
if !env.out_grouping(G_v, 97, 252) {
break 'lab0;
}
// or, line 40
'lab9: loop {
let v_6 = env.cursor;
'lab10: loop {
// (, line 40
if !env.out_grouping(G_v, 97, 252) {
break 'lab10;
}
// gopast, line 40
'golab11: loop {
'lab12: loop {
if !env.in_grouping(G_v, 97, 252) {
break 'lab12;
}
break 'golab11;
}
if env.cursor >= env.limit {
break 'lab10;
}
env.next_char();
}
break 'lab9;
}
env.cursor = v_6;
// (, line 40
if !env.in_grouping(G_v, 97, 252) {
break 'lab0;
}
// next, line 40
if env.cursor >= env.limit {
break 'lab0;
}
env.next_char();
break 'lab9;
}
break 'lab1;
}
// setmark pV, line 41
context.i_pV = env.cursor;
break 'lab0;
}
env.cursor = v_1;
// do, line 43
let v_8 = env.cursor;
'lab13: loop {
// (, line 43
// gopast, line 44
'golab14: loop {
'lab15: loop {
if !env.in_grouping(G_v, 97, 252) {
break 'lab15;
}
break 'golab14;
}
if env.cursor >= env.limit {
break 'lab13;
}
env.next_char();
}
// gopast, line 44
'golab16: loop {
'lab17: loop {
if !env.out_grouping(G_v, 97, 252) {
break 'lab17;
}
break 'golab16;
}
if env.cursor >= env.limit {
break 'lab13;
}
env.next_char();
}
// setmark p1, line 44
context.i_p1 = env.cursor;
// gopast, line 45
'golab18: loop {
'lab19: loop {
if !env.in_grouping(G_v, 97, 252) {
break 'lab19;
}
break 'golab18;
}
if env.cursor >= env.limit {
break 'lab13;
}
env.next_char();
}
// gopast, line 45
'golab20: loop {
'lab21: loop {
if !env.out_grouping(G_v, 97, 252) {
break 'lab21;
}
break 'golab20;
}
if env.cursor >= env.limit {
break 'lab13;
}
env.next_char();
}
// setmark p2, line 45
context.i_p2 = env.cursor;
break 'lab13;
}
env.cursor = v_8;
return true;
}
fn r_postlude(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// repeat, line 49
'replab0: loop{
let v_1 = env.cursor;
'lab1: for _ in 0..1 {
// (, line 49
// [, line 50
env.bra = env.cursor;
// substring, line 50
among_var = env.find_among(A_0, context);
if among_var == 0 {
break 'lab1;
}
// ], line 50
env.ket = env.cursor;
if among_var == 0 {
break 'lab1;
} else if among_var == 1 {
// (, line 51
// <-, line 51
if !env.slice_from("a") {
return false;
}
} else if among_var == 2 {
// (, line 52
// <-, line 52
if !env.slice_from("e") {
return false;
}
} else if among_var == 3 {
// (, line 53
// <-, line 53
if !env.slice_from("i") {
return false;
}
} else if among_var == 4 {
// (, line 54
// <-, line 54
if !env.slice_from("o") {
return false;
}
} else if among_var == 5 {
// (, line 55
// <-, line 55
if !env.slice_from("u") {
return false;
}
} else if among_var == 6 {
// (, line 57
// next, line 57
if env.cursor >= env.limit {
break 'lab1;
}
env.next_char();
}
continue 'replab0;
}
env.cursor = v_1;
break 'replab0;
}
return true;
}
fn r_RV(env: &mut SnowballEnv, context: &mut Context) -> bool {
if !(context.i_pV <= env.cursor){
return false;
}
return true;
}
fn r_R1(env: &mut SnowballEnv, context: &mut Context) -> bool {
if !(context.i_p1 <= env.cursor){
return false;
}
return true;
}
fn r_R2(env: &mut SnowballEnv, context: &mut Context) -> bool {
if !(context.i_p2 <= env.cursor){
return false;
}
return true;
}
fn r_attached_pronoun(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 67
// [, line 68
env.ket = env.cursor;
// substring, line 68
if env.find_among_b(A_1, context) == 0 {
return false;
}
// ], line 68
env.bra = env.cursor;
// substring, line 72
among_var = env.find_among_b(A_2, context);
if among_var == 0 {
return false;
}
// call RV, line 72
if !r_RV(env, context) {
return false;
}
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 73
// ], line 73
env.bra = env.cursor;
// <-, line 73
if !env.slice_from("iendo") {
return false;
}
} else if among_var == 2 {
// (, line 74
// ], line 74
env.bra = env.cursor;
// <-, line 74
if !env.slice_from("ando") {
return false;
}
} else if among_var == 3 {
// (, line 75
// ], line 75
env.bra = env.cursor;
// <-, line 75
if !env.slice_from("ar") {
return false;
}
} else if among_var == 4 {
// (, line 76
// ], line 76
env.bra = env.cursor;
// <-, line 76
if !env.slice_from("er") {
return false;
}
} else if among_var == 5 {
// (, line 77
// ], line 77
env.bra = env.cursor;
// <-, line 77
if !env.slice_from("ir") {
return false;
}
} else if among_var == 6 {
// (, line 81
// delete, line 81
if !env.slice_del() {
return false;
}
} else if among_var == 7 {
// (, line 82
// literal, line 82
if !env.eq_s_b(&"u") {
return false;
}
// delete, line 82
if !env.slice_del() {
return false;
}
}
return true;
}
fn r_standard_suffix(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 86
// [, line 87
env.ket = env.cursor;
// substring, line 87
among_var = env.find_among_b(A_6, context);
if among_var == 0 {
return false;
}
// ], line 87
env.bra = env.cursor;
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 98
// call R2, line 99
if !r_R2(env, context) {
return false;
}
// delete, line 99
if !env.slice_del() {
return false;
}
} else if among_var == 2 {
// (, line 104
// call R2, line 105
if !r_R2(env, context) {
return false;
}
// delete, line 105
if !env.slice_del() {
return false;
}
// try, line 106
let v_1 = env.limit - env.cursor;
'lab0: loop {
// (, line 106
// [, line 106
env.ket = env.cursor;
// literal, line 106
if !env.eq_s_b(&"ic") {
env.cursor = env.limit - v_1;
break 'lab0;
}
// ], line 106
env.bra = env.cursor;
// call R2, line 106
if !r_R2(env, context) {
env.cursor = env.limit - v_1;
break 'lab0;
}
// delete, line 106
if !env.slice_del() {
return false;
}
break 'lab0;
}
} else if among_var == 3 {
// (, line 110
// call R2, line 111
if !r_R2(env, context) {
return false;
}
// <-, line 111
if !env.slice_from("log") {
return false;
}
} else if among_var == 4 {
// (, line 114
// call R2, line 115
if !r_R2(env, context) {
return false;
}
// <-, line 115
if !env.slice_from("u") {
return false;
}
} else if among_var == 5 {
// (, line 118
// call R2, line 119
if !r_R2(env, context) {
return false;
}
// <-, line 119
if !env.slice_from("ente") {
return false;
}
} else if among_var == 6 {
// (, line 122
// call R1, line 123
if !r_R1(env, context) {
return false;
}
// delete, line 123
if !env.slice_del() {
return false;
}
// try, line 124
let v_2 = env.limit - env.cursor;
'lab1: loop {
// (, line 124
// [, line 125
env.ket = env.cursor;
// substring, line 125
among_var = env.find_among_b(A_3, context);
if among_var == 0 {
env.cursor = env.limit - v_2;
break 'lab1;
}
// ], line 125
env.bra = env.cursor;
// call R2, line 125
if !r_R2(env, context) {
env.cursor = env.limit - v_2;
break 'lab1;
}
// delete, line 125
if !env.slice_del() {
return false;
}
if among_var == 0 {
env.cursor = env.limit - v_2;
break 'lab1;
} else if among_var == 1 {
// (, line 126
// [, line 126
env.ket = env.cursor;
// literal, line 126
if !env.eq_s_b(&"at") {
env.cursor = env.limit - v_2;
break 'lab1;
}
// ], line 126
env.bra = env.cursor;
// call R2, line 126
if !r_R2(env, context) {
env.cursor = env.limit - v_2;
break 'lab1;
}
// delete, line 126
if !env.slice_del() {
return false;
}
}
break 'lab1;
}
} else if among_var == 7 {
// (, line 134
// call R2, line 135
if !r_R2(env, context) {
return false;
}
// delete, line 135
if !env.slice_del() {
return false;
}
// try, line 136
let v_3 = env.limit - env.cursor;
'lab2: loop {
// (, line 136
// [, line 137
env.ket = env.cursor;
// substring, line 137
among_var = env.find_among_b(A_4, context);
if among_var == 0 {
env.cursor = env.limit - v_3;
break 'lab2;
}
// ], line 137
env.bra = env.cursor;
if among_var == 0 {
env.cursor = env.limit - v_3;
break 'lab2;
} else if among_var == 1 {
// (, line 140
// call R2, line 140
if !r_R2(env, context) {
env.cursor = env.limit - v_3;
break 'lab2;
}
// delete, line 140
if !env.slice_del() {
return false;
}
}
break 'lab2;
}
} else if among_var == 8 {
// (, line 146
// call R2, line 147
if !r_R2(env, context) {
return false;
}
// delete, line 147
if !env.slice_del() {
return false;
}
// try, line 148
let v_4 = env.limit - env.cursor;
'lab3: loop {
// (, line 148
// [, line 149
env.ket = env.cursor;
// substring, line 149
among_var = env.find_among_b(A_5, context);
if among_var == 0 {
env.cursor = env.limit - v_4;
break 'lab3;
}
// ], line 149
env.bra = env.cursor;
if among_var == 0 {
env.cursor = env.limit - v_4;
break 'lab3;
} else if among_var == 1 {
// (, line 152
// call R2, line 152
if !r_R2(env, context) {
env.cursor = env.limit - v_4;
break 'lab3;
}
// delete, line 152
if !env.slice_del() {
return false;
}
}
break 'lab3;
}
} else if among_var == 9 {
// (, line 158
// call R2, line 159
if !r_R2(env, context) {
return false;
}
// delete, line 159
if !env.slice_del() {
return false;
}
// try, line 160
let v_5 = env.limit - env.cursor;
'lab4: loop {
// (, line 160
// [, line 161
env.ket = env.cursor;
// literal, line 161
if !env.eq_s_b(&"at") {
env.cursor = env.limit - v_5;
break 'lab4;
}
// ], line 161
env.bra = env.cursor;
// call R2, line 161
if !r_R2(env, context) {
env.cursor = env.limit - v_5;
break 'lab4;
}
// delete, line 161
if !env.slice_del() {
return false;
}
break 'lab4;
}
}
return true;
}
fn r_y_verb_suffix(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 167
// setlimit, line 168
let v_1 = env.limit - env.cursor;
// tomark, line 168
if env.cursor < context.i_pV {
return false;
}
env.cursor = context.i_pV;
let v_2 = env.limit_backward;
env.limit_backward = env.cursor;
env.cursor = env.limit - v_1;
// (, line 168
// [, line 168
env.ket = env.cursor;
// substring, line 168
among_var = env.find_among_b(A_7, context);
if among_var == 0 {
env.limit_backward = v_2;
return false;
}
// ], line 168
env.bra = env.cursor;
env.limit_backward = v_2;
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 171
// literal, line 171
if !env.eq_s_b(&"u") {
return false;
}
// delete, line 171
if !env.slice_del() {
return false;
}
}
return true;
}
fn r_verb_suffix(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 175
// setlimit, line 176
let v_1 = env.limit - env.cursor;
// tomark, line 176
if env.cursor < context.i_pV {
return false;
}
env.cursor = context.i_pV;
let v_2 = env.limit_backward;
env.limit_backward = env.cursor;
env.cursor = env.limit - v_1;
// (, line 176
// [, line 176
env.ket = env.cursor;
// substring, line 176
among_var = env.find_among_b(A_8, context);
if among_var == 0 {
env.limit_backward = v_2;
return false;
}
// ], line 176
env.bra = env.cursor;
env.limit_backward = v_2;
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 179
// try, line 179
let v_3 = env.limit - env.cursor;
'lab0: loop {
// (, line 179
// literal, line 179
if !env.eq_s_b(&"u") {
env.cursor = env.limit - v_3;
break 'lab0;
}
// test, line 179
let v_4 = env.limit - env.cursor;
// literal, line 179
if !env.eq_s_b(&"g") {
env.cursor = env.limit - v_3;
break 'lab0;
}
env.cursor = env.limit - v_4;
break 'lab0;
}
// ], line 179
env.bra = env.cursor;
// delete, line 179
if !env.slice_del() {
return false;
}
} else if among_var == 2 {
// (, line 200
// delete, line 200
if !env.slice_del() {
return false;
}
}
return true;
}
fn r_residual_suffix(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 204
// [, line 205
env.ket = env.cursor;
// substring, line 205
among_var = env.find_among_b(A_9, context);
if among_var == 0 {
return false;
}
// ], line 205
env.bra = env.cursor;
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 208
// call RV, line 208
if !r_RV(env, context) {
return false;
}
// delete, line 208
if !env.slice_del() {
return false;
}
} else if among_var == 2 {
// (, line 210
// call RV, line 210
if !r_RV(env, context) {
return false;
}
// delete, line 210
if !env.slice_del() {
return false;
}
// try, line 210
let v_1 = env.limit - env.cursor;
'lab0: loop {
// (, line 210
// [, line 210
env.ket = env.cursor;
// literal, line 210
if !env.eq_s_b(&"u") {
env.cursor = env.limit - v_1;
break 'lab0;
}
// ], line 210
env.bra = env.cursor;
// test, line 210
let v_2 = env.limit - env.cursor;
// literal, line 210
if !env.eq_s_b(&"g") {
env.cursor = env.limit - v_1;
break 'lab0;
}
env.cursor = env.limit - v_2;
// call RV, line 210
if !r_RV(env, context) {
env.cursor = env.limit - v_1;
break 'lab0;
}
// delete, line 210
if !env.slice_del() {
return false;
}
break 'lab0;
}
}
return true;
}
pub fn stem(env: &mut SnowballEnv) -> bool {
let mut context = &mut Context {
i_p2: 0,
i_p1: 0,
i_pV: 0,
};
// (, line 215
// do, line 216
let v_1 = env.cursor;
'lab0: loop {
// call mark_regions, line 216
if !r_mark_regions(env, context) {
break 'lab0;
}
break 'lab0;
}
env.cursor = v_1;
// backwards, line 217
env.limit_backward = env.cursor;
env.cursor = env.limit;
// (, line 217
// do, line 218
let v_2 = env.limit - env.cursor;
'lab1: loop {
// call attached_pronoun, line 218
if !r_attached_pronoun(env, context) {
break 'lab1;
}
break 'lab1;
}
env.cursor = env.limit - v_2;
// do, line 219
let v_3 = env.limit - env.cursor;
'lab2: loop {
// (, line 219
// or, line 219
'lab3: loop {
let v_4 = env.limit - env.cursor;
'lab4: loop {
// call standard_suffix, line 219
if !r_standard_suffix(env, context) {
break 'lab4;
}
break 'lab3;
}
env.cursor = env.limit - v_4;
'lab5: loop {
// call y_verb_suffix, line 220
if !r_y_verb_suffix(env, context) {
break 'lab5;
}
break 'lab3;
}
env.cursor = env.limit - v_4;
// call verb_suffix, line 221
if !r_verb_suffix(env, context) {
break 'lab2;
}
break 'lab3;
}
break 'lab2;
}
env.cursor = env.limit - v_3;
// do, line 223
let v_5 = env.limit - env.cursor;
'lab6: loop {
// call residual_suffix, line 223
if !r_residual_suffix(env, context) {
break 'lab6;
}
break 'lab6;
}
env.cursor = env.limit - v_5;
env.cursor = env.limit_backward;
// do, line 225
let v_6 = env.cursor;
'lab7: loop {
// call postlude, line 225
if !r_postlude(env, context) {
break 'lab7;
}
break 'lab7;
}
env.cursor = v_6;
return true;
}
| rust | MIT | 1fde09dfa08fb0fb07fbd6570aba8ecc98174edb | 2026-01-04T20:25:20.053159Z | false |
CurrySoftware/rust-stemmers | https://github.com/CurrySoftware/rust-stemmers/blob/1fde09dfa08fb0fb07fbd6570aba8ecc98174edb/src/snowball/algorithms/greek.rs | src/snowball/algorithms/greek.rs | //! This file was generated automatically by the Snowball to Rust compiler
//! http://snowballstem.org/
#![allow(non_upper_case_globals)]
#![allow(non_snake_case)]
#![allow(unused_variables)]
#![allow(unused_mut)]
use snowball::SnowballEnv;
use snowball::Among;
static A_0: &'static [Among<Context>; 46] = &[
Among("", -1, 25, None),
Among("\u{03C2}", 0, 18, None),
Among("\u{0386}", 0, 1, None),
Among("\u{0388}", 0, 5, None),
Among("\u{0389}", 0, 7, None),
Among("\u{038A}", 0, 9, None),
Among("\u{03CA}", 0, 7, None),
Among("\u{03CB}", 0, 20, None),
Among("\u{038C}", 0, 15, None),
Among("\u{03CC}", 0, 15, None),
Among("\u{03CD}", 0, 20, None),
Among("\u{038E}", 0, 20, None),
Among("\u{03CE}", 0, 24, None),
Among("\u{038F}", 0, 24, None),
Among("\u{0390}", 0, 7, None),
Among("\u{0391}", 0, 1, None),
Among("\u{0392}", 0, 2, None),
Among("\u{0393}", 0, 3, None),
Among("\u{0394}", 0, 4, None),
Among("\u{0395}", 0, 5, None),
Among("\u{0396}", 0, 6, None),
Among("\u{0397}", 0, 7, None),
Among("\u{0398}", 0, 8, None),
Among("\u{0399}", 0, 9, None),
Among("\u{039A}", 0, 10, None),
Among("\u{039B}", 0, 11, None),
Among("\u{039C}", 0, 12, None),
Among("\u{039D}", 0, 13, None),
Among("\u{039E}", 0, 14, None),
Among("\u{039F}", 0, 15, None),
Among("\u{03A0}", 0, 16, None),
Among("\u{03A1}", 0, 17, None),
Among("\u{03A3}", 0, 18, None),
Among("\u{03A4}", 0, 19, None),
Among("\u{03A5}", 0, 20, None),
Among("\u{03A6}", 0, 21, None),
Among("\u{03A7}", 0, 22, None),
Among("\u{03A8}", 0, 23, None),
Among("\u{03A9}", 0, 24, None),
Among("\u{03AA}", 0, 9, None),
Among("\u{03AB}", 0, 20, None),
Among("\u{03AC}", 0, 1, None),
Among("\u{03AD}", 0, 5, None),
Among("\u{03AE}", 0, 7, None),
Among("\u{03AF}", 0, 9, None),
Among("\u{03B0}", 0, 20, None),
];
static A_1: &'static [Among<Context>; 40] = &[
Among("\u{03BA}\u{03B1}\u{03B8}\u{03B5}\u{03C3}\u{03C4}\u{03C9}\u{03C3}", -1, 10, None),
Among("\u{03C6}\u{03C9}\u{03C3}", -1, 9, None),
Among("\u{03C0}\u{03B5}\u{03C1}\u{03B1}\u{03C3}", -1, 7, None),
Among("\u{03C4}\u{03B5}\u{03C1}\u{03B1}\u{03C3}", -1, 8, None),
Among("\u{03BA}\u{03C1}\u{03B5}\u{03B1}\u{03C3}", -1, 6, None),
Among("\u{03BA}\u{03B1}\u{03B8}\u{03B5}\u{03C3}\u{03C4}\u{03C9}\u{03C4}\u{03BF}\u{03C3}", -1, 10, None),
Among("\u{03C6}\u{03C9}\u{03C4}\u{03BF}\u{03C3}", -1, 9, None),
Among("\u{03C0}\u{03B5}\u{03C1}\u{03B1}\u{03C4}\u{03BF}\u{03C3}", -1, 7, None),
Among("\u{03C4}\u{03B5}\u{03C1}\u{03B1}\u{03C4}\u{03BF}\u{03C3}", -1, 8, None),
Among("\u{03BA}\u{03C1}\u{03B5}\u{03B1}\u{03C4}\u{03BF}\u{03C3}", -1, 6, None),
Among("\u{03B3}\u{03B5}\u{03B3}\u{03BF}\u{03BD}\u{03BF}\u{03C4}\u{03BF}\u{03C3}", -1, 11, None),
Among("\u{03B3}\u{03B5}\u{03B3}\u{03BF}\u{03BD}\u{03BF}\u{03C3}", -1, 11, None),
Among("\u{03C6}\u{03B1}\u{03B3}\u{03B9}\u{03BF}\u{03C5}", -1, 1, None),
Among("\u{03C3}\u{03BA}\u{03B1}\u{03B3}\u{03B9}\u{03BF}\u{03C5}", -1, 2, None),
Among("\u{03C3}\u{03BF}\u{03B3}\u{03B9}\u{03BF}\u{03C5}", -1, 4, None),
Among("\u{03C4}\u{03B1}\u{03C4}\u{03BF}\u{03B3}\u{03B9}\u{03BF}\u{03C5}", -1, 5, None),
Among("\u{03BF}\u{03BB}\u{03BF}\u{03B3}\u{03B9}\u{03BF}\u{03C5}", -1, 3, None),
Among("\u{03BA}\u{03B1}\u{03B8}\u{03B5}\u{03C3}\u{03C4}\u{03C9}\u{03C4}\u{03B1}", -1, 10, None),
Among("\u{03C6}\u{03C9}\u{03C4}\u{03B1}", -1, 9, None),
Among("\u{03C0}\u{03B5}\u{03C1}\u{03B1}\u{03C4}\u{03B1}", -1, 7, None),
Among("\u{03C4}\u{03B5}\u{03C1}\u{03B1}\u{03C4}\u{03B1}", -1, 8, None),
Among("\u{03BA}\u{03C1}\u{03B5}\u{03B1}\u{03C4}\u{03B1}", -1, 6, None),
Among("\u{03B3}\u{03B5}\u{03B3}\u{03BF}\u{03BD}\u{03BF}\u{03C4}\u{03B1}", -1, 11, None),
Among("\u{03C6}\u{03B1}\u{03B3}\u{03B9}\u{03B1}", -1, 1, None),
Among("\u{03C3}\u{03BA}\u{03B1}\u{03B3}\u{03B9}\u{03B1}", -1, 2, None),
Among("\u{03C3}\u{03BF}\u{03B3}\u{03B9}\u{03B1}", -1, 4, None),
Among("\u{03C4}\u{03B1}\u{03C4}\u{03BF}\u{03B3}\u{03B9}\u{03B1}", -1, 5, None),
Among("\u{03BF}\u{03BB}\u{03BF}\u{03B3}\u{03B9}\u{03B1}", -1, 3, None),
Among("\u{03C0}\u{03B5}\u{03C1}\u{03B1}\u{03C4}\u{03B7}", -1, 7, None),
Among("\u{03BA}\u{03B1}\u{03B8}\u{03B5}\u{03C3}\u{03C4}\u{03C9}\u{03C4}\u{03C9}\u{03BD}", -1, 10, None),
Among("\u{03C6}\u{03C9}\u{03C4}\u{03C9}\u{03BD}", -1, 9, None),
Among("\u{03C0}\u{03B5}\u{03C1}\u{03B1}\u{03C4}\u{03C9}\u{03BD}", -1, 7, None),
Among("\u{03C4}\u{03B5}\u{03C1}\u{03B1}\u{03C4}\u{03C9}\u{03BD}", -1, 8, None),
Among("\u{03BA}\u{03C1}\u{03B5}\u{03B1}\u{03C4}\u{03C9}\u{03BD}", -1, 6, None),
Among("\u{03B3}\u{03B5}\u{03B3}\u{03BF}\u{03BD}\u{03BF}\u{03C4}\u{03C9}\u{03BD}", -1, 11, None),
Among("\u{03C6}\u{03B1}\u{03B3}\u{03B9}\u{03C9}\u{03BD}", -1, 1, None),
Among("\u{03C3}\u{03BA}\u{03B1}\u{03B3}\u{03B9}\u{03C9}\u{03BD}", -1, 2, None),
Among("\u{03C3}\u{03BF}\u{03B3}\u{03B9}\u{03C9}\u{03BD}", -1, 4, None),
Among("\u{03C4}\u{03B1}\u{03C4}\u{03BF}\u{03B3}\u{03B9}\u{03C9}\u{03BD}", -1, 5, None),
Among("\u{03BF}\u{03BB}\u{03BF}\u{03B3}\u{03B9}\u{03C9}\u{03BD}", -1, 3, None),
];
static A_2: &'static [Among<Context>; 9] = &[
Among("\u{03C0}\u{03B1}", -1, 1, None),
Among("\u{03BE}\u{03B1}\u{03BD}\u{03B1}\u{03C0}\u{03B1}", 0, 1, None),
Among("\u{03B5}\u{03C0}\u{03B1}", 0, 1, None),
Among("\u{03C0}\u{03B5}\u{03C1}\u{03B9}\u{03C0}\u{03B1}", 0, 1, None),
Among("\u{03B1}\u{03BD}\u{03B1}\u{03BC}\u{03C0}\u{03B1}", 0, 1, None),
Among("\u{03B5}\u{03BC}\u{03C0}\u{03B1}", 0, 1, None),
Among("\u{03B4}\u{03B1}\u{03BD}\u{03B5}", -1, 1, None),
Among("\u{03B1}\u{03B8}\u{03C1}\u{03BF}", -1, 1, None),
Among("\u{03C3}\u{03C5}\u{03BD}\u{03B1}\u{03B8}\u{03C1}\u{03BF}", 7, 1, None),
];
static A_3: &'static [Among<Context>; 22] = &[
Among("\u{03C0}", -1, 1, None),
Among("\u{03B9}\u{03BC}\u{03C0}", 0, 1, None),
Among("\u{03C1}", -1, 1, None),
Among("\u{03C0}\u{03C1}", 2, 1, None),
Among("\u{03BC}\u{03C0}\u{03C1}", 3, 1, None),
Among("\u{03B1}\u{03C1}\u{03C1}", 2, 1, None),
Among("\u{03B3}\u{03BB}\u{03C5}\u{03BA}\u{03C5}\u{03C1}", 2, 1, None),
Among("\u{03C0}\u{03BF}\u{03BB}\u{03C5}\u{03C1}", 2, 1, None),
Among("\u{03B1}\u{03BC}\u{03C0}\u{03B1}\u{03C1}", 2, 1, None),
Among("\u{03BC}\u{03B1}\u{03C1}", 2, 1, None),
Among("\u{03B3}\u{03BA}\u{03C1}", 2, 1, None),
Among("\u{03C0}\u{03B9}\u{03C0}\u{03B5}\u{03C1}\u{03BF}\u{03C1}", 2, 1, None),
Among("\u{03B2}\u{03BF}\u{03BB}\u{03B2}\u{03BF}\u{03C1}", 2, 1, None),
Among("\u{03B3}\u{03BB}\u{03C5}\u{03BA}\u{03BF}\u{03C1}", 2, 1, None),
Among("\u{03BB}\u{03BF}\u{03C5}", -1, 1, None),
Among("\u{03B2}", -1, 1, None),
Among("\u{03B2}\u{03B1}\u{03B8}\u{03C5}\u{03C1}\u{03B9}", -1, 1, None),
Among("\u{03B2}\u{03B1}\u{03C1}\u{03BA}", -1, 1, None),
Among("\u{03BC}\u{03B1}\u{03C1}\u{03BA}", -1, 1, None),
Among("\u{03BB}", -1, 1, None),
Among("\u{03BC}", -1, 1, None),
Among("\u{03BA}\u{03BF}\u{03C1}\u{03BD}", -1, 1, None),
];
static A_4: &'static [Among<Context>; 14] = &[
Among("\u{03B9}\u{03B6}\u{03B5}\u{03C3}", -1, 1, None),
Among("\u{03B9}\u{03B6}\u{03B5}\u{03B9}\u{03C3}", -1, 1, None),
Among("\u{03B9}\u{03B6}\u{03C9}", -1, 1, None),
Among("\u{03B9}\u{03B6}\u{03B1}", -1, 1, None),
Among("\u{03B9}\u{03B6}\u{03B1}\u{03C4}\u{03B5}", -1, 1, None),
Among("\u{03B9}\u{03B6}\u{03B5}\u{03C4}\u{03B5}", -1, 1, None),
Among("\u{03B9}\u{03B6}\u{03B5}", -1, 1, None),
Among("\u{03B9}\u{03B6}\u{03BF}\u{03C5}\u{03BC}\u{03B5}", -1, 1, None),
Among("\u{03B9}\u{03B6}\u{03B1}\u{03BC}\u{03B5}", -1, 1, None),
Among("\u{03B9}\u{03B6}\u{03BF}\u{03C5}\u{03BD}\u{03B5}", -1, 1, None),
Among("\u{03B9}\u{03B6}\u{03B1}\u{03BD}\u{03B5}", -1, 1, None),
Among("\u{03B9}\u{03B6}\u{03B5}\u{03B9}", -1, 1, None),
Among("\u{03B9}\u{03B6}\u{03BF}\u{03C5}\u{03BD}", -1, 1, None),
Among("\u{03B9}\u{03B6}\u{03B1}\u{03BD}", -1, 1, None),
];
static A_5: &'static [Among<Context>; 8] = &[
Among("\u{03C3}", -1, 1, None),
Among("\u{03C7}", -1, 1, None),
Among("\u{03C5}\u{03C8}", -1, 1, None),
Among("\u{03B6}\u{03C9}", -1, 1, None),
Among("\u{03B2}\u{03B9}", -1, 1, None),
Among("\u{03BB}\u{03B9}", -1, 1, None),
Among("\u{03B1}\u{03BB}", -1, 1, None),
Among("\u{03B5}\u{03BD}", -1, 1, None),
];
static A_6: &'static [Among<Context>; 7] = &[
Among("\u{03C9}\u{03B8}\u{03B7}\u{03BA}\u{03B5}\u{03C3}", -1, 1, None),
Among("\u{03C9}\u{03B8}\u{03B7}\u{03BA}\u{03B1}", -1, 1, None),
Among("\u{03C9}\u{03B8}\u{03B7}\u{03BA}\u{03B1}\u{03C4}\u{03B5}", -1, 1, None),
Among("\u{03C9}\u{03B8}\u{03B7}\u{03BA}\u{03B5}", -1, 1, None),
Among("\u{03C9}\u{03B8}\u{03B7}\u{03BA}\u{03B1}\u{03BC}\u{03B5}", -1, 1, None),
Among("\u{03C9}\u{03B8}\u{03B7}\u{03BA}\u{03B1}\u{03BD}\u{03B5}", -1, 1, None),
Among("\u{03C9}\u{03B8}\u{03B7}\u{03BA}\u{03B1}\u{03BD}", -1, 1, None),
];
static A_7: &'static [Among<Context>; 19] = &[
Among("\u{03BE}\u{03B1}\u{03BD}\u{03B1}\u{03C0}\u{03B1}", -1, 1, None),
Among("\u{03B5}\u{03C0}\u{03B1}", -1, 1, None),
Among("\u{03C0}\u{03B5}\u{03C1}\u{03B9}\u{03C0}\u{03B1}", -1, 1, None),
Among("\u{03B1}\u{03BD}\u{03B1}\u{03BC}\u{03C0}\u{03B1}", -1, 1, None),
Among("\u{03B5}\u{03BC}\u{03C0}\u{03B1}", -1, 1, None),
Among("\u{03C7}\u{03B1}\u{03C1}\u{03C4}\u{03BF}\u{03C0}\u{03B1}", -1, 1, None),
Among("\u{03B5}\u{03BE}\u{03B1}\u{03C1}\u{03C7}\u{03B1}", -1, 1, None),
Among("\u{03C0}\u{03B5}", -1, 1, None),
Among("\u{03B5}\u{03C0}\u{03B5}", 7, 1, None),
Among("\u{03BC}\u{03B5}\u{03C4}\u{03B5}\u{03C0}\u{03B5}", 8, 1, None),
Among("\u{03B5}\u{03C3}\u{03B5}", -1, 1, None),
Among("\u{03BA}\u{03BB}\u{03B5}", -1, 1, None),
Among("\u{03B5}\u{03C3}\u{03C9}\u{03BA}\u{03BB}\u{03B5}", 11, 1, None),
Among("\u{03B5}\u{03BA}\u{03BB}\u{03B5}", 11, 1, None),
Among("\u{03B1}\u{03C0}\u{03B5}\u{03BA}\u{03BB}\u{03B5}", 13, 1, None),
Among("\u{03B1}\u{03C0}\u{03BF}\u{03BA}\u{03BB}\u{03B5}", 11, 1, None),
Among("\u{03B4}\u{03B1}\u{03BD}\u{03B5}", -1, 1, None),
Among("\u{03B1}\u{03B8}\u{03C1}\u{03BF}", -1, 1, None),
Among("\u{03C3}\u{03C5}\u{03BD}\u{03B1}\u{03B8}\u{03C1}\u{03BF}", 17, 1, None),
];
static A_8: &'static [Among<Context>; 13] = &[
Among("\u{03C0}", -1, 1, None),
Among("\u{03BB}\u{03B1}\u{03C1}", -1, 1, None),
Among("\u{03B4}\u{03B7}\u{03BC}\u{03BF}\u{03BA}\u{03C1}\u{03B1}\u{03C4}", -1, 1, None),
Among("\u{03B1}\u{03C6}", -1, 1, None),
Among("\u{03B3}\u{03B9}\u{03B3}\u{03B1}\u{03BD}\u{03C4}\u{03BF}\u{03B1}\u{03C6}", 3, 1, None),
Among("\u{03B3}\u{03B5}", -1, 1, None),
Among("\u{03B3}\u{03BA}\u{03B5}", -1, 1, None),
Among("\u{03B3}\u{03BA}", -1, 1, None),
Among("\u{03BC}", -1, 1, None),
Among("\u{03C0}\u{03BF}\u{03C5}\u{03BA}\u{03B1}\u{03BC}", 8, 1, None),
Among("\u{03BA}\u{03BF}\u{03BC}", 8, 1, None),
Among("\u{03B1}\u{03BD}", -1, 1, None),
Among("\u{03BF}\u{03BB}\u{03BF}", -1, 1, None),
];
static A_9: &'static [Among<Context>; 7] = &[
Among("\u{03B9}\u{03C3}\u{03B5}\u{03C3}", -1, 1, None),
Among("\u{03B9}\u{03C3}\u{03B1}", -1, 1, None),
Among("\u{03B9}\u{03C3}\u{03B5}", -1, 1, None),
Among("\u{03B9}\u{03C3}\u{03B1}\u{03C4}\u{03B5}", -1, 1, None),
Among("\u{03B9}\u{03C3}\u{03B1}\u{03BC}\u{03B5}", -1, 1, None),
Among("\u{03B9}\u{03C3}\u{03B1}\u{03BD}\u{03B5}", -1, 1, None),
Among("\u{03B9}\u{03C3}\u{03B1}\u{03BD}", -1, 1, None),
];
static A_10: &'static [Among<Context>; 19] = &[
Among("\u{03BE}\u{03B1}\u{03BD}\u{03B1}\u{03C0}\u{03B1}", -1, 1, None),
Among("\u{03B5}\u{03C0}\u{03B1}", -1, 1, None),
Among("\u{03C0}\u{03B5}\u{03C1}\u{03B9}\u{03C0}\u{03B1}", -1, 1, None),
Among("\u{03B1}\u{03BD}\u{03B1}\u{03BC}\u{03C0}\u{03B1}", -1, 1, None),
Among("\u{03B5}\u{03BC}\u{03C0}\u{03B1}", -1, 1, None),
Among("\u{03C7}\u{03B1}\u{03C1}\u{03C4}\u{03BF}\u{03C0}\u{03B1}", -1, 1, None),
Among("\u{03B5}\u{03BE}\u{03B1}\u{03C1}\u{03C7}\u{03B1}", -1, 1, None),
Among("\u{03C0}\u{03B5}", -1, 1, None),
Among("\u{03B5}\u{03C0}\u{03B5}", 7, 1, None),
Among("\u{03BC}\u{03B5}\u{03C4}\u{03B5}\u{03C0}\u{03B5}", 8, 1, None),
Among("\u{03B5}\u{03C3}\u{03B5}", -1, 1, None),
Among("\u{03BA}\u{03BB}\u{03B5}", -1, 1, None),
Among("\u{03B5}\u{03C3}\u{03C9}\u{03BA}\u{03BB}\u{03B5}", 11, 1, None),
Among("\u{03B5}\u{03BA}\u{03BB}\u{03B5}", 11, 1, None),
Among("\u{03B1}\u{03C0}\u{03B5}\u{03BA}\u{03BB}\u{03B5}", 13, 1, None),
Among("\u{03B1}\u{03C0}\u{03BF}\u{03BA}\u{03BB}\u{03B5}", 11, 1, None),
Among("\u{03B4}\u{03B1}\u{03BD}\u{03B5}", -1, 1, None),
Among("\u{03B1}\u{03B8}\u{03C1}\u{03BF}", -1, 1, None),
Among("\u{03C3}\u{03C5}\u{03BD}\u{03B1}\u{03B8}\u{03C1}\u{03BF}", 17, 1, None),
];
static A_11: &'static [Among<Context>; 7] = &[
Among("\u{03B9}\u{03C3}\u{03B5}\u{03B9}\u{03C3}", -1, 1, None),
Among("\u{03B9}\u{03C3}\u{03C9}", -1, 1, None),
Among("\u{03B9}\u{03C3}\u{03B5}\u{03C4}\u{03B5}", -1, 1, None),
Among("\u{03B9}\u{03C3}\u{03BF}\u{03C5}\u{03BC}\u{03B5}", -1, 1, None),
Among("\u{03B9}\u{03C3}\u{03BF}\u{03C5}\u{03BD}\u{03B5}", -1, 1, None),
Among("\u{03B9}\u{03C3}\u{03B5}\u{03B9}", -1, 1, None),
Among("\u{03B9}\u{03C3}\u{03BF}\u{03C5}\u{03BD}", -1, 1, None),
];
static A_12: &'static [Among<Context>; 7] = &[
Among("\u{03C3}\u{03B5}", -1, 1, None),
Among("\u{03B1}\u{03C3}\u{03B5}", 0, 1, None),
Among("\u{03C0}\u{03BB}\u{03B5}", -1, 1, None),
Among("\u{03BA}\u{03BB}\u{03B5}", -1, 1, None),
Among("\u{03B5}\u{03C3}\u{03C9}\u{03BA}\u{03BB}\u{03B5}", 3, 1, None),
Among("\u{03B4}\u{03B1}\u{03BD}\u{03B5}", -1, 1, None),
Among("\u{03C3}\u{03C5}\u{03BD}\u{03B1}\u{03B8}\u{03C1}\u{03BF}", -1, 1, None),
];
static A_13: &'static [Among<Context>; 33] = &[
Among("\u{03C0}", -1, 1, None),
Among("\u{03B5}\u{03C5}\u{03C0}", 0, 1, None),
Among("\u{03B1}\u{03C0}", 0, 1, None),
Among("\u{03B5}\u{03BC}\u{03C0}", 0, 1, None),
Among("\u{03B3}\u{03C5}\u{03C1}", -1, 1, None),
Among("\u{03C7}\u{03C1}", -1, 1, None),
Among("\u{03C7}\u{03C9}\u{03C1}", -1, 1, None),
Among("\u{03B1}\u{03C1}", -1, 1, None),
Among("\u{03B1}\u{03BF}\u{03C1}", -1, 1, None),
Among("\u{03C7}\u{03C4}", -1, 1, None),
Among("\u{03B1}\u{03C7}\u{03C4}", 9, 1, None),
Among("\u{03BA}\u{03C4}", -1, 1, None),
Among("\u{03B1}\u{03BA}\u{03C4}", 11, 1, None),
Among("\u{03C3}\u{03C7}", -1, 1, None),
Among("\u{03B1}\u{03C3}\u{03C7}", 13, 1, None),
Among("\u{03C4}\u{03B1}\u{03C7}", -1, 1, None),
Among("\u{03C5}\u{03C8}", -1, 1, None),
Among("\u{03B1}\u{03C4}\u{03B1}", -1, 1, None),
Among("\u{03C6}\u{03B1}", -1, 1, None),
Among("\u{03B7}\u{03C6}\u{03B1}", 18, 1, None),
Among("\u{03BB}\u{03C5}\u{03B3}", -1, 1, None),
Among("\u{03BC}\u{03B5}\u{03B3}", -1, 1, None),
Among("\u{03B7}\u{03B4}", -1, 1, None),
Among("\u{03B5}\u{03C7}\u{03B8}", -1, 1, None),
Among("\u{03BA}\u{03B1}\u{03B8}", -1, 1, None),
Among("\u{03C3}\u{03BA}", -1, 1, None),
Among("\u{03BA}\u{03B1}\u{03BA}", -1, 1, None),
Among("\u{03BC}\u{03B1}\u{03BA}", -1, 1, None),
Among("\u{03BA}\u{03C5}\u{03BB}", -1, 1, None),
Among("\u{03C6}\u{03B9}\u{03BB}", -1, 1, None),
Among("\u{03BC}", -1, 1, None),
Among("\u{03B3}\u{03B5}\u{03BC}", 30, 1, None),
Among("\u{03B1}\u{03C7}\u{03BD}", -1, 1, None),
];
static A_14: &'static [Among<Context>; 11] = &[
Among("\u{03B9}\u{03C3}\u{03C4}\u{03BF}\u{03C5}\u{03C3}", -1, 1, None),
Among("\u{03B9}\u{03C3}\u{03C4}\u{03B5}\u{03C3}", -1, 1, None),
Among("\u{03B9}\u{03C3}\u{03C4}\u{03B7}\u{03C3}", -1, 1, None),
Among("\u{03B9}\u{03C3}\u{03C4}\u{03BF}\u{03C3}", -1, 1, None),
Among("\u{03B9}\u{03C3}\u{03C4}\u{03BF}\u{03C5}", -1, 1, None),
Among("\u{03B9}\u{03C3}\u{03C4}\u{03B1}", -1, 1, None),
Among("\u{03B9}\u{03C3}\u{03C4}\u{03B5}", -1, 1, None),
Among("\u{03B9}\u{03C3}\u{03C4}\u{03B7}", -1, 1, None),
Among("\u{03B9}\u{03C3}\u{03C4}\u{03BF}\u{03B9}", -1, 1, None),
Among("\u{03B9}\u{03C3}\u{03C4}\u{03C9}\u{03BD}", -1, 1, None),
Among("\u{03B9}\u{03C3}\u{03C4}\u{03BF}", -1, 1, None),
];
static A_15: &'static [Among<Context>; 5] = &[
Among("\u{03C3}\u{03B5}", -1, 1, None),
Among("\u{03BC}\u{03B5}\u{03C4}\u{03B1}\u{03C3}\u{03B5}", 0, 1, None),
Among("\u{03BC}\u{03B9}\u{03BA}\u{03C1}\u{03BF}\u{03C3}\u{03B5}", 0, 1, None),
Among("\u{03B5}\u{03B3}\u{03BA}\u{03BB}\u{03B5}", -1, 1, None),
Among("\u{03B1}\u{03C0}\u{03BF}\u{03BA}\u{03BB}\u{03B5}", -1, 1, None),
];
static A_16: &'static [Among<Context>; 2] = &[
Among("\u{03B4}\u{03B1}\u{03BD}\u{03B5}", -1, 1, None),
Among("\u{03B1}\u{03BD}\u{03C4}\u{03B9}\u{03B4}\u{03B1}\u{03BD}\u{03B5}", 0, 1, None),
];
static A_17: &'static [Among<Context>; 10] = &[
Among("\u{03C4}\u{03BF}\u{03C0}\u{03B9}\u{03BA}", -1, 7, None),
Among("\u{03C3}\u{03BA}\u{03B5}\u{03C0}\u{03C4}\u{03B9}\u{03BA}", -1, 6, None),
Among("\u{03B3}\u{03BD}\u{03C9}\u{03C3}\u{03C4}\u{03B9}\u{03BA}", -1, 3, None),
Among("\u{03B1}\u{03B3}\u{03BD}\u{03C9}\u{03C3}\u{03C4}\u{03B9}\u{03BA}", 2, 1, None),
Among("\u{03B5}\u{03BA}\u{03BB}\u{03B5}\u{03BA}\u{03C4}\u{03B9}\u{03BA}", -1, 5, None),
Among("\u{03B1}\u{03C4}\u{03BF}\u{03BC}\u{03B9}\u{03BA}", -1, 2, None),
Among("\u{03B5}\u{03B8}\u{03BD}\u{03B9}\u{03BA}", -1, 4, None),
Among("\u{03B8}\u{03B5}\u{03B1}\u{03C4}\u{03C1}\u{03B9}\u{03BD}", -1, 10, None),
Among("\u{03B1}\u{03BB}\u{03B5}\u{03BE}\u{03B1}\u{03BD}\u{03B4}\u{03C1}\u{03B9}\u{03BD}", -1, 8, None),
Among("\u{03B2}\u{03C5}\u{03B6}\u{03B1}\u{03BD}\u{03C4}\u{03B9}\u{03BD}", -1, 9, None),
];
static A_18: &'static [Among<Context>; 6] = &[
Among("\u{03B9}\u{03C3}\u{03BC}\u{03BF}\u{03C5}\u{03C3}", -1, 1, None),
Among("\u{03B9}\u{03C3}\u{03BC}\u{03BF}\u{03C3}", -1, 1, None),
Among("\u{03B9}\u{03C3}\u{03BC}\u{03BF}\u{03C5}", -1, 1, None),
Among("\u{03B9}\u{03C3}\u{03BC}\u{03BF}\u{03B9}", -1, 1, None),
Among("\u{03B9}\u{03C3}\u{03BC}\u{03C9}\u{03BD}", -1, 1, None),
Among("\u{03B9}\u{03C3}\u{03BC}\u{03BF}", -1, 1, None),
];
static A_19: &'static [Among<Context>; 2] = &[
Among("\u{03C3}", -1, 1, None),
Among("\u{03C7}", -1, 1, None),
];
static A_20: &'static [Among<Context>; 4] = &[
Among("\u{03B1}\u{03C1}\u{03B1}\u{03BA}\u{03B9}\u{03B1}", -1, 1, None),
Among("\u{03BF}\u{03C5}\u{03B4}\u{03B1}\u{03BA}\u{03B9}\u{03B1}", -1, 1, None),
Among("\u{03B1}\u{03C1}\u{03B1}\u{03BA}\u{03B9}", -1, 1, None),
Among("\u{03BF}\u{03C5}\u{03B4}\u{03B1}\u{03BA}\u{03B9}", -1, 1, None),
];
static A_21: &'static [Among<Context>; 33] = &[
Among("\u{03BA}\u{03B1}\u{03C4}\u{03C1}\u{03B1}\u{03C0}", -1, 1, None),
Among("\u{03C1}", -1, 1, None),
Among("\u{03B2}\u{03C1}", 1, 1, None),
Among("\u{03BB}\u{03B1}\u{03B2}\u{03C1}", 2, 1, None),
Among("\u{03B1}\u{03BC}\u{03B2}\u{03C1}", 2, 1, None),
Among("\u{03BC}\u{03B5}\u{03C1}", 1, 1, None),
Among("\u{03B1}\u{03BD}\u{03B8}\u{03C1}", 1, 1, None),
Among("\u{03BA}\u{03BF}\u{03C1}", 1, 1, None),
Among("\u{03C3}", -1, 1, None),
Among("\u{03BD}\u{03B1}\u{03B3}\u{03BA}\u{03B1}\u{03C3}", 8, 1, None),
Among("\u{03BC}\u{03BF}\u{03C5}\u{03C3}\u{03C4}", -1, 1, None),
Among("\u{03C1}\u{03C5}", -1, 1, None),
Among("\u{03C6}", -1, 1, None),
Among("\u{03C3}\u{03C6}", 12, 1, None),
Among("\u{03B1}\u{03BB}\u{03B9}\u{03C3}\u{03C6}", 13, 1, None),
Among("\u{03C7}", -1, 1, None),
Among("\u{03B2}\u{03B1}\u{03BC}\u{03B2}", -1, 1, None),
Among("\u{03C3}\u{03BB}\u{03BF}\u{03B2}", -1, 1, None),
Among("\u{03C4}\u{03C3}\u{03B5}\u{03C7}\u{03BF}\u{03C3}\u{03BB}\u{03BF}\u{03B2}", 17, 1, None),
Among("\u{03C4}\u{03B6}", -1, 1, None),
Among("\u{03BA}", -1, 1, None),
Among("\u{03C3}\u{03BA}", 20, 1, None),
Among("\u{03BA}\u{03B1}\u{03C0}\u{03B1}\u{03BA}", 20, 1, None),
Among("\u{03C3}\u{03BF}\u{03BA}", 20, 1, None),
Among("\u{03C0}\u{03BB}", -1, 1, None),
Among("\u{03C6}\u{03C5}\u{03BB}", -1, 1, None),
Among("\u{03BB}\u{03BF}\u{03C5}\u{03BB}", -1, 1, None),
Among("\u{03BC}\u{03B1}\u{03BB}", -1, 1, None),
Among("\u{03C6}\u{03B1}\u{03C1}\u{03BC}", -1, 1, None),
Among("\u{03BA}\u{03B1}\u{03B9}\u{03BC}", -1, 1, None),
Among("\u{03BA}\u{03BB}\u{03B9}\u{03BC}", -1, 1, None),
Among("\u{03C3}\u{03C0}\u{03B1}\u{03BD}", -1, 1, None),
Among("\u{03BA}\u{03BF}\u{03BD}", -1, 1, None),
];
static A_22: &'static [Among<Context>; 15] = &[
Among("\u{03C0}", -1, 1, None),
Among("\u{03C0}\u{03B1}\u{03C4}\u{03B5}\u{03C1}", -1, 1, None),
Among("\u{03C4}\u{03BF}\u{03C3}", -1, 1, None),
Among("\u{03BD}\u{03C5}\u{03C6}", -1, 1, None),
Among("\u{03B2}", -1, 1, None),
Among("\u{03BA}\u{03B1}\u{03C1}\u{03B4}", -1, 1, None),
Among("\u{03B6}", -1, 1, None),
Among("\u{03C3}\u{03BA}", -1, 1, None),
Among("\u{03B2}\u{03B1}\u{03BB}", -1, 1, None),
Among("\u{03B3}\u{03BB}", -1, 1, None),
Among("\u{03C4}\u{03C1}\u{03B9}\u{03C0}\u{03BF}\u{03BB}", -1, 1, None),
Among("\u{03BC}\u{03B1}\u{03BA}\u{03C1}\u{03C5}\u{03BD}", -1, 1, None),
Among("\u{03B3}\u{03B9}\u{03B1}\u{03BD}", -1, 1, None),
Among("\u{03B7}\u{03B3}\u{03BF}\u{03C5}\u{03BC}\u{03B5}\u{03BD}", -1, 1, None),
Among("\u{03BA}\u{03BF}\u{03BD}", -1, 1, None),
];
static A_23: &'static [Among<Context>; 8] = &[
Among("\u{03B9}\u{03C4}\u{03C3}\u{03B1}\u{03C3}", -1, 1, None),
Among("\u{03B9}\u{03C4}\u{03C3}\u{03B5}\u{03C3}", -1, 1, None),
Among("\u{03B9}\u{03C4}\u{03C3}\u{03B1}", -1, 1, None),
Among("\u{03B1}\u{03BA}\u{03B9}\u{03B1}", -1, 1, None),
Among("\u{03B1}\u{03C1}\u{03B1}\u{03BA}\u{03B9}\u{03B1}", 3, 1, None),
Among("\u{03B1}\u{03BA}\u{03B9}", -1, 1, None),
Among("\u{03B1}\u{03C1}\u{03B1}\u{03BA}\u{03B9}", 5, 1, None),
Among("\u{03B9}\u{03C4}\u{03C3}\u{03C9}\u{03BD}", -1, 1, None),
];
static A_24: &'static [Among<Context>; 4] = &[
Among("\u{03B9}\u{03C1}", -1, 1, None),
Among("\u{03C8}\u{03B1}\u{03BB}", -1, 1, None),
Among("\u{03B1}\u{03B9}\u{03C6}\u{03BD}", -1, 1, None),
Among("\u{03BF}\u{03BB}\u{03BF}", -1, 1, None),
];
static A_25: &'static [Among<Context>; 2] = &[
Among("\u{03B5}", -1, 1, None),
Among("\u{03C0}\u{03B1}\u{03B9}\u{03C7}\u{03BD}", -1, 1, None),
];
static A_26: &'static [Among<Context>; 3] = &[
Among("\u{03B9}\u{03B4}\u{03B9}\u{03B1}", -1, 1, None),
Among("\u{03B9}\u{03B4}\u{03B9}\u{03C9}\u{03BD}", -1, 1, None),
Among("\u{03B9}\u{03B4}\u{03B9}\u{03BF}", -1, 1, None),
];
static A_27: &'static [Among<Context>; 7] = &[
Among("\u{03C1}", -1, 1, None),
Among("\u{03B9}\u{03B2}", -1, 1, None),
Among("\u{03B4}", -1, 1, None),
Among("\u{03BB}\u{03C5}\u{03BA}", -1, 1, None),
Among("\u{03C6}\u{03C1}\u{03B1}\u{03B3}\u{03BA}", -1, 1, None),
Among("\u{03BF}\u{03B2}\u{03B5}\u{03BB}", -1, 1, None),
Among("\u{03BC}\u{03B7}\u{03BD}", -1, 1, None),
];
static A_28: &'static [Among<Context>; 4] = &[
Among("\u{03B9}\u{03C3}\u{03BA}\u{03BF}\u{03C3}", -1, 1, None),
Among("\u{03B9}\u{03C3}\u{03BA}\u{03BF}\u{03C5}", -1, 1, None),
Among("\u{03B9}\u{03C3}\u{03BA}\u{03B5}", -1, 1, None),
Among("\u{03B9}\u{03C3}\u{03BA}\u{03BF}", -1, 1, None),
];
static A_29: &'static [Among<Context>; 2] = &[
Among("\u{03B1}\u{03B4}\u{03B5}\u{03C3}", -1, 1, None),
Among("\u{03B1}\u{03B4}\u{03C9}\u{03BD}", -1, 1, None),
];
static A_30: &'static [Among<Context>; 10] = &[
Among("\u{03BC}\u{03C0}\u{03B1}\u{03BC}\u{03C0}", -1, -1, None),
Among("\u{03BA}\u{03C5}\u{03C1}", -1, -1, None),
Among("\u{03C0}\u{03B1}\u{03C4}\u{03B5}\u{03C1}", -1, -1, None),
Among("\u{03C0}\u{03B5}\u{03B8}\u{03B5}\u{03C1}", -1, -1, None),
Among("\u{03BD}\u{03C4}\u{03B1}\u{03BD}\u{03C4}", -1, -1, None),
Among("\u{03B3}\u{03B9}\u{03B1}\u{03B3}\u{03B9}", -1, -1, None),
Among("\u{03B8}\u{03B5}\u{03B9}", -1, -1, None),
Among("\u{03BF}\u{03BA}", -1, -1, None),
Among("\u{03BC}\u{03B1}\u{03BC}", -1, -1, None),
Among("\u{03BC}\u{03B1}\u{03BD}", -1, -1, None),
];
static A_31: &'static [Among<Context>; 2] = &[
Among("\u{03B5}\u{03B4}\u{03B5}\u{03C3}", -1, 1, None),
Among("\u{03B5}\u{03B4}\u{03C9}\u{03BD}", -1, 1, None),
];
static A_32: &'static [Among<Context>; 8] = &[
Among("\u{03BA}\u{03C1}\u{03B1}\u{03C3}\u{03C0}", -1, 1, None),
Among("\u{03C5}\u{03C0}", -1, 1, None),
Among("\u{03B4}\u{03B1}\u{03C0}", -1, 1, None),
Among("\u{03B3}\u{03B7}\u{03C0}", -1, 1, None),
Among("\u{03B9}\u{03C0}", -1, 1, None),
Among("\u{03B5}\u{03BC}\u{03C0}", -1, 1, None),
Among("\u{03BF}\u{03C0}", -1, 1, None),
Among("\u{03BC}\u{03B9}\u{03BB}", -1, 1, None),
];
static A_33: &'static [Among<Context>; 2] = &[
Among("\u{03BF}\u{03C5}\u{03B4}\u{03B5}\u{03C3}", -1, 1, None),
Among("\u{03BF}\u{03C5}\u{03B4}\u{03C9}\u{03BD}", -1, 1, None),
];
static A_34: &'static [Among<Context>; 15] = &[
Among("\u{03C3}\u{03C0}", -1, 1, None),
Among("\u{03C6}\u{03C1}", -1, 1, None),
Among("\u{03C3}", -1, 1, None),
Among("\u{03BB}\u{03B9}\u{03C7}", -1, 1, None),
Among("\u{03C4}\u{03C1}\u{03B1}\u{03B3}", -1, 1, None),
Among("\u{03C6}\u{03B5}", -1, 1, None),
Among("\u{03B1}\u{03C1}\u{03BA}", -1, 1, None),
Among("\u{03C3}\u{03BA}", -1, 1, None),
Among("\u{03BA}\u{03B1}\u{03BB}\u{03B9}\u{03B1}\u{03BA}", -1, 1, None),
Among("\u{03BB}\u{03BF}\u{03C5}\u{03BB}", -1, 1, None),
Among("\u{03C6}\u{03BB}", -1, 1, None),
Among("\u{03C0}\u{03B5}\u{03C4}\u{03B1}\u{03BB}", -1, 1, None),
Among("\u{03B2}\u{03B5}\u{03BB}", -1, 1, None),
Among("\u{03C7}\u{03BD}", -1, 1, None),
Among("\u{03C0}\u{03BB}\u{03B5}\u{03BE}", -1, 1, None),
];
static A_35: &'static [Among<Context>; 2] = &[
Among("\u{03B5}\u{03C9}\u{03C3}", -1, 1, None),
Among("\u{03B5}\u{03C9}\u{03BD}", -1, 1, None),
];
static A_36: &'static [Among<Context>; 8] = &[
Among("\u{03C0}", -1, 1, None),
Among("\u{03C0}\u{03B1}\u{03C1}", -1, 1, None),
Among("\u{03B4}", -1, 1, None),
Among("\u{03B9}\u{03B4}", 2, 1, None),
Among("\u{03B8}", -1, 1, None),
Among("\u{03B3}\u{03B1}\u{03BB}", -1, 1, None),
Among("\u{03B5}\u{03BB}", -1, 1, None),
Among("\u{03BD}", -1, 1, None),
];
static A_37: &'static [Among<Context>; 3] = &[
Among("\u{03B9}\u{03BF}\u{03C5}", -1, 1, None),
Among("\u{03B9}\u{03B1}", -1, 1, None),
Among("\u{03B9}\u{03C9}\u{03BD}", -1, 1, None),
];
static A_38: &'static [Among<Context>; 4] = &[
Among("\u{03B9}\u{03BA}\u{03BF}\u{03C5}", -1, 1, None),
Among("\u{03B9}\u{03BA}\u{03B1}", -1, 1, None),
Among("\u{03B9}\u{03BA}\u{03C9}\u{03BD}", -1, 1, None),
Among("\u{03B9}\u{03BA}\u{03BF}", -1, 1, None),
];
static A_39: &'static [Among<Context>; 36] = &[
Among("\u{03BA}\u{03B1}\u{03BB}\u{03C0}", -1, 1, None),
Among("\u{03B3}\u{03B5}\u{03C1}", -1, 1, None),
Among("\u{03C0}\u{03BB}\u{03B9}\u{03B1}\u{03C4}\u{03C3}", -1, 1, None),
Among("\u{03C0}\u{03B5}\u{03C4}\u{03C3}", -1, 1, None),
Among("\u{03C0}\u{03B9}\u{03C4}\u{03C3}", -1, 1, None),
Among("\u{03C6}\u{03C5}\u{03C3}", -1, 1, None),
Among("\u{03C7}\u{03B1}\u{03C3}", -1, 1, None),
Among("\u{03BC}\u{03C0}\u{03BF}\u{03C3}", -1, 1, None),
Among("\u{03C3}\u{03B5}\u{03C1}\u{03C4}", -1, 1, None),
Among("\u{03BC}\u{03C0}\u{03B1}\u{03B3}\u{03B9}\u{03B1}\u{03C4}", -1, 1, None),
Among("\u{03BD}\u{03B9}\u{03C4}", -1, 1, None),
Among("\u{03C0}\u{03B9}\u{03BA}\u{03B1}\u{03BD}\u{03C4}", -1, 1, None),
Among("\u{03B5}\u{03BE}\u{03C9}\u{03B4}", -1, 1, None),
Among("\u{03B1}\u{03B4}", -1, 1, None),
Among("\u{03BA}\u{03B1}\u{03C4}\u{03B1}\u{03B4}", 13, 1, None),
Among("\u{03C3}\u{03C5}\u{03BD}\u{03B1}\u{03B4}", 13, 1, None),
Among("\u{03B1}\u{03BD}\u{03C4}\u{03B9}\u{03B4}", -1, 1, None),
Among("\u{03B5}\u{03BD}\u{03B4}", -1, 1, None),
Among("\u{03C5}\u{03C0}\u{03BF}\u{03B4}", -1, 1, None),
Among("\u{03C0}\u{03C1}\u{03C9}\u{03C4}\u{03BF}\u{03B4}", -1, 1, None),
Among("\u{03C6}\u{03C5}\u{03BB}\u{03BF}\u{03B4}", -1, 1, None),
Among("\u{03B7}\u{03B8}", -1, 1, None),
Among("\u{03B1}\u{03BD}\u{03B7}\u{03B8}", 21, 1, None),
Among("\u{03BE}\u{03B9}\u{03BA}", -1, 1, None),
Among("\u{03BC}\u{03BF}\u{03C5}\u{03BB}", -1, 1, None),
Among("\u{03B1}\u{03BB}", -1, 1, None),
Among("\u{03B1}\u{03BC}\u{03BC}\u{03BF}\u{03C7}\u{03B1}\u{03BB}", 25, 1, None),
Among("\u{03C3}\u{03C5}\u{03BD}\u{03BF}\u{03BC}\u{03B7}\u{03BB}", -1, 1, None),
Among("\u{03BC}\u{03C0}\u{03BF}\u{03BB}", -1, 1, None),
Among("\u{03B2}\u{03C1}\u{03C9}\u{03BC}", -1, 1, None),
Among("\u{03C4}\u{03C3}\u{03B1}\u{03BC}", -1, 1, None),
Among("\u{03BC}\u{03C0}\u{03B1}\u{03BD}", -1, 1, None),
Among("\u{03B1}\u{03BC}\u{03B1}\u{03BD}", -1, 1, None),
Among("\u{03BA}\u{03B1}\u{03BB}\u{03BB}\u{03B9}\u{03BD}", -1, 1, None),
Among("\u{03C0}\u{03BF}\u{03C3}\u{03C4}\u{03B5}\u{03BB}\u{03BD}", -1, 1, None),
Among("\u{03C6}\u{03B9}\u{03BB}\u{03BF}\u{03BD}", -1, 1, None),
];
static A_40: &'static [Among<Context>; 5] = &[
Among("\u{03BF}\u{03C5}\u{03C3}\u{03B1}\u{03BC}\u{03B5}", -1, 1, None),
Among("\u{03B7}\u{03C3}\u{03B1}\u{03BC}\u{03B5}", -1, 1, None),
Among("\u{03B1}\u{03B3}\u{03B1}\u{03BC}\u{03B5}", -1, 1, None),
Among("\u{03B7}\u{03BA}\u{03B1}\u{03BC}\u{03B5}", -1, 1, None),
Among("\u{03B7}\u{03B8}\u{03B7}\u{03BA}\u{03B1}\u{03BC}\u{03B5}", 3, 1, None),
];
static A_41: &'static [Among<Context>; 12] = &[
Among("\u{03B1}\u{03BD}\u{03B1}\u{03C0}", -1, 1, None),
Among("\u{03C0}\u{03B9}\u{03BA}\u{03C1}", -1, 1, None),
Among("\u{03B1}\u{03C0}\u{03BF}\u{03C3}\u{03C4}", -1, 1, None),
Among("\u{03C0}\u{03BF}\u{03C4}", -1, 1, None),
Among("\u{03C7}", -1, 1, None),
Among("\u{03C3}\u{03B9}\u{03C7}", 4, 1, None),
Among("\u{03B2}\u{03BF}\u{03C5}\u{03B2}", -1, 1, None),
Among("\u{03C0}\u{03B5}\u{03B8}", -1, 1, None),
Among("\u{03BE}\u{03B5}\u{03B8}", -1, 1, None),
Among("\u{03B1}\u{03C0}\u{03BF}\u{03B8}", -1, 1, None),
Among("\u{03B1}\u{03C0}\u{03BF}\u{03BA}", -1, 1, None),
Among("\u{03BF}\u{03C5}\u{03BB}", -1, 1, None),
];
static A_42: &'static [Among<Context>; 2] = &[
Among("\u{03C4}\u{03C1}", -1, 1, None),
Among("\u{03C4}\u{03C3}", -1, 1, None),
];
static A_43: &'static [Among<Context>; 11] = &[
Among("\u{03BF}\u{03C5}\u{03C3}\u{03B1}\u{03BD}\u{03B5}", -1, 1, None),
Among("\u{03B7}\u{03C3}\u{03B1}\u{03BD}\u{03B5}", -1, 1, None),
Among("\u{03BF}\u{03C5}\u{03BD}\u{03C4}\u{03B1}\u{03BD}\u{03B5}", -1, 1, None),
Among("\u{03B9}\u{03BF}\u{03C5}\u{03BD}\u{03C4}\u{03B1}\u{03BD}\u{03B5}", 2, 1, None),
Among("\u{03BF}\u{03BD}\u{03C4}\u{03B1}\u{03BD}\u{03B5}", -1, 1, None),
Among("\u{03B9}\u{03BF}\u{03BD}\u{03C4}\u{03B1}\u{03BD}\u{03B5}", 4, 1, None),
Among("\u{03BF}\u{03C4}\u{03B1}\u{03BD}\u{03B5}", -1, 1, None),
Among("\u{03B9}\u{03BF}\u{03C4}\u{03B1}\u{03BD}\u{03B5}", 6, 1, None),
Among("\u{03B1}\u{03B3}\u{03B1}\u{03BD}\u{03B5}", -1, 1, None),
Among("\u{03B7}\u{03BA}\u{03B1}\u{03BD}\u{03B5}", -1, 1, None),
Among("\u{03B7}\u{03B8}\u{03B7}\u{03BA}\u{03B1}\u{03BD}\u{03B5}", 9, 1, None),
];
static A_44: &'static [Among<Context>; 95] = &[
Among("\u{03C0}", -1, 1, None),
Among("\u{03C3}\u{03C0}", 0, 1, None),
Among("\u{03C0}\u{03BF}\u{03BB}\u{03C5}\u{03B4}\u{03B1}\u{03C0}", 0, 1, None),
Among("\u{03B1}\u{03B4}\u{03B1}\u{03C0}", 0, 1, None),
Among("\u{03C7}\u{03B1}\u{03BC}\u{03B7}\u{03BB}\u{03BF}\u{03B4}\u{03B1}\u{03C0}", 0, 1, None),
Among("\u{03C4}\u{03C3}\u{03BF}\u{03C0}", 0, 1, None),
Among("\u{03BA}\u{03BF}\u{03C0}", 0, 1, None),
Among("\u{03C5}\u{03C0}\u{03BF}\u{03BA}\u{03BF}\u{03C0}", 6, 1, None),
Among("\u{03C0}\u{03B5}\u{03C1}\u{03B9}\u{03C4}\u{03C1}", -1, 1, None),
Among("\u{03BF}\u{03C5}\u{03C1}", -1, 1, None),
Among("\u{03B5}\u{03C1}", -1, 1, None),
Among("\u{03B2}\u{03B5}\u{03C4}\u{03B5}\u{03C1}", 10, 1, None),
Among("\u{03B3}\u{03B5}\u{03C1}", 10, 1, None),
Among("\u{03BB}\u{03BF}\u{03C5}\u{03B8}\u{03B7}\u{03C1}", -1, 1, None),
Among("\u{03BA}\u{03BF}\u{03C1}\u{03BC}\u{03BF}\u{03C1}", -1, 1, None),
Among("\u{03C3}", -1, 1, None),
Among("\u{03C3}\u{03B1}\u{03C1}\u{03B1}\u{03BA}\u{03B1}\u{03C4}\u{03C3}", 15, 1, None),
Among("\u{03B8}\u{03C5}\u{03C3}", 15, 1, None),
Among("\u{03B2}\u{03B1}\u{03C3}", 15, 1, None),
Among("\u{03C0}\u{03BF}\u{03BB}\u{03B9}\u{03C3}", 15, 1, None),
| rust | MIT | 1fde09dfa08fb0fb07fbd6570aba8ecc98174edb | 2026-01-04T20:25:20.053159Z | true |
CurrySoftware/rust-stemmers | https://github.com/CurrySoftware/rust-stemmers/blob/1fde09dfa08fb0fb07fbd6570aba8ecc98174edb/src/snowball/algorithms/portuguese.rs | src/snowball/algorithms/portuguese.rs | //! This file was generated automatically by the Snowball to Rust compiler
//! http://snowballstem.org/
#![allow(non_upper_case_globals)]
#![allow(non_snake_case)]
#![allow(unused_variables)]
#![allow(unused_mut)]
use snowball::SnowballEnv;
use snowball::Among;
static A_0: &'static [Among<Context>; 3] = &[
Among("", -1, 3, None),
Among("\u{00E3}", 0, 1, None),
Among("\u{00F5}", 0, 2, None),
];
static A_1: &'static [Among<Context>; 3] = &[
Among("", -1, 3, None),
Among("a~", 0, 1, None),
Among("o~", 0, 2, None),
];
static A_2: &'static [Among<Context>; 4] = &[
Among("ic", -1, -1, None),
Among("ad", -1, -1, None),
Among("os", -1, -1, None),
Among("iv", -1, 1, None),
];
static A_3: &'static [Among<Context>; 3] = &[
Among("ante", -1, 1, None),
Among("avel", -1, 1, None),
Among("\u{00ED}vel", -1, 1, None),
];
static A_4: &'static [Among<Context>; 3] = &[
Among("ic", -1, 1, None),
Among("abil", -1, 1, None),
Among("iv", -1, 1, None),
];
static A_5: &'static [Among<Context>; 45] = &[
Among("ica", -1, 1, None),
Among("\u{00E2}ncia", -1, 1, None),
Among("\u{00EA}ncia", -1, 4, None),
Among("logia", -1, 2, None),
Among("ira", -1, 9, None),
Among("adora", -1, 1, None),
Among("osa", -1, 1, None),
Among("ista", -1, 1, None),
Among("iva", -1, 8, None),
Among("eza", -1, 1, None),
Among("idade", -1, 7, None),
Among("ante", -1, 1, None),
Among("mente", -1, 6, None),
Among("amente", 12, 5, None),
Among("\u{00E1}vel", -1, 1, None),
Among("\u{00ED}vel", -1, 1, None),
Among("ico", -1, 1, None),
Among("ismo", -1, 1, None),
Among("oso", -1, 1, None),
Among("amento", -1, 1, None),
Among("imento", -1, 1, None),
Among("ivo", -1, 8, None),
Among("a\u{00E7}a~o", -1, 1, None),
Among("u\u{00E7}a~o", -1, 3, None),
Among("ador", -1, 1, None),
Among("icas", -1, 1, None),
Among("\u{00EA}ncias", -1, 4, None),
Among("logias", -1, 2, None),
Among("iras", -1, 9, None),
Among("adoras", -1, 1, None),
Among("osas", -1, 1, None),
Among("istas", -1, 1, None),
Among("ivas", -1, 8, None),
Among("ezas", -1, 1, None),
Among("idades", -1, 7, None),
Among("adores", -1, 1, None),
Among("antes", -1, 1, None),
Among("a\u{00E7}o~es", -1, 1, None),
Among("u\u{00E7}o~es", -1, 3, None),
Among("icos", -1, 1, None),
Among("ismos", -1, 1, None),
Among("osos", -1, 1, None),
Among("amentos", -1, 1, None),
Among("imentos", -1, 1, None),
Among("ivos", -1, 8, None),
];
static A_6: &'static [Among<Context>; 120] = &[
Among("ada", -1, 1, None),
Among("ida", -1, 1, None),
Among("ia", -1, 1, None),
Among("aria", 2, 1, None),
Among("eria", 2, 1, None),
Among("iria", 2, 1, None),
Among("ara", -1, 1, None),
Among("era", -1, 1, None),
Among("ira", -1, 1, None),
Among("ava", -1, 1, None),
Among("asse", -1, 1, None),
Among("esse", -1, 1, None),
Among("isse", -1, 1, None),
Among("aste", -1, 1, None),
Among("este", -1, 1, None),
Among("iste", -1, 1, None),
Among("ei", -1, 1, None),
Among("arei", 16, 1, None),
Among("erei", 16, 1, None),
Among("irei", 16, 1, None),
Among("am", -1, 1, None),
Among("iam", 20, 1, None),
Among("ariam", 21, 1, None),
Among("eriam", 21, 1, None),
Among("iriam", 21, 1, None),
Among("aram", 20, 1, None),
Among("eram", 20, 1, None),
Among("iram", 20, 1, None),
Among("avam", 20, 1, None),
Among("em", -1, 1, None),
Among("arem", 29, 1, None),
Among("erem", 29, 1, None),
Among("irem", 29, 1, None),
Among("assem", 29, 1, None),
Among("essem", 29, 1, None),
Among("issem", 29, 1, None),
Among("ado", -1, 1, None),
Among("ido", -1, 1, None),
Among("ando", -1, 1, None),
Among("endo", -1, 1, None),
Among("indo", -1, 1, None),
Among("ara~o", -1, 1, None),
Among("era~o", -1, 1, None),
Among("ira~o", -1, 1, None),
Among("ar", -1, 1, None),
Among("er", -1, 1, None),
Among("ir", -1, 1, None),
Among("as", -1, 1, None),
Among("adas", 47, 1, None),
Among("idas", 47, 1, None),
Among("ias", 47, 1, None),
Among("arias", 50, 1, None),
Among("erias", 50, 1, None),
Among("irias", 50, 1, None),
Among("aras", 47, 1, None),
Among("eras", 47, 1, None),
Among("iras", 47, 1, None),
Among("avas", 47, 1, None),
Among("es", -1, 1, None),
Among("ardes", 58, 1, None),
Among("erdes", 58, 1, None),
Among("irdes", 58, 1, None),
Among("ares", 58, 1, None),
Among("eres", 58, 1, None),
Among("ires", 58, 1, None),
Among("asses", 58, 1, None),
Among("esses", 58, 1, None),
Among("isses", 58, 1, None),
Among("astes", 58, 1, None),
Among("estes", 58, 1, None),
Among("istes", 58, 1, None),
Among("is", -1, 1, None),
Among("ais", 71, 1, None),
Among("eis", 71, 1, None),
Among("areis", 73, 1, None),
Among("ereis", 73, 1, None),
Among("ireis", 73, 1, None),
Among("\u{00E1}reis", 73, 1, None),
Among("\u{00E9}reis", 73, 1, None),
Among("\u{00ED}reis", 73, 1, None),
Among("\u{00E1}sseis", 73, 1, None),
Among("\u{00E9}sseis", 73, 1, None),
Among("\u{00ED}sseis", 73, 1, None),
Among("\u{00E1}veis", 73, 1, None),
Among("\u{00ED}eis", 73, 1, None),
Among("ar\u{00ED}eis", 84, 1, None),
Among("er\u{00ED}eis", 84, 1, None),
Among("ir\u{00ED}eis", 84, 1, None),
Among("ados", -1, 1, None),
Among("idos", -1, 1, None),
Among("amos", -1, 1, None),
Among("\u{00E1}ramos", 90, 1, None),
Among("\u{00E9}ramos", 90, 1, None),
Among("\u{00ED}ramos", 90, 1, None),
Among("\u{00E1}vamos", 90, 1, None),
Among("\u{00ED}amos", 90, 1, None),
Among("ar\u{00ED}amos", 95, 1, None),
Among("er\u{00ED}amos", 95, 1, None),
Among("ir\u{00ED}amos", 95, 1, None),
Among("emos", -1, 1, None),
Among("aremos", 99, 1, None),
Among("eremos", 99, 1, None),
Among("iremos", 99, 1, None),
Among("\u{00E1}ssemos", 99, 1, None),
Among("\u{00EA}ssemos", 99, 1, None),
Among("\u{00ED}ssemos", 99, 1, None),
Among("imos", -1, 1, None),
Among("armos", -1, 1, None),
Among("ermos", -1, 1, None),
Among("irmos", -1, 1, None),
Among("\u{00E1}mos", -1, 1, None),
Among("ar\u{00E1}s", -1, 1, None),
Among("er\u{00E1}s", -1, 1, None),
Among("ir\u{00E1}s", -1, 1, None),
Among("eu", -1, 1, None),
Among("iu", -1, 1, None),
Among("ou", -1, 1, None),
Among("ar\u{00E1}", -1, 1, None),
Among("er\u{00E1}", -1, 1, None),
Among("ir\u{00E1}", -1, 1, None),
];
static A_7: &'static [Among<Context>; 7] = &[
Among("a", -1, 1, None),
Among("i", -1, 1, None),
Among("o", -1, 1, None),
Among("os", -1, 1, None),
Among("\u{00E1}", -1, 1, None),
Among("\u{00ED}", -1, 1, None),
Among("\u{00F3}", -1, 1, None),
];
static A_8: &'static [Among<Context>; 4] = &[
Among("e", -1, 1, None),
Among("\u{00E7}", -1, 2, None),
Among("\u{00E9}", -1, 1, None),
Among("\u{00EA}", -1, 1, None),
];
static G_v: &'static [u8; 20] = &[17, 65, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 19, 12, 2];
#[derive(Clone)]
struct Context {
i_p2: usize,
i_p1: usize,
i_pV: usize,
}
fn r_prelude(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// repeat, line 36
'replab0: loop{
let v_1 = env.cursor;
'lab1: for _ in 0..1 {
// (, line 36
// [, line 37
env.bra = env.cursor;
// substring, line 37
among_var = env.find_among(A_0, context);
if among_var == 0 {
break 'lab1;
}
// ], line 37
env.ket = env.cursor;
if among_var == 0 {
break 'lab1;
} else if among_var == 1 {
// (, line 38
// <-, line 38
if !env.slice_from("a~") {
return false;
}
} else if among_var == 2 {
// (, line 39
// <-, line 39
if !env.slice_from("o~") {
return false;
}
} else if among_var == 3 {
// (, line 40
// next, line 40
if env.cursor >= env.limit {
break 'lab1;
}
env.next_char();
}
continue 'replab0;
}
env.cursor = v_1;
break 'replab0;
}
return true;
}
fn r_mark_regions(env: &mut SnowballEnv, context: &mut Context) -> bool {
// (, line 44
context.i_pV = env.limit;
context.i_p1 = env.limit;
context.i_p2 = env.limit;
// do, line 50
let v_1 = env.cursor;
'lab0: loop {
// (, line 50
// or, line 52
'lab1: loop {
let v_2 = env.cursor;
'lab2: loop {
// (, line 51
if !env.in_grouping(G_v, 97, 250) {
break 'lab2;
}
// or, line 51
'lab3: loop {
let v_3 = env.cursor;
'lab4: loop {
// (, line 51
if !env.out_grouping(G_v, 97, 250) {
break 'lab4;
}
// gopast, line 51
'golab5: loop {
'lab6: loop {
if !env.in_grouping(G_v, 97, 250) {
break 'lab6;
}
break 'golab5;
}
if env.cursor >= env.limit {
break 'lab4;
}
env.next_char();
}
break 'lab3;
}
env.cursor = v_3;
// (, line 51
if !env.in_grouping(G_v, 97, 250) {
break 'lab2;
}
// gopast, line 51
'golab7: loop {
'lab8: loop {
if !env.out_grouping(G_v, 97, 250) {
break 'lab8;
}
break 'golab7;
}
if env.cursor >= env.limit {
break 'lab2;
}
env.next_char();
}
break 'lab3;
}
break 'lab1;
}
env.cursor = v_2;
// (, line 53
if !env.out_grouping(G_v, 97, 250) {
break 'lab0;
}
// or, line 53
'lab9: loop {
let v_6 = env.cursor;
'lab10: loop {
// (, line 53
if !env.out_grouping(G_v, 97, 250) {
break 'lab10;
}
// gopast, line 53
'golab11: loop {
'lab12: loop {
if !env.in_grouping(G_v, 97, 250) {
break 'lab12;
}
break 'golab11;
}
if env.cursor >= env.limit {
break 'lab10;
}
env.next_char();
}
break 'lab9;
}
env.cursor = v_6;
// (, line 53
if !env.in_grouping(G_v, 97, 250) {
break 'lab0;
}
// next, line 53
if env.cursor >= env.limit {
break 'lab0;
}
env.next_char();
break 'lab9;
}
break 'lab1;
}
// setmark pV, line 54
context.i_pV = env.cursor;
break 'lab0;
}
env.cursor = v_1;
// do, line 56
let v_8 = env.cursor;
'lab13: loop {
// (, line 56
// gopast, line 57
'golab14: loop {
'lab15: loop {
if !env.in_grouping(G_v, 97, 250) {
break 'lab15;
}
break 'golab14;
}
if env.cursor >= env.limit {
break 'lab13;
}
env.next_char();
}
// gopast, line 57
'golab16: loop {
'lab17: loop {
if !env.out_grouping(G_v, 97, 250) {
break 'lab17;
}
break 'golab16;
}
if env.cursor >= env.limit {
break 'lab13;
}
env.next_char();
}
// setmark p1, line 57
context.i_p1 = env.cursor;
// gopast, line 58
'golab18: loop {
'lab19: loop {
if !env.in_grouping(G_v, 97, 250) {
break 'lab19;
}
break 'golab18;
}
if env.cursor >= env.limit {
break 'lab13;
}
env.next_char();
}
// gopast, line 58
'golab20: loop {
'lab21: loop {
if !env.out_grouping(G_v, 97, 250) {
break 'lab21;
}
break 'golab20;
}
if env.cursor >= env.limit {
break 'lab13;
}
env.next_char();
}
// setmark p2, line 58
context.i_p2 = env.cursor;
break 'lab13;
}
env.cursor = v_8;
return true;
}
fn r_postlude(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// repeat, line 62
'replab0: loop{
let v_1 = env.cursor;
'lab1: for _ in 0..1 {
// (, line 62
// [, line 63
env.bra = env.cursor;
// substring, line 63
among_var = env.find_among(A_1, context);
if among_var == 0 {
break 'lab1;
}
// ], line 63
env.ket = env.cursor;
if among_var == 0 {
break 'lab1;
} else if among_var == 1 {
// (, line 64
// <-, line 64
if !env.slice_from("\u{00E3}") {
return false;
}
} else if among_var == 2 {
// (, line 65
// <-, line 65
if !env.slice_from("\u{00F5}") {
return false;
}
} else if among_var == 3 {
// (, line 66
// next, line 66
if env.cursor >= env.limit {
break 'lab1;
}
env.next_char();
}
continue 'replab0;
}
env.cursor = v_1;
break 'replab0;
}
return true;
}
fn r_RV(env: &mut SnowballEnv, context: &mut Context) -> bool {
if !(context.i_pV <= env.cursor){
return false;
}
return true;
}
fn r_R1(env: &mut SnowballEnv, context: &mut Context) -> bool {
if !(context.i_p1 <= env.cursor){
return false;
}
return true;
}
fn r_R2(env: &mut SnowballEnv, context: &mut Context) -> bool {
if !(context.i_p2 <= env.cursor){
return false;
}
return true;
}
fn r_standard_suffix(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 76
// [, line 77
env.ket = env.cursor;
// substring, line 77
among_var = env.find_among_b(A_5, context);
if among_var == 0 {
return false;
}
// ], line 77
env.bra = env.cursor;
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 92
// call R2, line 93
if !r_R2(env, context) {
return false;
}
// delete, line 93
if !env.slice_del() {
return false;
}
} else if among_var == 2 {
// (, line 97
// call R2, line 98
if !r_R2(env, context) {
return false;
}
// <-, line 98
if !env.slice_from("log") {
return false;
}
} else if among_var == 3 {
// (, line 101
// call R2, line 102
if !r_R2(env, context) {
return false;
}
// <-, line 102
if !env.slice_from("u") {
return false;
}
} else if among_var == 4 {
// (, line 105
// call R2, line 106
if !r_R2(env, context) {
return false;
}
// <-, line 106
if !env.slice_from("ente") {
return false;
}
} else if among_var == 5 {
// (, line 109
// call R1, line 110
if !r_R1(env, context) {
return false;
}
// delete, line 110
if !env.slice_del() {
return false;
}
// try, line 111
let v_1 = env.limit - env.cursor;
'lab0: loop {
// (, line 111
// [, line 112
env.ket = env.cursor;
// substring, line 112
among_var = env.find_among_b(A_2, context);
if among_var == 0 {
env.cursor = env.limit - v_1;
break 'lab0;
}
// ], line 112
env.bra = env.cursor;
// call R2, line 112
if !r_R2(env, context) {
env.cursor = env.limit - v_1;
break 'lab0;
}
// delete, line 112
if !env.slice_del() {
return false;
}
if among_var == 0 {
env.cursor = env.limit - v_1;
break 'lab0;
} else if among_var == 1 {
// (, line 113
// [, line 113
env.ket = env.cursor;
// literal, line 113
if !env.eq_s_b(&"at") {
env.cursor = env.limit - v_1;
break 'lab0;
}
// ], line 113
env.bra = env.cursor;
// call R2, line 113
if !r_R2(env, context) {
env.cursor = env.limit - v_1;
break 'lab0;
}
// delete, line 113
if !env.slice_del() {
return false;
}
}
break 'lab0;
}
} else if among_var == 6 {
// (, line 121
// call R2, line 122
if !r_R2(env, context) {
return false;
}
// delete, line 122
if !env.slice_del() {
return false;
}
// try, line 123
let v_2 = env.limit - env.cursor;
'lab1: loop {
// (, line 123
// [, line 124
env.ket = env.cursor;
// substring, line 124
among_var = env.find_among_b(A_3, context);
if among_var == 0 {
env.cursor = env.limit - v_2;
break 'lab1;
}
// ], line 124
env.bra = env.cursor;
if among_var == 0 {
env.cursor = env.limit - v_2;
break 'lab1;
} else if among_var == 1 {
// (, line 127
// call R2, line 127
if !r_R2(env, context) {
env.cursor = env.limit - v_2;
break 'lab1;
}
// delete, line 127
if !env.slice_del() {
return false;
}
}
break 'lab1;
}
} else if among_var == 7 {
// (, line 133
// call R2, line 134
if !r_R2(env, context) {
return false;
}
// delete, line 134
if !env.slice_del() {
return false;
}
// try, line 135
let v_3 = env.limit - env.cursor;
'lab2: loop {
// (, line 135
// [, line 136
env.ket = env.cursor;
// substring, line 136
among_var = env.find_among_b(A_4, context);
if among_var == 0 {
env.cursor = env.limit - v_3;
break 'lab2;
}
// ], line 136
env.bra = env.cursor;
if among_var == 0 {
env.cursor = env.limit - v_3;
break 'lab2;
} else if among_var == 1 {
// (, line 139
// call R2, line 139
if !r_R2(env, context) {
env.cursor = env.limit - v_3;
break 'lab2;
}
// delete, line 139
if !env.slice_del() {
return false;
}
}
break 'lab2;
}
} else if among_var == 8 {
// (, line 145
// call R2, line 146
if !r_R2(env, context) {
return false;
}
// delete, line 146
if !env.slice_del() {
return false;
}
// try, line 147
let v_4 = env.limit - env.cursor;
'lab3: loop {
// (, line 147
// [, line 148
env.ket = env.cursor;
// literal, line 148
if !env.eq_s_b(&"at") {
env.cursor = env.limit - v_4;
break 'lab3;
}
// ], line 148
env.bra = env.cursor;
// call R2, line 148
if !r_R2(env, context) {
env.cursor = env.limit - v_4;
break 'lab3;
}
// delete, line 148
if !env.slice_del() {
return false;
}
break 'lab3;
}
} else if among_var == 9 {
// (, line 152
// call RV, line 153
if !r_RV(env, context) {
return false;
}
// literal, line 153
if !env.eq_s_b(&"e") {
return false;
}
// <-, line 154
if !env.slice_from("ir") {
return false;
}
}
return true;
}
fn r_verb_suffix(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// setlimit, line 159
let v_1 = env.limit - env.cursor;
// tomark, line 159
if env.cursor < context.i_pV {
return false;
}
env.cursor = context.i_pV;
let v_2 = env.limit_backward;
env.limit_backward = env.cursor;
env.cursor = env.limit - v_1;
// (, line 159
// [, line 160
env.ket = env.cursor;
// substring, line 160
among_var = env.find_among_b(A_6, context);
if among_var == 0 {
env.limit_backward = v_2;
return false;
}
// ], line 160
env.bra = env.cursor;
if among_var == 0 {
env.limit_backward = v_2;
return false;
} else if among_var == 1 {
// (, line 179
// delete, line 179
if !env.slice_del() {
return false;
}
}
env.limit_backward = v_2;
return true;
}
fn r_residual_suffix(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 183
// [, line 184
env.ket = env.cursor;
// substring, line 184
among_var = env.find_among_b(A_7, context);
if among_var == 0 {
return false;
}
// ], line 184
env.bra = env.cursor;
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 187
// call RV, line 187
if !r_RV(env, context) {
return false;
}
// delete, line 187
if !env.slice_del() {
return false;
}
}
return true;
}
fn r_residual_form(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 191
// [, line 192
env.ket = env.cursor;
// substring, line 192
among_var = env.find_among_b(A_8, context);
if among_var == 0 {
return false;
}
// ], line 192
env.bra = env.cursor;
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 194
// call RV, line 194
if !r_RV(env, context) {
return false;
}
// delete, line 194
if !env.slice_del() {
return false;
}
// [, line 194
env.ket = env.cursor;
// or, line 194
'lab0: loop {
let v_1 = env.limit - env.cursor;
'lab1: loop {
// (, line 194
// literal, line 194
if !env.eq_s_b(&"u") {
break 'lab1;
}
// ], line 194
env.bra = env.cursor;
// test, line 194
let v_2 = env.limit - env.cursor;
// literal, line 194
if !env.eq_s_b(&"g") {
break 'lab1;
}
env.cursor = env.limit - v_2;
break 'lab0;
}
env.cursor = env.limit - v_1;
// (, line 195
// literal, line 195
if !env.eq_s_b(&"i") {
return false;
}
// ], line 195
env.bra = env.cursor;
// test, line 195
let v_3 = env.limit - env.cursor;
// literal, line 195
if !env.eq_s_b(&"c") {
return false;
}
env.cursor = env.limit - v_3;
break 'lab0;
}
// call RV, line 195
if !r_RV(env, context) {
return false;
}
// delete, line 195
if !env.slice_del() {
return false;
}
} else if among_var == 2 {
// (, line 196
// <-, line 196
if !env.slice_from("c") {
return false;
}
}
return true;
}
pub fn stem(env: &mut SnowballEnv) -> bool {
let mut context = &mut Context {
i_p2: 0,
i_p1: 0,
i_pV: 0,
};
// (, line 201
// do, line 202
let v_1 = env.cursor;
'lab0: loop {
// call prelude, line 202
if !r_prelude(env, context) {
break 'lab0;
}
break 'lab0;
}
env.cursor = v_1;
// do, line 203
let v_2 = env.cursor;
'lab1: loop {
// call mark_regions, line 203
if !r_mark_regions(env, context) {
break 'lab1;
}
break 'lab1;
}
env.cursor = v_2;
// backwards, line 204
env.limit_backward = env.cursor;
env.cursor = env.limit;
// (, line 204
// do, line 205
let v_3 = env.limit - env.cursor;
'lab2: loop {
// (, line 205
// or, line 209
'lab3: loop {
let v_4 = env.limit - env.cursor;
'lab4: loop {
// (, line 206
// and, line 207
let v_5 = env.limit - env.cursor;
// (, line 206
// or, line 206
'lab5: loop {
let v_6 = env.limit - env.cursor;
'lab6: loop {
// call standard_suffix, line 206
if !r_standard_suffix(env, context) {
break 'lab6;
}
break 'lab5;
}
env.cursor = env.limit - v_6;
// call verb_suffix, line 206
if !r_verb_suffix(env, context) {
break 'lab4;
}
break 'lab5;
}
env.cursor = env.limit - v_5;
// do, line 207
let v_7 = env.limit - env.cursor;
'lab7: loop {
// (, line 207
// [, line 207
env.ket = env.cursor;
// literal, line 207
if !env.eq_s_b(&"i") {
break 'lab7;
}
// ], line 207
env.bra = env.cursor;
// test, line 207
let v_8 = env.limit - env.cursor;
// literal, line 207
if !env.eq_s_b(&"c") {
break 'lab7;
}
env.cursor = env.limit - v_8;
// call RV, line 207
if !r_RV(env, context) {
break 'lab7;
}
// delete, line 207
if !env.slice_del() {
return false;
}
break 'lab7;
}
env.cursor = env.limit - v_7;
break 'lab3;
}
env.cursor = env.limit - v_4;
// call residual_suffix, line 209
if !r_residual_suffix(env, context) {
break 'lab2;
}
break 'lab3;
}
break 'lab2;
}
env.cursor = env.limit - v_3;
// do, line 211
let v_9 = env.limit - env.cursor;
'lab8: loop {
// call residual_form, line 211
if !r_residual_form(env, context) {
break 'lab8;
}
break 'lab8;
}
env.cursor = env.limit - v_9;
env.cursor = env.limit_backward;
// do, line 213
let v_10 = env.cursor;
'lab9: loop {
// call postlude, line 213
if !r_postlude(env, context) {
break 'lab9;
}
break 'lab9;
}
env.cursor = v_10;
return true;
}
| rust | MIT | 1fde09dfa08fb0fb07fbd6570aba8ecc98174edb | 2026-01-04T20:25:20.053159Z | false |
CurrySoftware/rust-stemmers | https://github.com/CurrySoftware/rust-stemmers/blob/1fde09dfa08fb0fb07fbd6570aba8ecc98174edb/src/snowball/algorithms/finnish.rs | src/snowball/algorithms/finnish.rs | //! This file was generated automatically by the Snowball to Rust compiler
//! http://snowballstem.org/
#![allow(non_upper_case_globals)]
#![allow(non_snake_case)]
#![allow(unused_variables)]
#![allow(unused_mut)]
use snowball::SnowballEnv;
use snowball::Among;
static A_0: &'static [Among<Context>; 10] = &[
Among("pa", -1, 1, None),
Among("sti", -1, 2, None),
Among("kaan", -1, 1, None),
Among("han", -1, 1, None),
Among("kin", -1, 1, None),
Among("h\u{00E4}n", -1, 1, None),
Among("k\u{00E4}\u{00E4}n", -1, 1, None),
Among("ko", -1, 1, None),
Among("p\u{00E4}", -1, 1, None),
Among("k\u{00F6}", -1, 1, None),
];
static A_1: &'static [Among<Context>; 6] = &[
Among("lla", -1, -1, None),
Among("na", -1, -1, None),
Among("ssa", -1, -1, None),
Among("ta", -1, -1, None),
Among("lta", 3, -1, None),
Among("sta", 3, -1, None),
];
static A_2: &'static [Among<Context>; 6] = &[
Among("ll\u{00E4}", -1, -1, None),
Among("n\u{00E4}", -1, -1, None),
Among("ss\u{00E4}", -1, -1, None),
Among("t\u{00E4}", -1, -1, None),
Among("lt\u{00E4}", 3, -1, None),
Among("st\u{00E4}", 3, -1, None),
];
static A_3: &'static [Among<Context>; 2] = &[
Among("lle", -1, -1, None),
Among("ine", -1, -1, None),
];
static A_4: &'static [Among<Context>; 9] = &[
Among("nsa", -1, 3, None),
Among("mme", -1, 3, None),
Among("nne", -1, 3, None),
Among("ni", -1, 2, None),
Among("si", -1, 1, None),
Among("an", -1, 4, None),
Among("en", -1, 6, None),
Among("\u{00E4}n", -1, 5, None),
Among("ns\u{00E4}", -1, 3, None),
];
static A_5: &'static [Among<Context>; 7] = &[
Among("aa", -1, -1, None),
Among("ee", -1, -1, None),
Among("ii", -1, -1, None),
Among("oo", -1, -1, None),
Among("uu", -1, -1, None),
Among("\u{00E4}\u{00E4}", -1, -1, None),
Among("\u{00F6}\u{00F6}", -1, -1, None),
];
static A_6: &'static [Among<Context>; 30] = &[
Among("a", -1, 8, None),
Among("lla", 0, -1, None),
Among("na", 0, -1, None),
Among("ssa", 0, -1, None),
Among("ta", 0, -1, None),
Among("lta", 4, -1, None),
Among("sta", 4, -1, None),
Among("tta", 4, 9, None),
Among("lle", -1, -1, None),
Among("ine", -1, -1, None),
Among("ksi", -1, -1, None),
Among("n", -1, 7, None),
Among("han", 11, 1, None),
Among("den", 11, -1, Some(&r_VI)),
Among("seen", 11, -1, Some(&r_LONG)),
Among("hen", 11, 2, None),
Among("tten", 11, -1, Some(&r_VI)),
Among("hin", 11, 3, None),
Among("siin", 11, -1, Some(&r_VI)),
Among("hon", 11, 4, None),
Among("h\u{00E4}n", 11, 5, None),
Among("h\u{00F6}n", 11, 6, None),
Among("\u{00E4}", -1, 8, None),
Among("ll\u{00E4}", 22, -1, None),
Among("n\u{00E4}", 22, -1, None),
Among("ss\u{00E4}", 22, -1, None),
Among("t\u{00E4}", 22, -1, None),
Among("lt\u{00E4}", 26, -1, None),
Among("st\u{00E4}", 26, -1, None),
Among("tt\u{00E4}", 26, 9, None),
];
static A_7: &'static [Among<Context>; 14] = &[
Among("eja", -1, -1, None),
Among("mma", -1, 1, None),
Among("imma", 1, -1, None),
Among("mpa", -1, 1, None),
Among("impa", 3, -1, None),
Among("mmi", -1, 1, None),
Among("immi", 5, -1, None),
Among("mpi", -1, 1, None),
Among("impi", 7, -1, None),
Among("ej\u{00E4}", -1, -1, None),
Among("mm\u{00E4}", -1, 1, None),
Among("imm\u{00E4}", 10, -1, None),
Among("mp\u{00E4}", -1, 1, None),
Among("imp\u{00E4}", 12, -1, None),
];
static A_8: &'static [Among<Context>; 2] = &[
Among("i", -1, -1, None),
Among("j", -1, -1, None),
];
static A_9: &'static [Among<Context>; 2] = &[
Among("mma", -1, 1, None),
Among("imma", 0, -1, None),
];
static G_AEI: &'static [u8; 17] = &[17, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8];
static G_V1: &'static [u8; 19] = &[17, 65, 16, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 32];
static G_V2: &'static [u8; 19] = &[17, 65, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 32];
static G_particle_end: &'static [u8; 19] = &[17, 97, 24, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 32];
#[derive(Clone)]
struct Context {
b_ending_removed: bool,
S_x: String,
i_p2: usize,
i_p1: usize,
}
fn r_mark_regions(env: &mut SnowballEnv, context: &mut Context) -> bool {
// (, line 40
context.i_p1 = env.limit;
context.i_p2 = env.limit;
// goto, line 45
'golab0: loop {
let v_1 = env.cursor;
'lab1: loop {
if !env.in_grouping(G_V1, 97, 246) {
break 'lab1;
}
env.cursor = v_1;
break 'golab0;
}
env.cursor = v_1;
if env.cursor >= env.limit {
return false;
}
env.next_char();
}
// gopast, line 45
'golab2: loop {
'lab3: loop {
if !env.out_grouping(G_V1, 97, 246) {
break 'lab3;
}
break 'golab2;
}
if env.cursor >= env.limit {
return false;
}
env.next_char();
}
// setmark p1, line 45
context.i_p1 = env.cursor;
// goto, line 46
'golab4: loop {
let v_3 = env.cursor;
'lab5: loop {
if !env.in_grouping(G_V1, 97, 246) {
break 'lab5;
}
env.cursor = v_3;
break 'golab4;
}
env.cursor = v_3;
if env.cursor >= env.limit {
return false;
}
env.next_char();
}
// gopast, line 46
'golab6: loop {
'lab7: loop {
if !env.out_grouping(G_V1, 97, 246) {
break 'lab7;
}
break 'golab6;
}
if env.cursor >= env.limit {
return false;
}
env.next_char();
}
// setmark p2, line 46
context.i_p2 = env.cursor;
return true;
}
fn r_R2(env: &mut SnowballEnv, context: &mut Context) -> bool {
if !(context.i_p2 <= env.cursor){
return false;
}
return true;
}
fn r_particle_etc(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 53
// setlimit, line 54
let v_1 = env.limit - env.cursor;
// tomark, line 54
if env.cursor < context.i_p1 {
return false;
}
env.cursor = context.i_p1;
let v_2 = env.limit_backward;
env.limit_backward = env.cursor;
env.cursor = env.limit - v_1;
// (, line 54
// [, line 54
env.ket = env.cursor;
// substring, line 54
among_var = env.find_among_b(A_0, context);
if among_var == 0 {
env.limit_backward = v_2;
return false;
}
// ], line 54
env.bra = env.cursor;
env.limit_backward = v_2;
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 61
if !env.in_grouping_b(G_particle_end, 97, 246) {
return false;
}
} else if among_var == 2 {
// (, line 63
// call R2, line 63
if !r_R2(env, context) {
return false;
}
}
// delete, line 65
if !env.slice_del() {
return false;
}
return true;
}
fn r_possessive(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 67
// setlimit, line 68
let v_1 = env.limit - env.cursor;
// tomark, line 68
if env.cursor < context.i_p1 {
return false;
}
env.cursor = context.i_p1;
let v_2 = env.limit_backward;
env.limit_backward = env.cursor;
env.cursor = env.limit - v_1;
// (, line 68
// [, line 68
env.ket = env.cursor;
// substring, line 68
among_var = env.find_among_b(A_4, context);
if among_var == 0 {
env.limit_backward = v_2;
return false;
}
// ], line 68
env.bra = env.cursor;
env.limit_backward = v_2;
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 71
// not, line 71
let v_3 = env.limit - env.cursor;
'lab0: loop {
// literal, line 71
if !env.eq_s_b(&"k") {
break 'lab0;
}
return false;
}
env.cursor = env.limit - v_3;
// delete, line 71
if !env.slice_del() {
return false;
}
} else if among_var == 2 {
// (, line 73
// delete, line 73
if !env.slice_del() {
return false;
}
// [, line 73
env.ket = env.cursor;
// literal, line 73
if !env.eq_s_b(&"kse") {
return false;
}
// ], line 73
env.bra = env.cursor;
// <-, line 73
if !env.slice_from("ksi") {
return false;
}
} else if among_var == 3 {
// (, line 77
// delete, line 77
if !env.slice_del() {
return false;
}
} else if among_var == 4 {
// (, line 80
// among, line 80
if env.find_among_b(A_1, context) == 0 {
return false;
}
// delete, line 80
if !env.slice_del() {
return false;
}
} else if among_var == 5 {
// (, line 82
// among, line 82
if env.find_among_b(A_2, context) == 0 {
return false;
}
// delete, line 83
if !env.slice_del() {
return false;
}
} else if among_var == 6 {
// (, line 85
// among, line 85
if env.find_among_b(A_3, context) == 0 {
return false;
}
// delete, line 85
if !env.slice_del() {
return false;
}
}
return true;
}
fn r_LONG(env: &mut SnowballEnv, context: &mut Context) -> bool {
// among, line 90
if env.find_among_b(A_5, context) == 0 {
return false;
}
return true;
}
fn r_VI(env: &mut SnowballEnv, context: &mut Context) -> bool {
// (, line 92
// literal, line 92
if !env.eq_s_b(&"i") {
return false;
}
if !env.in_grouping_b(G_V2, 97, 246) {
return false;
}
return true;
}
fn r_case_ending(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 94
// setlimit, line 95
let v_1 = env.limit - env.cursor;
// tomark, line 95
if env.cursor < context.i_p1 {
return false;
}
env.cursor = context.i_p1;
let v_2 = env.limit_backward;
env.limit_backward = env.cursor;
env.cursor = env.limit - v_1;
// (, line 95
// [, line 95
env.ket = env.cursor;
// substring, line 95
among_var = env.find_among_b(A_6, context);
if among_var == 0 {
env.limit_backward = v_2;
return false;
}
// ], line 95
env.bra = env.cursor;
env.limit_backward = v_2;
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 97
// literal, line 97
if !env.eq_s_b(&"a") {
return false;
}
} else if among_var == 2 {
// (, line 98
// literal, line 98
if !env.eq_s_b(&"e") {
return false;
}
} else if among_var == 3 {
// (, line 99
// literal, line 99
if !env.eq_s_b(&"i") {
return false;
}
} else if among_var == 4 {
// (, line 100
// literal, line 100
if !env.eq_s_b(&"o") {
return false;
}
} else if among_var == 5 {
// (, line 101
// literal, line 101
if !env.eq_s_b(&"\u{00E4}") {
return false;
}
} else if among_var == 6 {
// (, line 102
// literal, line 102
if !env.eq_s_b(&"\u{00F6}") {
return false;
}
} else if among_var == 7 {
// (, line 110
// try, line 110
let v_3 = env.limit - env.cursor;
'lab0: loop {
// (, line 110
// and, line 112
let v_4 = env.limit - env.cursor;
// or, line 111
'lab1: loop {
let v_5 = env.limit - env.cursor;
'lab2: loop {
// call LONG, line 110
if !r_LONG(env, context) {
break 'lab2;
}
break 'lab1;
}
env.cursor = env.limit - v_5;
// literal, line 111
if !env.eq_s_b(&"ie") {
env.cursor = env.limit - v_3;
break 'lab0;
}
break 'lab1;
}
env.cursor = env.limit - v_4;
// next, line 112
if env.cursor <= env.limit_backward {
env.cursor = env.limit - v_3;
break 'lab0;
}
env.previous_char();
// ], line 112
env.bra = env.cursor;
break 'lab0;
}
} else if among_var == 8 {
// (, line 118
if !env.in_grouping_b(G_V1, 97, 246) {
return false;
}
if !env.out_grouping_b(G_V1, 97, 246) {
return false;
}
} else if among_var == 9 {
// (, line 120
// literal, line 120
if !env.eq_s_b(&"e") {
return false;
}
}
// delete, line 137
if !env.slice_del() {
return false;
}
// set ending_removed, line 138
context.b_ending_removed = true;
return true;
}
fn r_other_endings(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 140
// setlimit, line 141
let v_1 = env.limit - env.cursor;
// tomark, line 141
if env.cursor < context.i_p2 {
return false;
}
env.cursor = context.i_p2;
let v_2 = env.limit_backward;
env.limit_backward = env.cursor;
env.cursor = env.limit - v_1;
// (, line 141
// [, line 141
env.ket = env.cursor;
// substring, line 141
among_var = env.find_among_b(A_7, context);
if among_var == 0 {
env.limit_backward = v_2;
return false;
}
// ], line 141
env.bra = env.cursor;
env.limit_backward = v_2;
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 145
// not, line 145
let v_3 = env.limit - env.cursor;
'lab0: loop {
// literal, line 145
if !env.eq_s_b(&"po") {
break 'lab0;
}
return false;
}
env.cursor = env.limit - v_3;
}
// delete, line 150
if !env.slice_del() {
return false;
}
return true;
}
fn r_i_plural(env: &mut SnowballEnv, context: &mut Context) -> bool {
// (, line 152
// setlimit, line 153
let v_1 = env.limit - env.cursor;
// tomark, line 153
if env.cursor < context.i_p1 {
return false;
}
env.cursor = context.i_p1;
let v_2 = env.limit_backward;
env.limit_backward = env.cursor;
env.cursor = env.limit - v_1;
// (, line 153
// [, line 153
env.ket = env.cursor;
// substring, line 153
if env.find_among_b(A_8, context) == 0 {
env.limit_backward = v_2;
return false;
}
// ], line 153
env.bra = env.cursor;
env.limit_backward = v_2;
// delete, line 157
if !env.slice_del() {
return false;
}
return true;
}
fn r_t_plural(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 159
// setlimit, line 160
let v_1 = env.limit - env.cursor;
// tomark, line 160
if env.cursor < context.i_p1 {
return false;
}
env.cursor = context.i_p1;
let v_2 = env.limit_backward;
env.limit_backward = env.cursor;
env.cursor = env.limit - v_1;
// (, line 160
// [, line 161
env.ket = env.cursor;
// literal, line 161
if !env.eq_s_b(&"t") {
env.limit_backward = v_2;
return false;
}
// ], line 161
env.bra = env.cursor;
// test, line 161
let v_3 = env.limit - env.cursor;
if !env.in_grouping_b(G_V1, 97, 246) {
env.limit_backward = v_2;
return false;
}
env.cursor = env.limit - v_3;
// delete, line 162
if !env.slice_del() {
return false;
}
env.limit_backward = v_2;
// setlimit, line 164
let v_4 = env.limit - env.cursor;
// tomark, line 164
if env.cursor < context.i_p2 {
return false;
}
env.cursor = context.i_p2;
let v_5 = env.limit_backward;
env.limit_backward = env.cursor;
env.cursor = env.limit - v_4;
// (, line 164
// [, line 164
env.ket = env.cursor;
// substring, line 164
among_var = env.find_among_b(A_9, context);
if among_var == 0 {
env.limit_backward = v_5;
return false;
}
// ], line 164
env.bra = env.cursor;
env.limit_backward = v_5;
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 166
// not, line 166
let v_6 = env.limit - env.cursor;
'lab0: loop {
// literal, line 166
if !env.eq_s_b(&"po") {
break 'lab0;
}
return false;
}
env.cursor = env.limit - v_6;
}
// delete, line 169
if !env.slice_del() {
return false;
}
return true;
}
fn r_tidy(env: &mut SnowballEnv, context: &mut Context) -> bool {
// (, line 171
// setlimit, line 172
let v_1 = env.limit - env.cursor;
// tomark, line 172
if env.cursor < context.i_p1 {
return false;
}
env.cursor = context.i_p1;
let v_2 = env.limit_backward;
env.limit_backward = env.cursor;
env.cursor = env.limit - v_1;
// (, line 172
// do, line 173
let v_3 = env.limit - env.cursor;
'lab0: loop {
// (, line 173
// and, line 173
let v_4 = env.limit - env.cursor;
// call LONG, line 173
if !r_LONG(env, context) {
break 'lab0;
}
env.cursor = env.limit - v_4;
// (, line 173
// [, line 173
env.ket = env.cursor;
// next, line 173
if env.cursor <= env.limit_backward {
break 'lab0;
}
env.previous_char();
// ], line 173
env.bra = env.cursor;
// delete, line 173
if !env.slice_del() {
return false;
}
break 'lab0;
}
env.cursor = env.limit - v_3;
// do, line 174
let v_5 = env.limit - env.cursor;
'lab1: loop {
// (, line 174
// [, line 174
env.ket = env.cursor;
if !env.in_grouping_b(G_AEI, 97, 228) {
break 'lab1;
}
// ], line 174
env.bra = env.cursor;
if !env.out_grouping_b(G_V1, 97, 246) {
break 'lab1;
}
// delete, line 174
if !env.slice_del() {
return false;
}
break 'lab1;
}
env.cursor = env.limit - v_5;
// do, line 175
let v_6 = env.limit - env.cursor;
'lab2: loop {
// (, line 175
// [, line 175
env.ket = env.cursor;
// literal, line 175
if !env.eq_s_b(&"j") {
break 'lab2;
}
// ], line 175
env.bra = env.cursor;
// or, line 175
'lab3: loop {
let v_7 = env.limit - env.cursor;
'lab4: loop {
// literal, line 175
if !env.eq_s_b(&"o") {
break 'lab4;
}
break 'lab3;
}
env.cursor = env.limit - v_7;
// literal, line 175
if !env.eq_s_b(&"u") {
break 'lab2;
}
break 'lab3;
}
// delete, line 175
if !env.slice_del() {
return false;
}
break 'lab2;
}
env.cursor = env.limit - v_6;
// do, line 176
let v_8 = env.limit - env.cursor;
'lab5: loop {
// (, line 176
// [, line 176
env.ket = env.cursor;
// literal, line 176
if !env.eq_s_b(&"o") {
break 'lab5;
}
// ], line 176
env.bra = env.cursor;
// literal, line 176
if !env.eq_s_b(&"j") {
break 'lab5;
}
// delete, line 176
if !env.slice_del() {
return false;
}
break 'lab5;
}
env.cursor = env.limit - v_8;
env.limit_backward = v_2;
// goto, line 178
'golab6: loop {
let v_9 = env.limit - env.cursor;
'lab7: loop {
if !env.out_grouping_b(G_V1, 97, 246) {
break 'lab7;
}
env.cursor = env.limit - v_9;
break 'golab6;
}
env.cursor = env.limit - v_9;
if env.cursor <= env.limit_backward {
return false;
}
env.previous_char();
}
// [, line 178
env.ket = env.cursor;
// next, line 178
if env.cursor <= env.limit_backward {
return false;
}
env.previous_char();
// ], line 178
env.bra = env.cursor;
// -> x, line 178
context.S_x = env.slice_to();
if context.S_x.is_empty() {
return false;
}
// name x, line 178
if !env.eq_s_b(&context.S_x) {
return false;
}
// delete, line 178
if !env.slice_del() {
return false;
}
return true;
}
pub fn stem(env: &mut SnowballEnv) -> bool {
let mut context = &mut Context {
b_ending_removed: false,
S_x: String::new(),
i_p2: 0,
i_p1: 0,
};
// (, line 182
// do, line 184
let v_1 = env.cursor;
'lab0: loop {
// call mark_regions, line 184
if !r_mark_regions(env, context) {
break 'lab0;
}
break 'lab0;
}
env.cursor = v_1;
// unset ending_removed, line 185
context.b_ending_removed = false;
// backwards, line 186
env.limit_backward = env.cursor;
env.cursor = env.limit;
// (, line 186
// do, line 187
let v_2 = env.limit - env.cursor;
'lab1: loop {
// call particle_etc, line 187
if !r_particle_etc(env, context) {
break 'lab1;
}
break 'lab1;
}
env.cursor = env.limit - v_2;
// do, line 188
let v_3 = env.limit - env.cursor;
'lab2: loop {
// call possessive, line 188
if !r_possessive(env, context) {
break 'lab2;
}
break 'lab2;
}
env.cursor = env.limit - v_3;
// do, line 189
let v_4 = env.limit - env.cursor;
'lab3: loop {
// call case_ending, line 189
if !r_case_ending(env, context) {
break 'lab3;
}
break 'lab3;
}
env.cursor = env.limit - v_4;
// do, line 190
let v_5 = env.limit - env.cursor;
'lab4: loop {
// call other_endings, line 190
if !r_other_endings(env, context) {
break 'lab4;
}
break 'lab4;
}
env.cursor = env.limit - v_5;
// or, line 191
'lab5: loop {
let v_6 = env.limit - env.cursor;
'lab6: loop {
// (, line 191
// Boolean test ending_removed, line 191
if !context.b_ending_removed {
break 'lab6;
}
// do, line 191
let v_7 = env.limit - env.cursor;
'lab7: loop {
// call i_plural, line 191
if !r_i_plural(env, context) {
break 'lab7;
}
break 'lab7;
}
env.cursor = env.limit - v_7;
break 'lab5;
}
env.cursor = env.limit - v_6;
// do, line 191
let v_8 = env.limit - env.cursor;
'lab8: loop {
// call t_plural, line 191
if !r_t_plural(env, context) {
break 'lab8;
}
break 'lab8;
}
env.cursor = env.limit - v_8;
break 'lab5;
}
// do, line 192
let v_9 = env.limit - env.cursor;
'lab9: loop {
// call tidy, line 192
if !r_tidy(env, context) {
break 'lab9;
}
break 'lab9;
}
env.cursor = env.limit - v_9;
env.cursor = env.limit_backward;
return true;
}
| rust | MIT | 1fde09dfa08fb0fb07fbd6570aba8ecc98174edb | 2026-01-04T20:25:20.053159Z | false |
CurrySoftware/rust-stemmers | https://github.com/CurrySoftware/rust-stemmers/blob/1fde09dfa08fb0fb07fbd6570aba8ecc98174edb/src/snowball/algorithms/italian.rs | src/snowball/algorithms/italian.rs | //! This file was generated automatically by the Snowball to Rust compiler
//! http://snowballstem.org/
#![allow(non_upper_case_globals)]
#![allow(non_snake_case)]
#![allow(unused_variables)]
#![allow(unused_mut)]
use snowball::SnowballEnv;
use snowball::Among;
static A_0: &'static [Among<Context>; 7] = &[
Among("", -1, 7, None),
Among("qu", 0, 6, None),
Among("\u{00E1}", 0, 1, None),
Among("\u{00E9}", 0, 2, None),
Among("\u{00ED}", 0, 3, None),
Among("\u{00F3}", 0, 4, None),
Among("\u{00FA}", 0, 5, None),
];
static A_1: &'static [Among<Context>; 3] = &[
Among("", -1, 3, None),
Among("I", 0, 1, None),
Among("U", 0, 2, None),
];
static A_2: &'static [Among<Context>; 37] = &[
Among("la", -1, -1, None),
Among("cela", 0, -1, None),
Among("gliela", 0, -1, None),
Among("mela", 0, -1, None),
Among("tela", 0, -1, None),
Among("vela", 0, -1, None),
Among("le", -1, -1, None),
Among("cele", 6, -1, None),
Among("gliele", 6, -1, None),
Among("mele", 6, -1, None),
Among("tele", 6, -1, None),
Among("vele", 6, -1, None),
Among("ne", -1, -1, None),
Among("cene", 12, -1, None),
Among("gliene", 12, -1, None),
Among("mene", 12, -1, None),
Among("sene", 12, -1, None),
Among("tene", 12, -1, None),
Among("vene", 12, -1, None),
Among("ci", -1, -1, None),
Among("li", -1, -1, None),
Among("celi", 20, -1, None),
Among("glieli", 20, -1, None),
Among("meli", 20, -1, None),
Among("teli", 20, -1, None),
Among("veli", 20, -1, None),
Among("gli", 20, -1, None),
Among("mi", -1, -1, None),
Among("si", -1, -1, None),
Among("ti", -1, -1, None),
Among("vi", -1, -1, None),
Among("lo", -1, -1, None),
Among("celo", 31, -1, None),
Among("glielo", 31, -1, None),
Among("melo", 31, -1, None),
Among("telo", 31, -1, None),
Among("velo", 31, -1, None),
];
static A_3: &'static [Among<Context>; 5] = &[
Among("ando", -1, 1, None),
Among("endo", -1, 1, None),
Among("ar", -1, 2, None),
Among("er", -1, 2, None),
Among("ir", -1, 2, None),
];
static A_4: &'static [Among<Context>; 4] = &[
Among("ic", -1, -1, None),
Among("abil", -1, -1, None),
Among("os", -1, -1, None),
Among("iv", -1, 1, None),
];
static A_5: &'static [Among<Context>; 3] = &[
Among("ic", -1, 1, None),
Among("abil", -1, 1, None),
Among("iv", -1, 1, None),
];
static A_6: &'static [Among<Context>; 51] = &[
Among("ica", -1, 1, None),
Among("logia", -1, 3, None),
Among("osa", -1, 1, None),
Among("ista", -1, 1, None),
Among("iva", -1, 9, None),
Among("anza", -1, 1, None),
Among("enza", -1, 5, None),
Among("ice", -1, 1, None),
Among("atrice", 7, 1, None),
Among("iche", -1, 1, None),
Among("logie", -1, 3, None),
Among("abile", -1, 1, None),
Among("ibile", -1, 1, None),
Among("usione", -1, 4, None),
Among("azione", -1, 2, None),
Among("uzione", -1, 4, None),
Among("atore", -1, 2, None),
Among("ose", -1, 1, None),
Among("ante", -1, 1, None),
Among("mente", -1, 1, None),
Among("amente", 19, 7, None),
Among("iste", -1, 1, None),
Among("ive", -1, 9, None),
Among("anze", -1, 1, None),
Among("enze", -1, 5, None),
Among("ici", -1, 1, None),
Among("atrici", 25, 1, None),
Among("ichi", -1, 1, None),
Among("abili", -1, 1, None),
Among("ibili", -1, 1, None),
Among("ismi", -1, 1, None),
Among("usioni", -1, 4, None),
Among("azioni", -1, 2, None),
Among("uzioni", -1, 4, None),
Among("atori", -1, 2, None),
Among("osi", -1, 1, None),
Among("anti", -1, 1, None),
Among("amenti", -1, 6, None),
Among("imenti", -1, 6, None),
Among("isti", -1, 1, None),
Among("ivi", -1, 9, None),
Among("ico", -1, 1, None),
Among("ismo", -1, 1, None),
Among("oso", -1, 1, None),
Among("amento", -1, 6, None),
Among("imento", -1, 6, None),
Among("ivo", -1, 9, None),
Among("it\u{00E0}", -1, 8, None),
Among("ist\u{00E0}", -1, 1, None),
Among("ist\u{00E8}", -1, 1, None),
Among("ist\u{00EC}", -1, 1, None),
];
static A_7: &'static [Among<Context>; 87] = &[
Among("isca", -1, 1, None),
Among("enda", -1, 1, None),
Among("ata", -1, 1, None),
Among("ita", -1, 1, None),
Among("uta", -1, 1, None),
Among("ava", -1, 1, None),
Among("eva", -1, 1, None),
Among("iva", -1, 1, None),
Among("erebbe", -1, 1, None),
Among("irebbe", -1, 1, None),
Among("isce", -1, 1, None),
Among("ende", -1, 1, None),
Among("are", -1, 1, None),
Among("ere", -1, 1, None),
Among("ire", -1, 1, None),
Among("asse", -1, 1, None),
Among("ate", -1, 1, None),
Among("avate", 16, 1, None),
Among("evate", 16, 1, None),
Among("ivate", 16, 1, None),
Among("ete", -1, 1, None),
Among("erete", 20, 1, None),
Among("irete", 20, 1, None),
Among("ite", -1, 1, None),
Among("ereste", -1, 1, None),
Among("ireste", -1, 1, None),
Among("ute", -1, 1, None),
Among("erai", -1, 1, None),
Among("irai", -1, 1, None),
Among("isci", -1, 1, None),
Among("endi", -1, 1, None),
Among("erei", -1, 1, None),
Among("irei", -1, 1, None),
Among("assi", -1, 1, None),
Among("ati", -1, 1, None),
Among("iti", -1, 1, None),
Among("eresti", -1, 1, None),
Among("iresti", -1, 1, None),
Among("uti", -1, 1, None),
Among("avi", -1, 1, None),
Among("evi", -1, 1, None),
Among("ivi", -1, 1, None),
Among("isco", -1, 1, None),
Among("ando", -1, 1, None),
Among("endo", -1, 1, None),
Among("Yamo", -1, 1, None),
Among("iamo", -1, 1, None),
Among("avamo", -1, 1, None),
Among("evamo", -1, 1, None),
Among("ivamo", -1, 1, None),
Among("eremo", -1, 1, None),
Among("iremo", -1, 1, None),
Among("assimo", -1, 1, None),
Among("ammo", -1, 1, None),
Among("emmo", -1, 1, None),
Among("eremmo", 54, 1, None),
Among("iremmo", 54, 1, None),
Among("immo", -1, 1, None),
Among("ano", -1, 1, None),
Among("iscano", 58, 1, None),
Among("avano", 58, 1, None),
Among("evano", 58, 1, None),
Among("ivano", 58, 1, None),
Among("eranno", -1, 1, None),
Among("iranno", -1, 1, None),
Among("ono", -1, 1, None),
Among("iscono", 65, 1, None),
Among("arono", 65, 1, None),
Among("erono", 65, 1, None),
Among("irono", 65, 1, None),
Among("erebbero", -1, 1, None),
Among("irebbero", -1, 1, None),
Among("assero", -1, 1, None),
Among("essero", -1, 1, None),
Among("issero", -1, 1, None),
Among("ato", -1, 1, None),
Among("ito", -1, 1, None),
Among("uto", -1, 1, None),
Among("avo", -1, 1, None),
Among("evo", -1, 1, None),
Among("ivo", -1, 1, None),
Among("ar", -1, 1, None),
Among("ir", -1, 1, None),
Among("er\u{00E0}", -1, 1, None),
Among("ir\u{00E0}", -1, 1, None),
Among("er\u{00F2}", -1, 1, None),
Among("ir\u{00F2}", -1, 1, None),
];
static G_v: &'static [u8; 20] = &[17, 65, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 8, 2, 1];
static G_AEIO: &'static [u8; 19] = &[17, 65, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 8, 2];
static G_CG: &'static [u8; 1] = &[17];
#[derive(Clone)]
struct Context {
i_p2: usize,
i_p1: usize,
i_pV: usize,
}
fn r_prelude(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 33
// test, line 34
let v_1 = env.cursor;
// repeat, line 34
'replab0: loop{
let v_2 = env.cursor;
'lab1: for _ in 0..1 {
// (, line 34
// [, line 35
env.bra = env.cursor;
// substring, line 35
among_var = env.find_among(A_0, context);
if among_var == 0 {
break 'lab1;
}
// ], line 35
env.ket = env.cursor;
if among_var == 0 {
break 'lab1;
} else if among_var == 1 {
// (, line 36
// <-, line 36
if !env.slice_from("\u{00E0}") {
return false;
}
} else if among_var == 2 {
// (, line 37
// <-, line 37
if !env.slice_from("\u{00E8}") {
return false;
}
} else if among_var == 3 {
// (, line 38
// <-, line 38
if !env.slice_from("\u{00EC}") {
return false;
}
} else if among_var == 4 {
// (, line 39
// <-, line 39
if !env.slice_from("\u{00F2}") {
return false;
}
} else if among_var == 5 {
// (, line 40
// <-, line 40
if !env.slice_from("\u{00F9}") {
return false;
}
} else if among_var == 6 {
// (, line 41
// <-, line 41
if !env.slice_from("qU") {
return false;
}
} else if among_var == 7 {
// (, line 42
// next, line 42
if env.cursor >= env.limit {
break 'lab1;
}
env.next_char();
}
continue 'replab0;
}
env.cursor = v_2;
break 'replab0;
}
env.cursor = v_1;
// repeat, line 45
'replab2: loop{
let v_3 = env.cursor;
'lab3: for _ in 0..1 {
// goto, line 45
'golab4: loop {
let v_4 = env.cursor;
'lab5: loop {
// (, line 45
if !env.in_grouping(G_v, 97, 249) {
break 'lab5;
}
// [, line 46
env.bra = env.cursor;
// or, line 46
'lab6: loop {
let v_5 = env.cursor;
'lab7: loop {
// (, line 46
// literal, line 46
if !env.eq_s(&"u") {
break 'lab7;
}
// ], line 46
env.ket = env.cursor;
if !env.in_grouping(G_v, 97, 249) {
break 'lab7;
}
// <-, line 46
if !env.slice_from("U") {
return false;
}
break 'lab6;
}
env.cursor = v_5;
// (, line 47
// literal, line 47
if !env.eq_s(&"i") {
break 'lab5;
}
// ], line 47
env.ket = env.cursor;
if !env.in_grouping(G_v, 97, 249) {
break 'lab5;
}
// <-, line 47
if !env.slice_from("I") {
return false;
}
break 'lab6;
}
env.cursor = v_4;
break 'golab4;
}
env.cursor = v_4;
if env.cursor >= env.limit {
break 'lab3;
}
env.next_char();
}
continue 'replab2;
}
env.cursor = v_3;
break 'replab2;
}
return true;
}
fn r_mark_regions(env: &mut SnowballEnv, context: &mut Context) -> bool {
// (, line 51
context.i_pV = env.limit;
context.i_p1 = env.limit;
context.i_p2 = env.limit;
// do, line 57
let v_1 = env.cursor;
'lab0: loop {
// (, line 57
// or, line 59
'lab1: loop {
let v_2 = env.cursor;
'lab2: loop {
// (, line 58
if !env.in_grouping(G_v, 97, 249) {
break 'lab2;
}
// or, line 58
'lab3: loop {
let v_3 = env.cursor;
'lab4: loop {
// (, line 58
if !env.out_grouping(G_v, 97, 249) {
break 'lab4;
}
// gopast, line 58
'golab5: loop {
'lab6: loop {
if !env.in_grouping(G_v, 97, 249) {
break 'lab6;
}
break 'golab5;
}
if env.cursor >= env.limit {
break 'lab4;
}
env.next_char();
}
break 'lab3;
}
env.cursor = v_3;
// (, line 58
if !env.in_grouping(G_v, 97, 249) {
break 'lab2;
}
// gopast, line 58
'golab7: loop {
'lab8: loop {
if !env.out_grouping(G_v, 97, 249) {
break 'lab8;
}
break 'golab7;
}
if env.cursor >= env.limit {
break 'lab2;
}
env.next_char();
}
break 'lab3;
}
break 'lab1;
}
env.cursor = v_2;
// (, line 60
if !env.out_grouping(G_v, 97, 249) {
break 'lab0;
}
// or, line 60
'lab9: loop {
let v_6 = env.cursor;
'lab10: loop {
// (, line 60
if !env.out_grouping(G_v, 97, 249) {
break 'lab10;
}
// gopast, line 60
'golab11: loop {
'lab12: loop {
if !env.in_grouping(G_v, 97, 249) {
break 'lab12;
}
break 'golab11;
}
if env.cursor >= env.limit {
break 'lab10;
}
env.next_char();
}
break 'lab9;
}
env.cursor = v_6;
// (, line 60
if !env.in_grouping(G_v, 97, 249) {
break 'lab0;
}
// next, line 60
if env.cursor >= env.limit {
break 'lab0;
}
env.next_char();
break 'lab9;
}
break 'lab1;
}
// setmark pV, line 61
context.i_pV = env.cursor;
break 'lab0;
}
env.cursor = v_1;
// do, line 63
let v_8 = env.cursor;
'lab13: loop {
// (, line 63
// gopast, line 64
'golab14: loop {
'lab15: loop {
if !env.in_grouping(G_v, 97, 249) {
break 'lab15;
}
break 'golab14;
}
if env.cursor >= env.limit {
break 'lab13;
}
env.next_char();
}
// gopast, line 64
'golab16: loop {
'lab17: loop {
if !env.out_grouping(G_v, 97, 249) {
break 'lab17;
}
break 'golab16;
}
if env.cursor >= env.limit {
break 'lab13;
}
env.next_char();
}
// setmark p1, line 64
context.i_p1 = env.cursor;
// gopast, line 65
'golab18: loop {
'lab19: loop {
if !env.in_grouping(G_v, 97, 249) {
break 'lab19;
}
break 'golab18;
}
if env.cursor >= env.limit {
break 'lab13;
}
env.next_char();
}
// gopast, line 65
'golab20: loop {
'lab21: loop {
if !env.out_grouping(G_v, 97, 249) {
break 'lab21;
}
break 'golab20;
}
if env.cursor >= env.limit {
break 'lab13;
}
env.next_char();
}
// setmark p2, line 65
context.i_p2 = env.cursor;
break 'lab13;
}
env.cursor = v_8;
return true;
}
fn r_postlude(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// repeat, line 69
'replab0: loop{
let v_1 = env.cursor;
'lab1: for _ in 0..1 {
// (, line 69
// [, line 71
env.bra = env.cursor;
// substring, line 71
among_var = env.find_among(A_1, context);
if among_var == 0 {
break 'lab1;
}
// ], line 71
env.ket = env.cursor;
if among_var == 0 {
break 'lab1;
} else if among_var == 1 {
// (, line 72
// <-, line 72
if !env.slice_from("i") {
return false;
}
} else if among_var == 2 {
// (, line 73
// <-, line 73
if !env.slice_from("u") {
return false;
}
} else if among_var == 3 {
// (, line 74
// next, line 74
if env.cursor >= env.limit {
break 'lab1;
}
env.next_char();
}
continue 'replab0;
}
env.cursor = v_1;
break 'replab0;
}
return true;
}
fn r_RV(env: &mut SnowballEnv, context: &mut Context) -> bool {
if !(context.i_pV <= env.cursor){
return false;
}
return true;
}
fn r_R1(env: &mut SnowballEnv, context: &mut Context) -> bool {
if !(context.i_p1 <= env.cursor){
return false;
}
return true;
}
fn r_R2(env: &mut SnowballEnv, context: &mut Context) -> bool {
if !(context.i_p2 <= env.cursor){
return false;
}
return true;
}
fn r_attached_pronoun(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 85
// [, line 86
env.ket = env.cursor;
// substring, line 86
if env.find_among_b(A_2, context) == 0 {
return false;
}
// ], line 86
env.bra = env.cursor;
// among, line 96
among_var = env.find_among_b(A_3, context);
if among_var == 0 {
return false;
}
// (, line 96
// call RV, line 96
if !r_RV(env, context) {
return false;
}
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 97
// delete, line 97
if !env.slice_del() {
return false;
}
} else if among_var == 2 {
// (, line 98
// <-, line 98
if !env.slice_from("e") {
return false;
}
}
return true;
}
fn r_standard_suffix(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 102
// [, line 103
env.ket = env.cursor;
// substring, line 103
among_var = env.find_among_b(A_6, context);
if among_var == 0 {
return false;
}
// ], line 103
env.bra = env.cursor;
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 110
// call R2, line 110
if !r_R2(env, context) {
return false;
}
// delete, line 110
if !env.slice_del() {
return false;
}
} else if among_var == 2 {
// (, line 112
// call R2, line 112
if !r_R2(env, context) {
return false;
}
// delete, line 112
if !env.slice_del() {
return false;
}
// try, line 113
let v_1 = env.limit - env.cursor;
'lab0: loop {
// (, line 113
// [, line 113
env.ket = env.cursor;
// literal, line 113
if !env.eq_s_b(&"ic") {
env.cursor = env.limit - v_1;
break 'lab0;
}
// ], line 113
env.bra = env.cursor;
// call R2, line 113
if !r_R2(env, context) {
env.cursor = env.limit - v_1;
break 'lab0;
}
// delete, line 113
if !env.slice_del() {
return false;
}
break 'lab0;
}
} else if among_var == 3 {
// (, line 116
// call R2, line 116
if !r_R2(env, context) {
return false;
}
// <-, line 116
if !env.slice_from("log") {
return false;
}
} else if among_var == 4 {
// (, line 118
// call R2, line 118
if !r_R2(env, context) {
return false;
}
// <-, line 118
if !env.slice_from("u") {
return false;
}
} else if among_var == 5 {
// (, line 120
// call R2, line 120
if !r_R2(env, context) {
return false;
}
// <-, line 120
if !env.slice_from("ente") {
return false;
}
} else if among_var == 6 {
// (, line 122
// call RV, line 122
if !r_RV(env, context) {
return false;
}
// delete, line 122
if !env.slice_del() {
return false;
}
} else if among_var == 7 {
// (, line 123
// call R1, line 124
if !r_R1(env, context) {
return false;
}
// delete, line 124
if !env.slice_del() {
return false;
}
// try, line 125
let v_2 = env.limit - env.cursor;
'lab1: loop {
// (, line 125
// [, line 126
env.ket = env.cursor;
// substring, line 126
among_var = env.find_among_b(A_4, context);
if among_var == 0 {
env.cursor = env.limit - v_2;
break 'lab1;
}
// ], line 126
env.bra = env.cursor;
// call R2, line 126
if !r_R2(env, context) {
env.cursor = env.limit - v_2;
break 'lab1;
}
// delete, line 126
if !env.slice_del() {
return false;
}
if among_var == 0 {
env.cursor = env.limit - v_2;
break 'lab1;
} else if among_var == 1 {
// (, line 127
// [, line 127
env.ket = env.cursor;
// literal, line 127
if !env.eq_s_b(&"at") {
env.cursor = env.limit - v_2;
break 'lab1;
}
// ], line 127
env.bra = env.cursor;
// call R2, line 127
if !r_R2(env, context) {
env.cursor = env.limit - v_2;
break 'lab1;
}
// delete, line 127
if !env.slice_del() {
return false;
}
}
break 'lab1;
}
} else if among_var == 8 {
// (, line 132
// call R2, line 133
if !r_R2(env, context) {
return false;
}
// delete, line 133
if !env.slice_del() {
return false;
}
// try, line 134
let v_3 = env.limit - env.cursor;
'lab2: loop {
// (, line 134
// [, line 135
env.ket = env.cursor;
// substring, line 135
among_var = env.find_among_b(A_5, context);
if among_var == 0 {
env.cursor = env.limit - v_3;
break 'lab2;
}
// ], line 135
env.bra = env.cursor;
if among_var == 0 {
env.cursor = env.limit - v_3;
break 'lab2;
} else if among_var == 1 {
// (, line 136
// call R2, line 136
if !r_R2(env, context) {
env.cursor = env.limit - v_3;
break 'lab2;
}
// delete, line 136
if !env.slice_del() {
return false;
}
}
break 'lab2;
}
} else if among_var == 9 {
// (, line 140
// call R2, line 141
if !r_R2(env, context) {
return false;
}
// delete, line 141
if !env.slice_del() {
return false;
}
// try, line 142
let v_4 = env.limit - env.cursor;
'lab3: loop {
// (, line 142
// [, line 142
env.ket = env.cursor;
// literal, line 142
if !env.eq_s_b(&"at") {
env.cursor = env.limit - v_4;
break 'lab3;
}
// ], line 142
env.bra = env.cursor;
// call R2, line 142
if !r_R2(env, context) {
env.cursor = env.limit - v_4;
break 'lab3;
}
// delete, line 142
if !env.slice_del() {
return false;
}
// [, line 142
env.ket = env.cursor;
// literal, line 142
if !env.eq_s_b(&"ic") {
env.cursor = env.limit - v_4;
break 'lab3;
}
// ], line 142
env.bra = env.cursor;
// call R2, line 142
if !r_R2(env, context) {
env.cursor = env.limit - v_4;
break 'lab3;
}
// delete, line 142
if !env.slice_del() {
return false;
}
break 'lab3;
}
}
return true;
}
fn r_verb_suffix(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// setlimit, line 147
let v_1 = env.limit - env.cursor;
// tomark, line 147
if env.cursor < context.i_pV {
return false;
}
env.cursor = context.i_pV;
let v_2 = env.limit_backward;
env.limit_backward = env.cursor;
env.cursor = env.limit - v_1;
// (, line 147
// [, line 148
env.ket = env.cursor;
// substring, line 148
among_var = env.find_among_b(A_7, context);
if among_var == 0 {
env.limit_backward = v_2;
return false;
}
// ], line 148
env.bra = env.cursor;
if among_var == 0 {
env.limit_backward = v_2;
return false;
} else if among_var == 1 {
// (, line 162
// delete, line 162
if !env.slice_del() {
return false;
}
}
env.limit_backward = v_2;
return true;
}
fn r_vowel_suffix(env: &mut SnowballEnv, context: &mut Context) -> bool {
// (, line 169
// try, line 170
let v_1 = env.limit - env.cursor;
'lab0: loop {
// (, line 170
// [, line 171
env.ket = env.cursor;
if !env.in_grouping_b(G_AEIO, 97, 242) {
env.cursor = env.limit - v_1;
break 'lab0;
}
// ], line 171
env.bra = env.cursor;
// call RV, line 171
if !r_RV(env, context) {
env.cursor = env.limit - v_1;
break 'lab0;
}
// delete, line 171
if !env.slice_del() {
return false;
}
// [, line 172
env.ket = env.cursor;
// literal, line 172
if !env.eq_s_b(&"i") {
env.cursor = env.limit - v_1;
break 'lab0;
}
// ], line 172
env.bra = env.cursor;
// call RV, line 172
if !r_RV(env, context) {
env.cursor = env.limit - v_1;
break 'lab0;
}
// delete, line 172
if !env.slice_del() {
return false;
}
break 'lab0;
}
// try, line 174
let v_2 = env.limit - env.cursor;
'lab1: loop {
// (, line 174
// [, line 175
env.ket = env.cursor;
// literal, line 175
if !env.eq_s_b(&"h") {
env.cursor = env.limit - v_2;
break 'lab1;
}
// ], line 175
env.bra = env.cursor;
if !env.in_grouping_b(G_CG, 99, 103) {
env.cursor = env.limit - v_2;
break 'lab1;
}
// call RV, line 175
if !r_RV(env, context) {
env.cursor = env.limit - v_2;
break 'lab1;
}
// delete, line 175
if !env.slice_del() {
return false;
}
break 'lab1;
}
return true;
}
pub fn stem(env: &mut SnowballEnv) -> bool {
let mut context = &mut Context {
i_p2: 0,
i_p1: 0,
i_pV: 0,
};
// (, line 180
// do, line 181
let v_1 = env.cursor;
'lab0: loop {
// call prelude, line 181
if !r_prelude(env, context) {
break 'lab0;
}
break 'lab0;
}
env.cursor = v_1;
// do, line 182
let v_2 = env.cursor;
'lab1: loop {
// call mark_regions, line 182
if !r_mark_regions(env, context) {
break 'lab1;
}
break 'lab1;
}
env.cursor = v_2;
// backwards, line 183
env.limit_backward = env.cursor;
env.cursor = env.limit;
// (, line 183
// do, line 184
let v_3 = env.limit - env.cursor;
'lab2: loop {
// call attached_pronoun, line 184
if !r_attached_pronoun(env, context) {
break 'lab2;
}
break 'lab2;
}
env.cursor = env.limit - v_3;
// do, line 185
let v_4 = env.limit - env.cursor;
'lab3: loop {
// (, line 185
// or, line 185
'lab4: loop {
let v_5 = env.limit - env.cursor;
'lab5: loop {
// call standard_suffix, line 185
if !r_standard_suffix(env, context) {
break 'lab5;
}
break 'lab4;
}
env.cursor = env.limit - v_5;
// call verb_suffix, line 185
if !r_verb_suffix(env, context) {
break 'lab3;
}
break 'lab4;
}
break 'lab3;
}
env.cursor = env.limit - v_4;
// do, line 186
let v_6 = env.limit - env.cursor;
'lab6: loop {
// call vowel_suffix, line 186
if !r_vowel_suffix(env, context) {
break 'lab6;
}
break 'lab6;
}
env.cursor = env.limit - v_6;
env.cursor = env.limit_backward;
// do, line 188
let v_7 = env.cursor;
'lab7: loop {
// call postlude, line 188
if !r_postlude(env, context) {
break 'lab7;
}
break 'lab7;
}
env.cursor = v_7;
return true;
}
| rust | MIT | 1fde09dfa08fb0fb07fbd6570aba8ecc98174edb | 2026-01-04T20:25:20.053159Z | false |
CurrySoftware/rust-stemmers | https://github.com/CurrySoftware/rust-stemmers/blob/1fde09dfa08fb0fb07fbd6570aba8ecc98174edb/src/snowball/algorithms/mod.rs | src/snowball/algorithms/mod.rs | pub mod arabic;
pub mod armenian;
pub mod danish;
pub mod dutch;
pub mod english;
pub mod finnish;
pub mod french;
pub mod german;
pub mod greek;
pub mod hungarian;
pub mod italian;
pub mod norwegian;
pub mod portuguese;
pub mod romanian;
pub mod russian;
pub mod spanish;
pub mod swedish;
pub mod tamil;
pub mod turkish;
| rust | MIT | 1fde09dfa08fb0fb07fbd6570aba8ecc98174edb | 2026-01-04T20:25:20.053159Z | false |
CurrySoftware/rust-stemmers | https://github.com/CurrySoftware/rust-stemmers/blob/1fde09dfa08fb0fb07fbd6570aba8ecc98174edb/src/snowball/algorithms/danish.rs | src/snowball/algorithms/danish.rs | //! This file was generated automatically by the Snowball to Rust compiler
//! http://snowballstem.org/
#![allow(non_upper_case_globals)]
#![allow(non_snake_case)]
#![allow(unused_variables)]
#![allow(unused_mut)]
use snowball::SnowballEnv;
use snowball::Among;
static A_0: &'static [Among<Context>; 32] = &[
Among("hed", -1, 1, None),
Among("ethed", 0, 1, None),
Among("ered", -1, 1, None),
Among("e", -1, 1, None),
Among("erede", 3, 1, None),
Among("ende", 3, 1, None),
Among("erende", 5, 1, None),
Among("ene", 3, 1, None),
Among("erne", 3, 1, None),
Among("ere", 3, 1, None),
Among("en", -1, 1, None),
Among("heden", 10, 1, None),
Among("eren", 10, 1, None),
Among("er", -1, 1, None),
Among("heder", 13, 1, None),
Among("erer", 13, 1, None),
Among("s", -1, 2, None),
Among("heds", 16, 1, None),
Among("es", 16, 1, None),
Among("endes", 18, 1, None),
Among("erendes", 19, 1, None),
Among("enes", 18, 1, None),
Among("ernes", 18, 1, None),
Among("eres", 18, 1, None),
Among("ens", 16, 1, None),
Among("hedens", 24, 1, None),
Among("erens", 24, 1, None),
Among("ers", 16, 1, None),
Among("ets", 16, 1, None),
Among("erets", 28, 1, None),
Among("et", -1, 1, None),
Among("eret", 30, 1, None),
];
static A_1: &'static [Among<Context>; 4] = &[
Among("gd", -1, -1, None),
Among("dt", -1, -1, None),
Among("gt", -1, -1, None),
Among("kt", -1, -1, None),
];
static A_2: &'static [Among<Context>; 5] = &[
Among("ig", -1, 1, None),
Among("lig", 0, 1, None),
Among("elig", 1, 1, None),
Among("els", -1, 1, None),
Among("l\u{00F8}st", -1, 2, None),
];
static G_v: &'static [u8; 19] = &[17, 65, 16, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 48, 0, 128];
static G_s_ending: &'static [u8; 17] = &[239, 254, 42, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16];
#[derive(Clone)]
struct Context {
i_x: usize,
i_p1: usize,
S_ch: String,
}
fn r_mark_regions(env: &mut SnowballEnv, context: &mut Context) -> bool {
// (, line 29
context.i_p1 = env.limit;
// test, line 33
let v_1 = env.cursor;
// (, line 33
// hop, line 33
let c = env.byte_index_for_hop(3);
if 0 as i32 > c || c > env.limit as i32 {
return false;
}
env.cursor = c as usize;
// setmark x, line 33
context.i_x = env.cursor;
env.cursor = v_1;
// goto, line 34
'golab0: loop {
let v_2 = env.cursor;
'lab1: loop {
if !env.in_grouping(G_v, 97, 248) {
break 'lab1;
}
env.cursor = v_2;
break 'golab0;
}
env.cursor = v_2;
if env.cursor >= env.limit {
return false;
}
env.next_char();
}
// gopast, line 34
'golab2: loop {
'lab3: loop {
if !env.out_grouping(G_v, 97, 248) {
break 'lab3;
}
break 'golab2;
}
if env.cursor >= env.limit {
return false;
}
env.next_char();
}
// setmark p1, line 34
context.i_p1 = env.cursor;
// try, line 35
'lab4: loop {
// (, line 35
if !(context.i_p1 < context.i_x){
break 'lab4;
}
context.i_p1 = context.i_x;
break 'lab4;
}
return true;
}
fn r_main_suffix(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 40
// setlimit, line 41
let v_1 = env.limit - env.cursor;
// tomark, line 41
if env.cursor < context.i_p1 {
return false;
}
env.cursor = context.i_p1;
let v_2 = env.limit_backward;
env.limit_backward = env.cursor;
env.cursor = env.limit - v_1;
// (, line 41
// [, line 41
env.ket = env.cursor;
// substring, line 41
among_var = env.find_among_b(A_0, context);
if among_var == 0 {
env.limit_backward = v_2;
return false;
}
// ], line 41
env.bra = env.cursor;
env.limit_backward = v_2;
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 48
// delete, line 48
if !env.slice_del() {
return false;
}
} else if among_var == 2 {
// (, line 50
if !env.in_grouping_b(G_s_ending, 97, 229) {
return false;
}
// delete, line 50
if !env.slice_del() {
return false;
}
}
return true;
}
fn r_consonant_pair(env: &mut SnowballEnv, context: &mut Context) -> bool {
// (, line 54
// test, line 55
let v_1 = env.limit - env.cursor;
// (, line 55
// setlimit, line 56
let v_2 = env.limit - env.cursor;
// tomark, line 56
if env.cursor < context.i_p1 {
return false;
}
env.cursor = context.i_p1;
let v_3 = env.limit_backward;
env.limit_backward = env.cursor;
env.cursor = env.limit - v_2;
// (, line 56
// [, line 56
env.ket = env.cursor;
// substring, line 56
if env.find_among_b(A_1, context) == 0 {
env.limit_backward = v_3;
return false;
}
// ], line 56
env.bra = env.cursor;
env.limit_backward = v_3;
env.cursor = env.limit - v_1;
// next, line 62
if env.cursor <= env.limit_backward {
return false;
}
env.previous_char();
// ], line 62
env.bra = env.cursor;
// delete, line 62
if !env.slice_del() {
return false;
}
return true;
}
fn r_other_suffix(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 65
// do, line 66
let v_1 = env.limit - env.cursor;
'lab0: loop {
// (, line 66
// [, line 66
env.ket = env.cursor;
// literal, line 66
if !env.eq_s_b(&"st") {
break 'lab0;
}
// ], line 66
env.bra = env.cursor;
// literal, line 66
if !env.eq_s_b(&"ig") {
break 'lab0;
}
// delete, line 66
if !env.slice_del() {
return false;
}
break 'lab0;
}
env.cursor = env.limit - v_1;
// setlimit, line 67
let v_2 = env.limit - env.cursor;
// tomark, line 67
if env.cursor < context.i_p1 {
return false;
}
env.cursor = context.i_p1;
let v_3 = env.limit_backward;
env.limit_backward = env.cursor;
env.cursor = env.limit - v_2;
// (, line 67
// [, line 67
env.ket = env.cursor;
// substring, line 67
among_var = env.find_among_b(A_2, context);
if among_var == 0 {
env.limit_backward = v_3;
return false;
}
// ], line 67
env.bra = env.cursor;
env.limit_backward = v_3;
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 70
// delete, line 70
if !env.slice_del() {
return false;
}
// do, line 70
let v_4 = env.limit - env.cursor;
'lab1: loop {
// call consonant_pair, line 70
if !r_consonant_pair(env, context) {
break 'lab1;
}
break 'lab1;
}
env.cursor = env.limit - v_4;
} else if among_var == 2 {
// (, line 72
// <-, line 72
if !env.slice_from("l\u{00F8}s") {
return false;
}
}
return true;
}
fn r_undouble(env: &mut SnowballEnv, context: &mut Context) -> bool {
// (, line 75
// setlimit, line 76
let v_1 = env.limit - env.cursor;
// tomark, line 76
if env.cursor < context.i_p1 {
return false;
}
env.cursor = context.i_p1;
let v_2 = env.limit_backward;
env.limit_backward = env.cursor;
env.cursor = env.limit - v_1;
// (, line 76
// [, line 76
env.ket = env.cursor;
if !env.out_grouping_b(G_v, 97, 248) {
env.limit_backward = v_2;
return false;
}
// ], line 76
env.bra = env.cursor;
// -> ch, line 76
context.S_ch = env.slice_to();
if context.S_ch.is_empty() {
return false;
}
env.limit_backward = v_2;
// name ch, line 77
if !env.eq_s_b(&context.S_ch) {
return false;
}
// delete, line 78
if !env.slice_del() {
return false;
}
return true;
}
pub fn stem(env: &mut SnowballEnv) -> bool {
let mut context = &mut Context {
i_x: 0,
i_p1: 0,
S_ch: String::new(),
};
// (, line 82
// do, line 84
let v_1 = env.cursor;
'lab0: loop {
// call mark_regions, line 84
if !r_mark_regions(env, context) {
break 'lab0;
}
break 'lab0;
}
env.cursor = v_1;
// backwards, line 85
env.limit_backward = env.cursor;
env.cursor = env.limit;
// (, line 85
// do, line 86
let v_2 = env.limit - env.cursor;
'lab1: loop {
// call main_suffix, line 86
if !r_main_suffix(env, context) {
break 'lab1;
}
break 'lab1;
}
env.cursor = env.limit - v_2;
// do, line 87
let v_3 = env.limit - env.cursor;
'lab2: loop {
// call consonant_pair, line 87
if !r_consonant_pair(env, context) {
break 'lab2;
}
break 'lab2;
}
env.cursor = env.limit - v_3;
// do, line 88
let v_4 = env.limit - env.cursor;
'lab3: loop {
// call other_suffix, line 88
if !r_other_suffix(env, context) {
break 'lab3;
}
break 'lab3;
}
env.cursor = env.limit - v_4;
// do, line 89
let v_5 = env.limit - env.cursor;
'lab4: loop {
// call undouble, line 89
if !r_undouble(env, context) {
break 'lab4;
}
break 'lab4;
}
env.cursor = env.limit - v_5;
env.cursor = env.limit_backward;
return true;
}
| rust | MIT | 1fde09dfa08fb0fb07fbd6570aba8ecc98174edb | 2026-01-04T20:25:20.053159Z | false |
CurrySoftware/rust-stemmers | https://github.com/CurrySoftware/rust-stemmers/blob/1fde09dfa08fb0fb07fbd6570aba8ecc98174edb/src/snowball/algorithms/russian.rs | src/snowball/algorithms/russian.rs | //! This file was generated automatically by the Snowball to Rust compiler
//! http://snowballstem.org/
#![allow(non_upper_case_globals)]
#![allow(non_snake_case)]
#![allow(unused_variables)]
#![allow(unused_mut)]
use snowball::SnowballEnv;
use snowball::Among;
static A_0: &'static [Among<Context>; 9] = &[
Among("\u{0432}\u{0448}\u{0438}\u{0441}\u{044C}", -1, 1, None),
Among("\u{044B}\u{0432}\u{0448}\u{0438}\u{0441}\u{044C}", 0, 2, None),
Among("\u{0438}\u{0432}\u{0448}\u{0438}\u{0441}\u{044C}", 0, 2, None),
Among("\u{0432}", -1, 1, None),
Among("\u{044B}\u{0432}", 3, 2, None),
Among("\u{0438}\u{0432}", 3, 2, None),
Among("\u{0432}\u{0448}\u{0438}", -1, 1, None),
Among("\u{044B}\u{0432}\u{0448}\u{0438}", 6, 2, None),
Among("\u{0438}\u{0432}\u{0448}\u{0438}", 6, 2, None),
];
static A_1: &'static [Among<Context>; 26] = &[
Among("\u{0435}\u{043C}\u{0443}", -1, 1, None),
Among("\u{043E}\u{043C}\u{0443}", -1, 1, None),
Among("\u{044B}\u{0445}", -1, 1, None),
Among("\u{0438}\u{0445}", -1, 1, None),
Among("\u{0443}\u{044E}", -1, 1, None),
Among("\u{044E}\u{044E}", -1, 1, None),
Among("\u{0435}\u{044E}", -1, 1, None),
Among("\u{043E}\u{044E}", -1, 1, None),
Among("\u{044F}\u{044F}", -1, 1, None),
Among("\u{0430}\u{044F}", -1, 1, None),
Among("\u{044B}\u{0435}", -1, 1, None),
Among("\u{0435}\u{0435}", -1, 1, None),
Among("\u{0438}\u{0435}", -1, 1, None),
Among("\u{043E}\u{0435}", -1, 1, None),
Among("\u{044B}\u{043C}\u{0438}", -1, 1, None),
Among("\u{0438}\u{043C}\u{0438}", -1, 1, None),
Among("\u{044B}\u{0439}", -1, 1, None),
Among("\u{0435}\u{0439}", -1, 1, None),
Among("\u{0438}\u{0439}", -1, 1, None),
Among("\u{043E}\u{0439}", -1, 1, None),
Among("\u{044B}\u{043C}", -1, 1, None),
Among("\u{0435}\u{043C}", -1, 1, None),
Among("\u{0438}\u{043C}", -1, 1, None),
Among("\u{043E}\u{043C}", -1, 1, None),
Among("\u{0435}\u{0433}\u{043E}", -1, 1, None),
Among("\u{043E}\u{0433}\u{043E}", -1, 1, None),
];
static A_2: &'static [Among<Context>; 8] = &[
Among("\u{0432}\u{0448}", -1, 1, None),
Among("\u{044B}\u{0432}\u{0448}", 0, 2, None),
Among("\u{0438}\u{0432}\u{0448}", 0, 2, None),
Among("\u{0449}", -1, 1, None),
Among("\u{044E}\u{0449}", 3, 1, None),
Among("\u{0443}\u{044E}\u{0449}", 4, 2, None),
Among("\u{0435}\u{043C}", -1, 1, None),
Among("\u{043D}\u{043D}", -1, 1, None),
];
static A_3: &'static [Among<Context>; 2] = &[
Among("\u{0441}\u{044C}", -1, 1, None),
Among("\u{0441}\u{044F}", -1, 1, None),
];
static A_4: &'static [Among<Context>; 46] = &[
Among("\u{044B}\u{0442}", -1, 2, None),
Among("\u{044E}\u{0442}", -1, 1, None),
Among("\u{0443}\u{044E}\u{0442}", 1, 2, None),
Among("\u{044F}\u{0442}", -1, 2, None),
Among("\u{0435}\u{0442}", -1, 1, None),
Among("\u{0443}\u{0435}\u{0442}", 4, 2, None),
Among("\u{0438}\u{0442}", -1, 2, None),
Among("\u{043D}\u{044B}", -1, 1, None),
Among("\u{0435}\u{043D}\u{044B}", 7, 2, None),
Among("\u{0442}\u{044C}", -1, 1, None),
Among("\u{044B}\u{0442}\u{044C}", 9, 2, None),
Among("\u{0438}\u{0442}\u{044C}", 9, 2, None),
Among("\u{0435}\u{0448}\u{044C}", -1, 1, None),
Among("\u{0438}\u{0448}\u{044C}", -1, 2, None),
Among("\u{044E}", -1, 2, None),
Among("\u{0443}\u{044E}", 14, 2, None),
Among("\u{043B}\u{0430}", -1, 1, None),
Among("\u{044B}\u{043B}\u{0430}", 16, 2, None),
Among("\u{0438}\u{043B}\u{0430}", 16, 2, None),
Among("\u{043D}\u{0430}", -1, 1, None),
Among("\u{0435}\u{043D}\u{0430}", 19, 2, None),
Among("\u{0435}\u{0442}\u{0435}", -1, 1, None),
Among("\u{0438}\u{0442}\u{0435}", -1, 2, None),
Among("\u{0439}\u{0442}\u{0435}", -1, 1, None),
Among("\u{0443}\u{0439}\u{0442}\u{0435}", 23, 2, None),
Among("\u{0435}\u{0439}\u{0442}\u{0435}", 23, 2, None),
Among("\u{043B}\u{0438}", -1, 1, None),
Among("\u{044B}\u{043B}\u{0438}", 26, 2, None),
Among("\u{0438}\u{043B}\u{0438}", 26, 2, None),
Among("\u{0439}", -1, 1, None),
Among("\u{0443}\u{0439}", 29, 2, None),
Among("\u{0435}\u{0439}", 29, 2, None),
Among("\u{043B}", -1, 1, None),
Among("\u{044B}\u{043B}", 32, 2, None),
Among("\u{0438}\u{043B}", 32, 2, None),
Among("\u{044B}\u{043C}", -1, 2, None),
Among("\u{0435}\u{043C}", -1, 1, None),
Among("\u{0438}\u{043C}", -1, 2, None),
Among("\u{043D}", -1, 1, None),
Among("\u{0435}\u{043D}", 38, 2, None),
Among("\u{043B}\u{043E}", -1, 1, None),
Among("\u{044B}\u{043B}\u{043E}", 40, 2, None),
Among("\u{0438}\u{043B}\u{043E}", 40, 2, None),
Among("\u{043D}\u{043E}", -1, 1, None),
Among("\u{0435}\u{043D}\u{043E}", 43, 2, None),
Among("\u{043D}\u{043D}\u{043E}", 43, 1, None),
];
static A_5: &'static [Among<Context>; 36] = &[
Among("\u{0443}", -1, 1, None),
Among("\u{044F}\u{0445}", -1, 1, None),
Among("\u{0438}\u{044F}\u{0445}", 1, 1, None),
Among("\u{0430}\u{0445}", -1, 1, None),
Among("\u{044B}", -1, 1, None),
Among("\u{044C}", -1, 1, None),
Among("\u{044E}", -1, 1, None),
Among("\u{044C}\u{044E}", 6, 1, None),
Among("\u{0438}\u{044E}", 6, 1, None),
Among("\u{044F}", -1, 1, None),
Among("\u{044C}\u{044F}", 9, 1, None),
Among("\u{0438}\u{044F}", 9, 1, None),
Among("\u{0430}", -1, 1, None),
Among("\u{0435}\u{0432}", -1, 1, None),
Among("\u{043E}\u{0432}", -1, 1, None),
Among("\u{0435}", -1, 1, None),
Among("\u{044C}\u{0435}", 15, 1, None),
Among("\u{0438}\u{0435}", 15, 1, None),
Among("\u{0438}", -1, 1, None),
Among("\u{0435}\u{0438}", 18, 1, None),
Among("\u{0438}\u{0438}", 18, 1, None),
Among("\u{044F}\u{043C}\u{0438}", 18, 1, None),
Among("\u{0438}\u{044F}\u{043C}\u{0438}", 21, 1, None),
Among("\u{0430}\u{043C}\u{0438}", 18, 1, None),
Among("\u{0439}", -1, 1, None),
Among("\u{0435}\u{0439}", 24, 1, None),
Among("\u{0438}\u{0435}\u{0439}", 25, 1, None),
Among("\u{0438}\u{0439}", 24, 1, None),
Among("\u{043E}\u{0439}", 24, 1, None),
Among("\u{044F}\u{043C}", -1, 1, None),
Among("\u{0438}\u{044F}\u{043C}", 29, 1, None),
Among("\u{0430}\u{043C}", -1, 1, None),
Among("\u{0435}\u{043C}", -1, 1, None),
Among("\u{0438}\u{0435}\u{043C}", 32, 1, None),
Among("\u{043E}\u{043C}", -1, 1, None),
Among("\u{043E}", -1, 1, None),
];
static A_6: &'static [Among<Context>; 2] = &[
Among("\u{043E}\u{0441}\u{0442}", -1, 1, None),
Among("\u{043E}\u{0441}\u{0442}\u{044C}", -1, 1, None),
];
static A_7: &'static [Among<Context>; 4] = &[
Among("\u{0435}\u{0439}\u{0448}", -1, 1, None),
Among("\u{044C}", -1, 3, None),
Among("\u{0435}\u{0439}\u{0448}\u{0435}", -1, 1, None),
Among("\u{043D}", -1, 2, None),
];
static G_v: &'static [u8; 4] = &[33, 65, 8, 232];
#[derive(Clone)]
struct Context {
i_p2: usize,
i_pV: usize,
}
fn r_mark_regions(env: &mut SnowballEnv, context: &mut Context) -> bool {
// (, line 57
context.i_pV = env.limit;
context.i_p2 = env.limit;
// do, line 61
let v_1 = env.cursor;
'lab0: loop {
// (, line 61
// gopast, line 62
'golab1: loop {
'lab2: loop {
if !env.in_grouping(G_v, 1072, 1103) {
break 'lab2;
}
break 'golab1;
}
if env.cursor >= env.limit {
break 'lab0;
}
env.next_char();
}
// setmark pV, line 62
context.i_pV = env.cursor;
// gopast, line 62
'golab3: loop {
'lab4: loop {
if !env.out_grouping(G_v, 1072, 1103) {
break 'lab4;
}
break 'golab3;
}
if env.cursor >= env.limit {
break 'lab0;
}
env.next_char();
}
// gopast, line 63
'golab5: loop {
'lab6: loop {
if !env.in_grouping(G_v, 1072, 1103) {
break 'lab6;
}
break 'golab5;
}
if env.cursor >= env.limit {
break 'lab0;
}
env.next_char();
}
// gopast, line 63
'golab7: loop {
'lab8: loop {
if !env.out_grouping(G_v, 1072, 1103) {
break 'lab8;
}
break 'golab7;
}
if env.cursor >= env.limit {
break 'lab0;
}
env.next_char();
}
// setmark p2, line 63
context.i_p2 = env.cursor;
break 'lab0;
}
env.cursor = v_1;
return true;
}
fn r_R2(env: &mut SnowballEnv, context: &mut Context) -> bool {
if !(context.i_p2 <= env.cursor){
return false;
}
return true;
}
fn r_perfective_gerund(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 71
// [, line 72
env.ket = env.cursor;
// substring, line 72
among_var = env.find_among_b(A_0, context);
if among_var == 0 {
return false;
}
// ], line 72
env.bra = env.cursor;
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 76
// or, line 76
'lab0: loop {
let v_1 = env.limit - env.cursor;
'lab1: loop {
// literal, line 76
if !env.eq_s_b(&"\u{0430}") {
break 'lab1;
}
break 'lab0;
}
env.cursor = env.limit - v_1;
// literal, line 76
if !env.eq_s_b(&"\u{044F}") {
return false;
}
break 'lab0;
}
// delete, line 76
if !env.slice_del() {
return false;
}
} else if among_var == 2 {
// (, line 83
// delete, line 83
if !env.slice_del() {
return false;
}
}
return true;
}
fn r_adjective(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 87
// [, line 88
env.ket = env.cursor;
// substring, line 88
among_var = env.find_among_b(A_1, context);
if among_var == 0 {
return false;
}
// ], line 88
env.bra = env.cursor;
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 97
// delete, line 97
if !env.slice_del() {
return false;
}
}
return true;
}
fn r_adjectival(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 101
// call adjective, line 102
if !r_adjective(env, context) {
return false;
}
// try, line 109
let v_1 = env.limit - env.cursor;
'lab0: loop {
// (, line 109
// [, line 110
env.ket = env.cursor;
// substring, line 110
among_var = env.find_among_b(A_2, context);
if among_var == 0 {
env.cursor = env.limit - v_1;
break 'lab0;
}
// ], line 110
env.bra = env.cursor;
if among_var == 0 {
env.cursor = env.limit - v_1;
break 'lab0;
} else if among_var == 1 {
// (, line 115
// or, line 115
'lab1: loop {
let v_2 = env.limit - env.cursor;
'lab2: loop {
// literal, line 115
if !env.eq_s_b(&"\u{0430}") {
break 'lab2;
}
break 'lab1;
}
env.cursor = env.limit - v_2;
// literal, line 115
if !env.eq_s_b(&"\u{044F}") {
env.cursor = env.limit - v_1;
break 'lab0;
}
break 'lab1;
}
// delete, line 115
if !env.slice_del() {
return false;
}
} else if among_var == 2 {
// (, line 122
// delete, line 122
if !env.slice_del() {
return false;
}
}
break 'lab0;
}
return true;
}
fn r_reflexive(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 128
// [, line 129
env.ket = env.cursor;
// substring, line 129
among_var = env.find_among_b(A_3, context);
if among_var == 0 {
return false;
}
// ], line 129
env.bra = env.cursor;
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 132
// delete, line 132
if !env.slice_del() {
return false;
}
}
return true;
}
fn r_verb(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 136
// [, line 137
env.ket = env.cursor;
// substring, line 137
among_var = env.find_among_b(A_4, context);
if among_var == 0 {
return false;
}
// ], line 137
env.bra = env.cursor;
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 143
// or, line 143
'lab0: loop {
let v_1 = env.limit - env.cursor;
'lab1: loop {
// literal, line 143
if !env.eq_s_b(&"\u{0430}") {
break 'lab1;
}
break 'lab0;
}
env.cursor = env.limit - v_1;
// literal, line 143
if !env.eq_s_b(&"\u{044F}") {
return false;
}
break 'lab0;
}
// delete, line 143
if !env.slice_del() {
return false;
}
} else if among_var == 2 {
// (, line 151
// delete, line 151
if !env.slice_del() {
return false;
}
}
return true;
}
fn r_noun(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 159
// [, line 160
env.ket = env.cursor;
// substring, line 160
among_var = env.find_among_b(A_5, context);
if among_var == 0 {
return false;
}
// ], line 160
env.bra = env.cursor;
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 167
// delete, line 167
if !env.slice_del() {
return false;
}
}
return true;
}
fn r_derivational(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 175
// [, line 176
env.ket = env.cursor;
// substring, line 176
among_var = env.find_among_b(A_6, context);
if among_var == 0 {
return false;
}
// ], line 176
env.bra = env.cursor;
// call R2, line 176
if !r_R2(env, context) {
return false;
}
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 179
// delete, line 179
if !env.slice_del() {
return false;
}
}
return true;
}
fn r_tidy_up(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 183
// [, line 184
env.ket = env.cursor;
// substring, line 184
among_var = env.find_among_b(A_7, context);
if among_var == 0 {
return false;
}
// ], line 184
env.bra = env.cursor;
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 188
// delete, line 188
if !env.slice_del() {
return false;
}
// [, line 189
env.ket = env.cursor;
// literal, line 189
if !env.eq_s_b(&"\u{043D}") {
return false;
}
// ], line 189
env.bra = env.cursor;
// literal, line 189
if !env.eq_s_b(&"\u{043D}") {
return false;
}
// delete, line 189
if !env.slice_del() {
return false;
}
} else if among_var == 2 {
// (, line 192
// literal, line 192
if !env.eq_s_b(&"\u{043D}") {
return false;
}
// delete, line 192
if !env.slice_del() {
return false;
}
} else if among_var == 3 {
// (, line 194
// delete, line 194
if !env.slice_del() {
return false;
}
}
return true;
}
pub fn stem(env: &mut SnowballEnv) -> bool {
let mut context = &mut Context {
i_p2: 0,
i_pV: 0,
};
// (, line 199
// do, line 201
let v_1 = env.cursor;
'lab0: loop {
// call mark_regions, line 201
if !r_mark_regions(env, context) {
break 'lab0;
}
break 'lab0;
}
env.cursor = v_1;
// backwards, line 202
env.limit_backward = env.cursor;
env.cursor = env.limit;
// setlimit, line 202
let v_2 = env.limit - env.cursor;
// tomark, line 202
if env.cursor < context.i_pV {
return false;
}
env.cursor = context.i_pV;
let v_3 = env.limit_backward;
env.limit_backward = env.cursor;
env.cursor = env.limit - v_2;
// (, line 202
// do, line 203
let v_4 = env.limit - env.cursor;
'lab1: loop {
// (, line 203
// or, line 204
'lab2: loop {
let v_5 = env.limit - env.cursor;
'lab3: loop {
// call perfective_gerund, line 204
if !r_perfective_gerund(env, context) {
break 'lab3;
}
break 'lab2;
}
env.cursor = env.limit - v_5;
// (, line 205
// try, line 205
let v_6 = env.limit - env.cursor;
'lab4: loop {
// call reflexive, line 205
if !r_reflexive(env, context) {
env.cursor = env.limit - v_6;
break 'lab4;
}
break 'lab4;
}
// or, line 206
'lab5: loop {
let v_7 = env.limit - env.cursor;
'lab6: loop {
// call adjectival, line 206
if !r_adjectival(env, context) {
break 'lab6;
}
break 'lab5;
}
env.cursor = env.limit - v_7;
'lab7: loop {
// call verb, line 206
if !r_verb(env, context) {
break 'lab7;
}
break 'lab5;
}
env.cursor = env.limit - v_7;
// call noun, line 206
if !r_noun(env, context) {
break 'lab1;
}
break 'lab5;
}
break 'lab2;
}
break 'lab1;
}
env.cursor = env.limit - v_4;
// try, line 209
let v_8 = env.limit - env.cursor;
'lab8: loop {
// (, line 209
// [, line 209
env.ket = env.cursor;
// literal, line 209
if !env.eq_s_b(&"\u{0438}") {
env.cursor = env.limit - v_8;
break 'lab8;
}
// ], line 209
env.bra = env.cursor;
// delete, line 209
if !env.slice_del() {
return false;
}
break 'lab8;
}
// do, line 212
let v_9 = env.limit - env.cursor;
'lab9: loop {
// call derivational, line 212
if !r_derivational(env, context) {
break 'lab9;
}
break 'lab9;
}
env.cursor = env.limit - v_9;
// do, line 213
let v_10 = env.limit - env.cursor;
'lab10: loop {
// call tidy_up, line 213
if !r_tidy_up(env, context) {
break 'lab10;
}
break 'lab10;
}
env.cursor = env.limit - v_10;
env.limit_backward = v_3;
env.cursor = env.limit_backward;
return true;
}
| rust | MIT | 1fde09dfa08fb0fb07fbd6570aba8ecc98174edb | 2026-01-04T20:25:20.053159Z | false |
CurrySoftware/rust-stemmers | https://github.com/CurrySoftware/rust-stemmers/blob/1fde09dfa08fb0fb07fbd6570aba8ecc98174edb/src/snowball/algorithms/arabic.rs | src/snowball/algorithms/arabic.rs | //! This file was generated automatically by the Snowball to Rust compiler
//! http://snowballstem.org/
#![allow(non_upper_case_globals)]
#![allow(non_snake_case)]
#![allow(unused_variables)]
#![allow(unused_mut)]
use snowball::SnowballEnv;
use snowball::Among;
static A_0: &'static [Among<Context>; 161] = &[
Among("!", -1, 3, None),
Among("\"", -1, 3, None),
Among("%", -1, 3, None),
Among("*", -1, 3, None),
Among(",", -1, 3, None),
Among(".", -1, 3, None),
Among("/", -1, 3, None),
Among(":", -1, 3, None),
Among(";", -1, 3, None),
Among("?", -1, 3, None),
Among("\\", -1, 3, None),
Among("\u{060C}", -1, 4, None),
Among("\u{061B}", -1, 4, None),
Among("\u{061F}", -1, 4, None),
Among("\u{0640}", -1, 2, None),
Among("\u{064B}", -1, 1, None),
Among("\u{064C}", -1, 1, None),
Among("\u{064D}", -1, 1, None),
Among("\u{064E}", -1, 1, None),
Among("\u{064F}", -1, 1, None),
Among("\u{0650}", -1, 1, None),
Among("\u{0651}", -1, 1, None),
Among("\u{0652}", -1, 1, None),
Among("\u{0660}", -1, 5, None),
Among("\u{0661}", -1, 6, None),
Among("\u{0662}", -1, 7, None),
Among("\u{0663}", -1, 8, None),
Among("\u{0664}", -1, 9, None),
Among("\u{0665}", -1, 10, None),
Among("\u{0666}", -1, 11, None),
Among("\u{0667}", -1, 12, None),
Among("\u{0668}", -1, 13, None),
Among("\u{0669}", -1, 14, None),
Among("\u{066A}", -1, 15, None),
Among("\u{066B}", -1, 15, None),
Among("\u{066C}", -1, 15, None),
Among("\u{FE80}", -1, 16, None),
Among("\u{FE81}", -1, 20, None),
Among("\u{FE82}", -1, 20, None),
Among("\u{FE83}", -1, 17, None),
Among("\u{FE84}", -1, 17, None),
Among("\u{FE85}", -1, 21, None),
Among("\u{FE86}", -1, 21, None),
Among("\u{FE87}", -1, 18, None),
Among("\u{FE88}", -1, 18, None),
Among("\u{FE89}", -1, 19, None),
Among("\u{FE8A}", -1, 19, None),
Among("\u{FE8B}", -1, 19, None),
Among("\u{FE8C}", -1, 19, None),
Among("\u{FE8D}", -1, 22, None),
Among("\u{FE8E}", -1, 22, None),
Among("\u{FE8F}", -1, 23, None),
Among("\u{FE90}", -1, 23, None),
Among("\u{FE91}", -1, 23, None),
Among("\u{FE92}", -1, 23, None),
Among("\u{FE93}", -1, 24, None),
Among("\u{FE94}", -1, 24, None),
Among("\u{FE95}", -1, 25, None),
Among("\u{FE96}", -1, 25, None),
Among("\u{FE97}", -1, 25, None),
Among("\u{FE98}", -1, 25, None),
Among("\u{FE99}", -1, 26, None),
Among("\u{FE9A}", -1, 26, None),
Among("\u{FE9B}", -1, 26, None),
Among("\u{FE9C}", -1, 26, None),
Among("\u{FE9D}", -1, 27, None),
Among("\u{FE9E}", -1, 27, None),
Among("\u{FE9F}", -1, 27, None),
Among("\u{FEA0}", -1, 27, None),
Among("\u{FEA1}", -1, 28, None),
Among("\u{FEA2}", -1, 28, None),
Among("\u{FEA3}", -1, 28, None),
Among("\u{FEA4}", -1, 28, None),
Among("\u{FEA5}", -1, 29, None),
Among("\u{FEA6}", -1, 29, None),
Among("\u{FEA7}", -1, 29, None),
Among("\u{FEA8}", -1, 29, None),
Among("\u{FEA9}", -1, 30, None),
Among("\u{FEAA}", -1, 30, None),
Among("\u{FEAB}", -1, 31, None),
Among("\u{FEAC}", -1, 31, None),
Among("\u{FEAD}", -1, 32, None),
Among("\u{FEAE}", -1, 32, None),
Among("\u{FEAF}", -1, 33, None),
Among("\u{FEB0}", -1, 33, None),
Among("\u{FEB1}", -1, 34, None),
Among("\u{FEB2}", -1, 34, None),
Among("\u{FEB3}", -1, 34, None),
Among("\u{FEB4}", -1, 34, None),
Among("\u{FEB5}", -1, 35, None),
Among("\u{FEB6}", -1, 35, None),
Among("\u{FEB7}", -1, 35, None),
Among("\u{FEB8}", -1, 35, None),
Among("\u{FEB9}", -1, 36, None),
Among("\u{FEBA}", -1, 36, None),
Among("\u{FEBB}", -1, 36, None),
Among("\u{FEBC}", -1, 36, None),
Among("\u{FEBD}", -1, 37, None),
Among("\u{FEBE}", -1, 37, None),
Among("\u{FEBF}", -1, 37, None),
Among("\u{FEC0}", -1, 37, None),
Among("\u{FEC1}", -1, 38, None),
Among("\u{FEC2}", -1, 38, None),
Among("\u{FEC3}", -1, 38, None),
Among("\u{FEC4}", -1, 38, None),
Among("\u{FEC5}", -1, 39, None),
Among("\u{FEC6}", -1, 39, None),
Among("\u{FEC7}", -1, 39, None),
Among("\u{FEC8}", -1, 39, None),
Among("\u{FEC9}", -1, 40, None),
Among("\u{FECA}", -1, 40, None),
Among("\u{FECB}", -1, 40, None),
Among("\u{FECC}", -1, 40, None),
Among("\u{FECD}", -1, 41, None),
Among("\u{FECE}", -1, 41, None),
Among("\u{FECF}", -1, 41, None),
Among("\u{FED0}", -1, 41, None),
Among("\u{FED1}", -1, 42, None),
Among("\u{FED2}", -1, 42, None),
Among("\u{FED3}", -1, 42, None),
Among("\u{FED4}", -1, 42, None),
Among("\u{FED5}", -1, 43, None),
Among("\u{FED6}", -1, 43, None),
Among("\u{FED7}", -1, 43, None),
Among("\u{FED8}", -1, 43, None),
Among("\u{FED9}", -1, 44, None),
Among("\u{FEDA}", -1, 44, None),
Among("\u{FEDB}", -1, 44, None),
Among("\u{FEDC}", -1, 44, None),
Among("\u{FEDD}", -1, 45, None),
Among("\u{FEDE}", -1, 45, None),
Among("\u{FEDF}", -1, 45, None),
Among("\u{FEE0}", -1, 45, None),
Among("\u{FEE1}", -1, 46, None),
Among("\u{FEE2}", -1, 46, None),
Among("\u{FEE3}", -1, 46, None),
Among("\u{FEE4}", -1, 46, None),
Among("\u{FEE5}", -1, 47, None),
Among("\u{FEE6}", -1, 47, None),
Among("\u{FEE7}", -1, 47, None),
Among("\u{FEE8}", -1, 47, None),
Among("\u{FEE9}", -1, 48, None),
Among("\u{FEEA}", -1, 48, None),
Among("\u{FEEB}", -1, 48, None),
Among("\u{FEEC}", -1, 48, None),
Among("\u{FEED}", -1, 49, None),
Among("\u{FEEE}", -1, 49, None),
Among("\u{FEEF}", -1, 50, None),
Among("\u{FEF0}", -1, 50, None),
Among("\u{FEF1}", -1, 51, None),
Among("\u{FEF2}", -1, 51, None),
Among("\u{FEF3}", -1, 51, None),
Among("\u{FEF4}", -1, 51, None),
Among("\u{FEF5}", -1, 55, None),
Among("\u{FEF6}", -1, 55, None),
Among("\u{FEF7}", -1, 53, None),
Among("\u{FEF8}", -1, 53, None),
Among("\u{FEF9}", -1, 54, None),
Among("\u{FEFA}", -1, 54, None),
Among("\u{FEFB}", -1, 52, None),
Among("\u{FEFC}", -1, 52, None),
];
static A_1: &'static [Among<Context>; 5] = &[
Among("\u{0622}", -1, 1, None),
Among("\u{0623}", -1, 1, None),
Among("\u{0624}", -1, 2, None),
Among("\u{0625}", -1, 1, None),
Among("\u{0626}", -1, 3, None),
];
static A_2: &'static [Among<Context>; 5] = &[
Among("\u{0622}", -1, 1, None),
Among("\u{0623}", -1, 1, None),
Among("\u{0624}", -1, 2, None),
Among("\u{0625}", -1, 1, None),
Among("\u{0626}", -1, 3, None),
];
static A_3: &'static [Among<Context>; 4] = &[
Among("\u{0627}\u{0644}", -1, 2, None),
Among("\u{0628}\u{0627}\u{0644}", -1, 1, None),
Among("\u{0643}\u{0627}\u{0644}", -1, 1, None),
Among("\u{0644}\u{0644}", -1, 2, None),
];
static A_4: &'static [Among<Context>; 5] = &[
Among("\u{0623}\u{0622}", -1, 2, None),
Among("\u{0623}\u{0623}", -1, 1, None),
Among("\u{0623}\u{0624}", -1, 3, None),
Among("\u{0623}\u{0625}", -1, 5, None),
Among("\u{0623}\u{0627}", -1, 4, None),
];
static A_5: &'static [Among<Context>; 2] = &[
Among("\u{0641}", -1, 1, None),
Among("\u{0648}", -1, 2, None),
];
static A_6: &'static [Among<Context>; 4] = &[
Among("\u{0627}\u{0644}", -1, 2, None),
Among("\u{0628}\u{0627}\u{0644}", -1, 1, None),
Among("\u{0643}\u{0627}\u{0644}", -1, 1, None),
Among("\u{0644}\u{0644}", -1, 2, None),
];
static A_7: &'static [Among<Context>; 3] = &[
Among("\u{0628}", -1, 1, None),
Among("\u{0628}\u{0628}", 0, 2, None),
Among("\u{0643}\u{0643}", -1, 3, None),
];
static A_8: &'static [Among<Context>; 4] = &[
Among("\u{0633}\u{0623}", -1, 4, None),
Among("\u{0633}\u{062A}", -1, 2, None),
Among("\u{0633}\u{0646}", -1, 3, None),
Among("\u{0633}\u{064A}", -1, 1, None),
];
static A_9: &'static [Among<Context>; 3] = &[
Among("\u{062A}\u{0633}\u{062A}", -1, 1, None),
Among("\u{0646}\u{0633}\u{062A}", -1, 1, None),
Among("\u{064A}\u{0633}\u{062A}", -1, 1, None),
];
static A_10: &'static [Among<Context>; 10] = &[
Among("\u{0643}", -1, 1, None),
Among("\u{0643}\u{0645}", -1, 2, None),
Among("\u{0647}\u{0645}", -1, 2, None),
Among("\u{0647}\u{0646}", -1, 2, None),
Among("\u{0647}", -1, 1, None),
Among("\u{064A}", -1, 1, None),
Among("\u{0643}\u{0645}\u{0627}", -1, 3, None),
Among("\u{0647}\u{0645}\u{0627}", -1, 3, None),
Among("\u{0646}\u{0627}", -1, 2, None),
Among("\u{0647}\u{0627}", -1, 2, None),
];
static A_11: &'static [Among<Context>; 1] = &[
Among("\u{0646}", -1, 1, None),
];
static A_12: &'static [Among<Context>; 3] = &[
Among("\u{0648}", -1, 1, None),
Among("\u{064A}", -1, 1, None),
Among("\u{0627}", -1, 1, None),
];
static A_13: &'static [Among<Context>; 1] = &[
Among("\u{0627}\u{062A}", -1, 1, None),
];
static A_14: &'static [Among<Context>; 1] = &[
Among("\u{062A}", -1, 1, None),
];
static A_15: &'static [Among<Context>; 1] = &[
Among("\u{0629}", -1, 1, None),
];
static A_16: &'static [Among<Context>; 1] = &[
Among("\u{064A}", -1, 1, None),
];
static A_17: &'static [Among<Context>; 12] = &[
Among("\u{0643}", -1, 1, None),
Among("\u{0643}\u{0645}", -1, 2, None),
Among("\u{0647}\u{0645}", -1, 2, None),
Among("\u{0643}\u{0646}", -1, 2, None),
Among("\u{0647}\u{0646}", -1, 2, None),
Among("\u{0647}", -1, 1, None),
Among("\u{0643}\u{0645}\u{0648}", -1, 3, None),
Among("\u{0646}\u{064A}", -1, 2, None),
Among("\u{0643}\u{0645}\u{0627}", -1, 3, None),
Among("\u{0647}\u{0645}\u{0627}", -1, 3, None),
Among("\u{0646}\u{0627}", -1, 2, None),
Among("\u{0647}\u{0627}", -1, 2, None),
];
static A_18: &'static [Among<Context>; 11] = &[
Among("\u{0646}", -1, 2, None),
Among("\u{0648}\u{0646}", 0, 4, None),
Among("\u{064A}\u{0646}", 0, 4, None),
Among("\u{0627}\u{0646}", 0, 4, None),
Among("\u{062A}\u{0646}", 0, 3, None),
Among("\u{064A}", -1, 2, None),
Among("\u{0627}", -1, 2, None),
Among("\u{062A}\u{0645}\u{0627}", 6, 5, None),
Among("\u{0646}\u{0627}", 6, 3, None),
Among("\u{062A}\u{0627}", 6, 3, None),
Among("\u{062A}", -1, 1, None),
];
static A_19: &'static [Among<Context>; 2] = &[
Among("\u{062A}\u{0645}", -1, 1, None),
Among("\u{0648}\u{0627}", -1, 1, None),
];
static A_20: &'static [Among<Context>; 2] = &[
Among("\u{0648}", -1, 1, None),
Among("\u{062A}\u{0645}\u{0648}", 0, 2, None),
];
static A_21: &'static [Among<Context>; 1] = &[
Among("\u{0649}", -1, 1, None),
];
#[derive(Clone)]
struct Context {
b_is_defined: bool,
b_is_verb: bool,
b_is_noun: bool,
i_word_len: usize,
}
fn r_Normalize_pre(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 258
// loop, line 259
for _ in 0..env.current.chars().count() {
// (, line 259
// or, line 328
'lab0: loop {
let v_2 = env.cursor;
'lab1: loop {
// (, line 260
// [, line 261
env.bra = env.cursor;
// substring, line 261
among_var = env.find_among(A_0, context);
if among_var == 0 {
break 'lab1;
}
// ], line 261
env.ket = env.cursor;
if among_var == 0 {
break 'lab1;
} else if among_var == 1 {
// (, line 262
// delete, line 262
if !env.slice_del() {
return false;
}
} else if among_var == 2 {
// (, line 263
// delete, line 263
if !env.slice_del() {
return false;
}
} else if among_var == 3 {
// (, line 266
// delete, line 266
if !env.slice_del() {
return false;
}
} else if among_var == 4 {
// (, line 267
// delete, line 267
if !env.slice_del() {
return false;
}
} else if among_var == 5 {
// (, line 270
// <-, line 270
if !env.slice_from("0") {
return false;
}
} else if among_var == 6 {
// (, line 271
// <-, line 271
if !env.slice_from("1") {
return false;
}
} else if among_var == 7 {
// (, line 272
// <-, line 272
if !env.slice_from("2") {
return false;
}
} else if among_var == 8 {
// (, line 273
// <-, line 273
if !env.slice_from("3") {
return false;
}
} else if among_var == 9 {
// (, line 274
// <-, line 274
if !env.slice_from("4") {
return false;
}
} else if among_var == 10 {
// (, line 275
// <-, line 275
if !env.slice_from("5") {
return false;
}
} else if among_var == 11 {
// (, line 276
// <-, line 276
if !env.slice_from("6") {
return false;
}
} else if among_var == 12 {
// (, line 277
// <-, line 277
if !env.slice_from("7") {
return false;
}
} else if among_var == 13 {
// (, line 278
// <-, line 278
if !env.slice_from("8") {
return false;
}
} else if among_var == 14 {
// (, line 279
// <-, line 279
if !env.slice_from("9") {
return false;
}
} else if among_var == 15 {
// (, line 280
// delete, line 280
if !env.slice_del() {
return false;
}
} else if among_var == 16 {
// (, line 283
// <-, line 283
if !env.slice_from("\u{0621}") {
return false;
}
} else if among_var == 17 {
// (, line 284
// <-, line 284
if !env.slice_from("\u{0623}") {
return false;
}
} else if among_var == 18 {
// (, line 285
// <-, line 285
if !env.slice_from("\u{0625}") {
return false;
}
} else if among_var == 19 {
// (, line 286
// <-, line 286
if !env.slice_from("\u{0626}") {
return false;
}
} else if among_var == 20 {
// (, line 287
// <-, line 287
if !env.slice_from("\u{0622}") {
return false;
}
} else if among_var == 21 {
// (, line 288
// <-, line 288
if !env.slice_from("\u{0624}") {
return false;
}
} else if among_var == 22 {
// (, line 289
// <-, line 289
if !env.slice_from("\u{0627}") {
return false;
}
} else if among_var == 23 {
// (, line 290
// <-, line 290
if !env.slice_from("\u{0628}") {
return false;
}
} else if among_var == 24 {
// (, line 291
// <-, line 291
if !env.slice_from("\u{0629}") {
return false;
}
} else if among_var == 25 {
// (, line 292
// <-, line 292
if !env.slice_from("\u{062A}") {
return false;
}
} else if among_var == 26 {
// (, line 293
// <-, line 293
if !env.slice_from("\u{062B}") {
return false;
}
} else if among_var == 27 {
// (, line 294
// <-, line 294
if !env.slice_from("\u{062C}") {
return false;
}
} else if among_var == 28 {
// (, line 295
// <-, line 295
if !env.slice_from("\u{062D}") {
return false;
}
} else if among_var == 29 {
// (, line 296
// <-, line 296
if !env.slice_from("\u{062E}") {
return false;
}
} else if among_var == 30 {
// (, line 297
// <-, line 297
if !env.slice_from("\u{062F}") {
return false;
}
} else if among_var == 31 {
// (, line 298
// <-, line 298
if !env.slice_from("\u{0630}") {
return false;
}
} else if among_var == 32 {
// (, line 299
// <-, line 299
if !env.slice_from("\u{0631}") {
return false;
}
} else if among_var == 33 {
// (, line 300
// <-, line 300
if !env.slice_from("\u{0632}") {
return false;
}
} else if among_var == 34 {
// (, line 301
// <-, line 301
if !env.slice_from("\u{0633}") {
return false;
}
} else if among_var == 35 {
// (, line 302
// <-, line 302
if !env.slice_from("\u{0634}") {
return false;
}
} else if among_var == 36 {
// (, line 303
// <-, line 303
if !env.slice_from("\u{0635}") {
return false;
}
} else if among_var == 37 {
// (, line 304
// <-, line 304
if !env.slice_from("\u{0636}") {
return false;
}
} else if among_var == 38 {
// (, line 305
// <-, line 305
if !env.slice_from("\u{0637}") {
return false;
}
} else if among_var == 39 {
// (, line 306
// <-, line 306
if !env.slice_from("\u{0638}") {
return false;
}
} else if among_var == 40 {
// (, line 307
// <-, line 307
if !env.slice_from("\u{0639}") {
return false;
}
} else if among_var == 41 {
// (, line 308
// <-, line 308
if !env.slice_from("\u{063A}") {
return false;
}
} else if among_var == 42 {
// (, line 309
// <-, line 309
if !env.slice_from("\u{0641}") {
return false;
}
} else if among_var == 43 {
// (, line 310
// <-, line 310
if !env.slice_from("\u{0642}") {
return false;
}
} else if among_var == 44 {
// (, line 311
// <-, line 311
if !env.slice_from("\u{0643}") {
return false;
}
} else if among_var == 45 {
// (, line 312
// <-, line 312
if !env.slice_from("\u{0644}") {
return false;
}
} else if among_var == 46 {
// (, line 313
// <-, line 313
if !env.slice_from("\u{0645}") {
return false;
}
} else if among_var == 47 {
// (, line 314
// <-, line 314
if !env.slice_from("\u{0646}") {
return false;
}
} else if among_var == 48 {
// (, line 315
// <-, line 315
if !env.slice_from("\u{0647}") {
return false;
}
} else if among_var == 49 {
// (, line 316
// <-, line 316
if !env.slice_from("\u{0648}") {
return false;
}
} else if among_var == 50 {
// (, line 317
// <-, line 317
if !env.slice_from("\u{0649}") {
return false;
}
} else if among_var == 51 {
// (, line 318
// <-, line 318
if !env.slice_from("\u{064A}") {
return false;
}
} else if among_var == 52 {
// (, line 321
// <-, line 321
if !env.slice_from("\u{0644}\u{0627}") {
return false;
}
} else if among_var == 53 {
// (, line 322
// <-, line 322
if !env.slice_from("\u{0644}\u{0623}") {
return false;
}
} else if among_var == 54 {
// (, line 323
// <-, line 323
if !env.slice_from("\u{0644}\u{0625}") {
return false;
}
} else if among_var == 55 {
// (, line 324
// <-, line 324
if !env.slice_from("\u{0644}\u{0622}") {
return false;
}
}
break 'lab0;
}
env.cursor = v_2;
// next, line 329
if env.cursor >= env.limit {
return false;
}
env.next_char();
break 'lab0;
}
}
return true;
}
fn r_Normalize_post(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 333
// do, line 335
let v_1 = env.cursor;
'lab0: loop {
// (, line 335
// backwards, line 337
env.limit_backward = env.cursor;
env.cursor = env.limit;
// (, line 337
// [, line 338
env.ket = env.cursor;
// substring, line 338
among_var = env.find_among_b(A_1, context);
if among_var == 0 {
break 'lab0;
}
// ], line 338
env.bra = env.cursor;
if among_var == 0 {
break 'lab0;
} else if among_var == 1 {
// (, line 339
// <-, line 339
if !env.slice_from("\u{0621}") {
return false;
}
} else if among_var == 2 {
// (, line 340
// <-, line 340
if !env.slice_from("\u{0621}") {
return false;
}
} else if among_var == 3 {
// (, line 341
// <-, line 341
if !env.slice_from("\u{0621}") {
return false;
}
}
env.cursor = env.limit_backward;
break 'lab0;
}
env.cursor = v_1;
// do, line 346
let v_2 = env.cursor;
'lab1: loop {
// loop, line 346
for _ in 0..context.i_word_len {
// (, line 346
// or, line 355
'lab2: loop {
let v_4 = env.cursor;
'lab3: loop {
// (, line 347
// [, line 349
env.bra = env.cursor;
// substring, line 349
among_var = env.find_among(A_2, context);
if among_var == 0 {
break 'lab3;
}
// ], line 349
env.ket = env.cursor;
if among_var == 0 {
break 'lab3;
} else if among_var == 1 {
// (, line 350
// <-, line 350
if !env.slice_from("\u{0627}") {
return false;
}
} else if among_var == 2 {
// (, line 351
// <-, line 351
if !env.slice_from("\u{0648}") {
return false;
}
} else if among_var == 3 {
// (, line 352
// <-, line 352
if !env.slice_from("\u{064A}") {
return false;
}
}
break 'lab2;
}
env.cursor = v_4;
// next, line 356
if env.cursor >= env.limit {
break 'lab1;
}
env.next_char();
break 'lab2;
}
}
break 'lab1;
}
env.cursor = v_2;
return true;
}
fn r_Checks1(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 361
context.i_word_len = env.current.chars().count();
// [, line 363
env.bra = env.cursor;
// substring, line 363
among_var = env.find_among(A_3, context);
if among_var == 0 {
return false;
}
// ], line 363
env.ket = env.cursor;
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 364
if !(context.i_word_len > 4){
return false;
}
// set is_noun, line 364
context.b_is_noun = true;
// unset is_verb, line 364
context.b_is_verb = false;
// set is_defined, line 364
context.b_is_defined = true;
} else if among_var == 2 {
// (, line 365
if !(context.i_word_len > 3){
return false;
}
// set is_noun, line 365
context.b_is_noun = true;
// unset is_verb, line 365
context.b_is_verb = false;
// set is_defined, line 365
context.b_is_defined = true;
}
return true;
}
fn r_Prefix_Step1(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 371
context.i_word_len = env.current.chars().count();
// [, line 373
env.bra = env.cursor;
// substring, line 373
among_var = env.find_among(A_4, context);
if among_var == 0 {
return false;
}
// ], line 373
env.ket = env.cursor;
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 374
if !(context.i_word_len > 3){
return false;
}
// <-, line 374
if !env.slice_from("\u{0623}") {
return false;
}
} else if among_var == 2 {
// (, line 375
if !(context.i_word_len > 3){
return false;
}
// <-, line 375
if !env.slice_from("\u{0622}") {
return false;
}
} else if among_var == 3 {
// (, line 376
if !(context.i_word_len > 3){
return false;
}
// <-, line 376
if !env.slice_from("\u{0623}") {
return false;
}
} else if among_var == 4 {
// (, line 377
if !(context.i_word_len > 3){
return false;
}
// <-, line 377
if !env.slice_from("\u{0627}") {
return false;
}
} else if among_var == 5 {
// (, line 378
if !(context.i_word_len > 3){
return false;
}
// <-, line 378
if !env.slice_from("\u{0625}") {
return false;
}
}
return true;
}
fn r_Prefix_Step2(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 383
context.i_word_len = env.current.chars().count();
// not, line 385
let v_1 = env.cursor;
'lab0: loop {
// literal, line 385
if !env.eq_s(&"\u{0641}\u{0627}") {
break 'lab0;
}
return false;
}
env.cursor = v_1;
// not, line 386
let v_2 = env.cursor;
'lab1: loop {
// literal, line 386
if !env.eq_s(&"\u{0648}\u{0627}") {
break 'lab1;
}
return false;
}
env.cursor = v_2;
// [, line 387
env.bra = env.cursor;
// substring, line 387
among_var = env.find_among(A_5, context);
if among_var == 0 {
return false;
}
// ], line 387
env.ket = env.cursor;
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 388
if !(context.i_word_len > 3){
return false;
}
// delete, line 388
if !env.slice_del() {
return false;
}
} else if among_var == 2 {
// (, line 389
if !(context.i_word_len > 3){
return false;
}
// delete, line 389
if !env.slice_del() {
return false;
}
}
return true;
}
fn r_Prefix_Step3a_Noun(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 393
context.i_word_len = env.current.chars().count();
// [, line 395
env.bra = env.cursor;
// substring, line 395
among_var = env.find_among(A_6, context);
if among_var == 0 {
return false;
}
// ], line 395
env.ket = env.cursor;
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 396
if !(context.i_word_len > 5){
return false;
}
// delete, line 396
if !env.slice_del() {
return false;
}
} else if among_var == 2 {
// (, line 397
if !(context.i_word_len > 4){
return false;
}
// delete, line 397
if !env.slice_del() {
return false;
}
}
return true;
}
fn r_Prefix_Step3b_Noun(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 401
context.i_word_len = env.current.chars().count();
// not, line 403
let v_1 = env.cursor;
'lab0: loop {
// literal, line 403
if !env.eq_s(&"\u{0628}\u{0627}") {
break 'lab0;
| rust | MIT | 1fde09dfa08fb0fb07fbd6570aba8ecc98174edb | 2026-01-04T20:25:20.053159Z | true |
CurrySoftware/rust-stemmers | https://github.com/CurrySoftware/rust-stemmers/blob/1fde09dfa08fb0fb07fbd6570aba8ecc98174edb/src/snowball/algorithms/french.rs | src/snowball/algorithms/french.rs | //! This file was generated automatically by the Snowball to Rust compiler
//! http://snowballstem.org/
#![allow(non_upper_case_globals)]
#![allow(non_snake_case)]
#![allow(unused_variables)]
#![allow(unused_mut)]
use snowball::SnowballEnv;
use snowball::Among;
static A_0: &'static [Among<Context>; 3] = &[
Among("col", -1, -1, None),
Among("par", -1, -1, None),
Among("tap", -1, -1, None),
];
static A_1: &'static [Among<Context>; 4] = &[
Among("", -1, 4, None),
Among("I", 0, 1, None),
Among("U", 0, 2, None),
Among("Y", 0, 3, None),
];
static A_2: &'static [Among<Context>; 6] = &[
Among("iqU", -1, 3, None),
Among("abl", -1, 3, None),
Among("I\u{00E8}r", -1, 4, None),
Among("i\u{00E8}r", -1, 4, None),
Among("eus", -1, 2, None),
Among("iv", -1, 1, None),
];
static A_3: &'static [Among<Context>; 3] = &[
Among("ic", -1, 2, None),
Among("abil", -1, 1, None),
Among("iv", -1, 3, None),
];
static A_4: &'static [Among<Context>; 43] = &[
Among("iqUe", -1, 1, None),
Among("atrice", -1, 2, None),
Among("ance", -1, 1, None),
Among("ence", -1, 5, None),
Among("logie", -1, 3, None),
Among("able", -1, 1, None),
Among("isme", -1, 1, None),
Among("euse", -1, 11, None),
Among("iste", -1, 1, None),
Among("ive", -1, 8, None),
Among("if", -1, 8, None),
Among("usion", -1, 4, None),
Among("ation", -1, 2, None),
Among("ution", -1, 4, None),
Among("ateur", -1, 2, None),
Among("iqUes", -1, 1, None),
Among("atrices", -1, 2, None),
Among("ances", -1, 1, None),
Among("ences", -1, 5, None),
Among("logies", -1, 3, None),
Among("ables", -1, 1, None),
Among("ismes", -1, 1, None),
Among("euses", -1, 11, None),
Among("istes", -1, 1, None),
Among("ives", -1, 8, None),
Among("ifs", -1, 8, None),
Among("usions", -1, 4, None),
Among("ations", -1, 2, None),
Among("utions", -1, 4, None),
Among("ateurs", -1, 2, None),
Among("ments", -1, 15, None),
Among("ements", 30, 6, None),
Among("issements", 31, 12, None),
Among("it\u{00E9}s", -1, 7, None),
Among("ment", -1, 15, None),
Among("ement", 34, 6, None),
Among("issement", 35, 12, None),
Among("amment", 34, 13, None),
Among("emment", 34, 14, None),
Among("aux", -1, 10, None),
Among("eaux", 39, 9, None),
Among("eux", -1, 1, None),
Among("it\u{00E9}", -1, 7, None),
];
static A_5: &'static [Among<Context>; 35] = &[
Among("ira", -1, 1, None),
Among("ie", -1, 1, None),
Among("isse", -1, 1, None),
Among("issante", -1, 1, None),
Among("i", -1, 1, None),
Among("irai", 4, 1, None),
Among("ir", -1, 1, None),
Among("iras", -1, 1, None),
Among("ies", -1, 1, None),
Among("\u{00EE}mes", -1, 1, None),
Among("isses", -1, 1, None),
Among("issantes", -1, 1, None),
Among("\u{00EE}tes", -1, 1, None),
Among("is", -1, 1, None),
Among("irais", 13, 1, None),
Among("issais", 13, 1, None),
Among("irions", -1, 1, None),
Among("issions", -1, 1, None),
Among("irons", -1, 1, None),
Among("issons", -1, 1, None),
Among("issants", -1, 1, None),
Among("it", -1, 1, None),
Among("irait", 21, 1, None),
Among("issait", 21, 1, None),
Among("issant", -1, 1, None),
Among("iraIent", -1, 1, None),
Among("issaIent", -1, 1, None),
Among("irent", -1, 1, None),
Among("issent", -1, 1, None),
Among("iront", -1, 1, None),
Among("\u{00EE}t", -1, 1, None),
Among("iriez", -1, 1, None),
Among("issiez", -1, 1, None),
Among("irez", -1, 1, None),
Among("issez", -1, 1, None),
];
static A_6: &'static [Among<Context>; 38] = &[
Among("a", -1, 3, None),
Among("era", 0, 2, None),
Among("asse", -1, 3, None),
Among("ante", -1, 3, None),
Among("\u{00E9}e", -1, 2, None),
Among("ai", -1, 3, None),
Among("erai", 5, 2, None),
Among("er", -1, 2, None),
Among("as", -1, 3, None),
Among("eras", 8, 2, None),
Among("\u{00E2}mes", -1, 3, None),
Among("asses", -1, 3, None),
Among("antes", -1, 3, None),
Among("\u{00E2}tes", -1, 3, None),
Among("\u{00E9}es", -1, 2, None),
Among("ais", -1, 3, None),
Among("erais", 15, 2, None),
Among("ions", -1, 1, None),
Among("erions", 17, 2, None),
Among("assions", 17, 3, None),
Among("erons", -1, 2, None),
Among("ants", -1, 3, None),
Among("\u{00E9}s", -1, 2, None),
Among("ait", -1, 3, None),
Among("erait", 23, 2, None),
Among("ant", -1, 3, None),
Among("aIent", -1, 3, None),
Among("eraIent", 26, 2, None),
Among("\u{00E8}rent", -1, 2, None),
Among("assent", -1, 3, None),
Among("eront", -1, 2, None),
Among("\u{00E2}t", -1, 3, None),
Among("ez", -1, 2, None),
Among("iez", 32, 2, None),
Among("eriez", 33, 2, None),
Among("assiez", 33, 3, None),
Among("erez", 32, 2, None),
Among("\u{00E9}", -1, 2, None),
];
static A_7: &'static [Among<Context>; 7] = &[
Among("e", -1, 3, None),
Among("I\u{00E8}re", 0, 2, None),
Among("i\u{00E8}re", 0, 2, None),
Among("ion", -1, 1, None),
Among("Ier", -1, 2, None),
Among("ier", -1, 2, None),
Among("\u{00EB}", -1, 4, None),
];
static A_8: &'static [Among<Context>; 5] = &[
Among("ell", -1, -1, None),
Among("eill", -1, -1, None),
Among("enn", -1, -1, None),
Among("onn", -1, -1, None),
Among("ett", -1, -1, None),
];
static G_v: &'static [u8; 20] = &[17, 65, 16, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 130, 103, 8, 5];
static G_keep_with_s: &'static [u8; 17] = &[1, 65, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128];
#[derive(Clone)]
struct Context {
i_p2: usize,
i_p1: usize,
i_pV: usize,
}
fn r_prelude(env: &mut SnowballEnv, context: &mut Context) -> bool {
// repeat, line 38
'replab0: loop{
let v_1 = env.cursor;
'lab1: for _ in 0..1 {
// goto, line 38
'golab2: loop {
let v_2 = env.cursor;
'lab3: loop {
// (, line 38
// or, line 44
'lab4: loop {
let v_3 = env.cursor;
'lab5: loop {
// (, line 40
if !env.in_grouping(G_v, 97, 251) {
break 'lab5;
}
// [, line 40
env.bra = env.cursor;
// or, line 40
'lab6: loop {
let v_4 = env.cursor;
'lab7: loop {
// (, line 40
// literal, line 40
if !env.eq_s(&"u") {
break 'lab7;
}
// ], line 40
env.ket = env.cursor;
if !env.in_grouping(G_v, 97, 251) {
break 'lab7;
}
// <-, line 40
if !env.slice_from("U") {
return false;
}
break 'lab6;
}
env.cursor = v_4;
'lab8: loop {
// (, line 41
// literal, line 41
if !env.eq_s(&"i") {
break 'lab8;
}
// ], line 41
env.ket = env.cursor;
if !env.in_grouping(G_v, 97, 251) {
break 'lab8;
}
// <-, line 41
if !env.slice_from("I") {
return false;
}
break 'lab6;
}
env.cursor = v_4;
// (, line 42
// literal, line 42
if !env.eq_s(&"y") {
break 'lab5;
}
// ], line 42
env.ket = env.cursor;
// <-, line 42
if !env.slice_from("Y") {
return false;
}
break 'lab6;
}
break 'lab4;
}
env.cursor = v_3;
'lab9: loop {
// (, line 45
// [, line 45
env.bra = env.cursor;
// literal, line 45
if !env.eq_s(&"y") {
break 'lab9;
}
// ], line 45
env.ket = env.cursor;
if !env.in_grouping(G_v, 97, 251) {
break 'lab9;
}
// <-, line 45
if !env.slice_from("Y") {
return false;
}
break 'lab4;
}
env.cursor = v_3;
// (, line 47
// literal, line 47
if !env.eq_s(&"q") {
break 'lab3;
}
// [, line 47
env.bra = env.cursor;
// literal, line 47
if !env.eq_s(&"u") {
break 'lab3;
}
// ], line 47
env.ket = env.cursor;
// <-, line 47
if !env.slice_from("U") {
return false;
}
break 'lab4;
}
env.cursor = v_2;
break 'golab2;
}
env.cursor = v_2;
if env.cursor >= env.limit {
break 'lab1;
}
env.next_char();
}
continue 'replab0;
}
env.cursor = v_1;
break 'replab0;
}
return true;
}
fn r_mark_regions(env: &mut SnowballEnv, context: &mut Context) -> bool {
// (, line 50
context.i_pV = env.limit;
context.i_p1 = env.limit;
context.i_p2 = env.limit;
// do, line 56
let v_1 = env.cursor;
'lab0: loop {
// (, line 56
// or, line 58
'lab1: loop {
let v_2 = env.cursor;
'lab2: loop {
// (, line 57
if !env.in_grouping(G_v, 97, 251) {
break 'lab2;
}
if !env.in_grouping(G_v, 97, 251) {
break 'lab2;
}
// next, line 57
if env.cursor >= env.limit {
break 'lab2;
}
env.next_char();
break 'lab1;
}
env.cursor = v_2;
'lab3: loop {
// among, line 59
if env.find_among(A_0, context) == 0 {
break 'lab3;
}
break 'lab1;
}
env.cursor = v_2;
// (, line 66
// next, line 66
if env.cursor >= env.limit {
break 'lab0;
}
env.next_char();
// gopast, line 66
'golab4: loop {
'lab5: loop {
if !env.in_grouping(G_v, 97, 251) {
break 'lab5;
}
break 'golab4;
}
if env.cursor >= env.limit {
break 'lab0;
}
env.next_char();
}
break 'lab1;
}
// setmark pV, line 67
context.i_pV = env.cursor;
break 'lab0;
}
env.cursor = v_1;
// do, line 69
let v_4 = env.cursor;
'lab6: loop {
// (, line 69
// gopast, line 70
'golab7: loop {
'lab8: loop {
if !env.in_grouping(G_v, 97, 251) {
break 'lab8;
}
break 'golab7;
}
if env.cursor >= env.limit {
break 'lab6;
}
env.next_char();
}
// gopast, line 70
'golab9: loop {
'lab10: loop {
if !env.out_grouping(G_v, 97, 251) {
break 'lab10;
}
break 'golab9;
}
if env.cursor >= env.limit {
break 'lab6;
}
env.next_char();
}
// setmark p1, line 70
context.i_p1 = env.cursor;
// gopast, line 71
'golab11: loop {
'lab12: loop {
if !env.in_grouping(G_v, 97, 251) {
break 'lab12;
}
break 'golab11;
}
if env.cursor >= env.limit {
break 'lab6;
}
env.next_char();
}
// gopast, line 71
'golab13: loop {
'lab14: loop {
if !env.out_grouping(G_v, 97, 251) {
break 'lab14;
}
break 'golab13;
}
if env.cursor >= env.limit {
break 'lab6;
}
env.next_char();
}
// setmark p2, line 71
context.i_p2 = env.cursor;
break 'lab6;
}
env.cursor = v_4;
return true;
}
fn r_postlude(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// repeat, line 75
'replab0: loop{
let v_1 = env.cursor;
'lab1: for _ in 0..1 {
// (, line 75
// [, line 77
env.bra = env.cursor;
// substring, line 77
among_var = env.find_among(A_1, context);
if among_var == 0 {
break 'lab1;
}
// ], line 77
env.ket = env.cursor;
if among_var == 0 {
break 'lab1;
} else if among_var == 1 {
// (, line 78
// <-, line 78
if !env.slice_from("i") {
return false;
}
} else if among_var == 2 {
// (, line 79
// <-, line 79
if !env.slice_from("u") {
return false;
}
} else if among_var == 3 {
// (, line 80
// <-, line 80
if !env.slice_from("y") {
return false;
}
} else if among_var == 4 {
// (, line 81
// next, line 81
if env.cursor >= env.limit {
break 'lab1;
}
env.next_char();
}
continue 'replab0;
}
env.cursor = v_1;
break 'replab0;
}
return true;
}
fn r_RV(env: &mut SnowballEnv, context: &mut Context) -> bool {
if !(context.i_pV <= env.cursor){
return false;
}
return true;
}
fn r_R1(env: &mut SnowballEnv, context: &mut Context) -> bool {
if !(context.i_p1 <= env.cursor){
return false;
}
return true;
}
fn r_R2(env: &mut SnowballEnv, context: &mut Context) -> bool {
if !(context.i_p2 <= env.cursor){
return false;
}
return true;
}
fn r_standard_suffix(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 91
// [, line 92
env.ket = env.cursor;
// substring, line 92
among_var = env.find_among_b(A_4, context);
if among_var == 0 {
return false;
}
// ], line 92
env.bra = env.cursor;
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 96
// call R2, line 96
if !r_R2(env, context) {
return false;
}
// delete, line 96
if !env.slice_del() {
return false;
}
} else if among_var == 2 {
// (, line 99
// call R2, line 99
if !r_R2(env, context) {
return false;
}
// delete, line 99
if !env.slice_del() {
return false;
}
// try, line 100
let v_1 = env.limit - env.cursor;
'lab0: loop {
// (, line 100
// [, line 100
env.ket = env.cursor;
// literal, line 100
if !env.eq_s_b(&"ic") {
env.cursor = env.limit - v_1;
break 'lab0;
}
// ], line 100
env.bra = env.cursor;
// or, line 100
'lab1: loop {
let v_2 = env.limit - env.cursor;
'lab2: loop {
// (, line 100
// call R2, line 100
if !r_R2(env, context) {
break 'lab2;
}
// delete, line 100
if !env.slice_del() {
return false;
}
break 'lab1;
}
env.cursor = env.limit - v_2;
// <-, line 100
if !env.slice_from("iqU") {
return false;
}
break 'lab1;
}
break 'lab0;
}
} else if among_var == 3 {
// (, line 104
// call R2, line 104
if !r_R2(env, context) {
return false;
}
// <-, line 104
if !env.slice_from("log") {
return false;
}
} else if among_var == 4 {
// (, line 107
// call R2, line 107
if !r_R2(env, context) {
return false;
}
// <-, line 107
if !env.slice_from("u") {
return false;
}
} else if among_var == 5 {
// (, line 110
// call R2, line 110
if !r_R2(env, context) {
return false;
}
// <-, line 110
if !env.slice_from("ent") {
return false;
}
} else if among_var == 6 {
// (, line 113
// call RV, line 114
if !r_RV(env, context) {
return false;
}
// delete, line 114
if !env.slice_del() {
return false;
}
// try, line 115
let v_3 = env.limit - env.cursor;
'lab3: loop {
// (, line 115
// [, line 116
env.ket = env.cursor;
// substring, line 116
among_var = env.find_among_b(A_2, context);
if among_var == 0 {
env.cursor = env.limit - v_3;
break 'lab3;
}
// ], line 116
env.bra = env.cursor;
if among_var == 0 {
env.cursor = env.limit - v_3;
break 'lab3;
} else if among_var == 1 {
// (, line 117
// call R2, line 117
if !r_R2(env, context) {
env.cursor = env.limit - v_3;
break 'lab3;
}
// delete, line 117
if !env.slice_del() {
return false;
}
// [, line 117
env.ket = env.cursor;
// literal, line 117
if !env.eq_s_b(&"at") {
env.cursor = env.limit - v_3;
break 'lab3;
}
// ], line 117
env.bra = env.cursor;
// call R2, line 117
if !r_R2(env, context) {
env.cursor = env.limit - v_3;
break 'lab3;
}
// delete, line 117
if !env.slice_del() {
return false;
}
} else if among_var == 2 {
// (, line 118
// or, line 118
'lab4: loop {
let v_4 = env.limit - env.cursor;
'lab5: loop {
// (, line 118
// call R2, line 118
if !r_R2(env, context) {
break 'lab5;
}
// delete, line 118
if !env.slice_del() {
return false;
}
break 'lab4;
}
env.cursor = env.limit - v_4;
// (, line 118
// call R1, line 118
if !r_R1(env, context) {
env.cursor = env.limit - v_3;
break 'lab3;
}
// <-, line 118
if !env.slice_from("eux") {
return false;
}
break 'lab4;
}
} else if among_var == 3 {
// (, line 120
// call R2, line 120
if !r_R2(env, context) {
env.cursor = env.limit - v_3;
break 'lab3;
}
// delete, line 120
if !env.slice_del() {
return false;
}
} else if among_var == 4 {
// (, line 122
// call RV, line 122
if !r_RV(env, context) {
env.cursor = env.limit - v_3;
break 'lab3;
}
// <-, line 122
if !env.slice_from("i") {
return false;
}
}
break 'lab3;
}
} else if among_var == 7 {
// (, line 128
// call R2, line 129
if !r_R2(env, context) {
return false;
}
// delete, line 129
if !env.slice_del() {
return false;
}
// try, line 130
let v_5 = env.limit - env.cursor;
'lab6: loop {
// (, line 130
// [, line 131
env.ket = env.cursor;
// substring, line 131
among_var = env.find_among_b(A_3, context);
if among_var == 0 {
env.cursor = env.limit - v_5;
break 'lab6;
}
// ], line 131
env.bra = env.cursor;
if among_var == 0 {
env.cursor = env.limit - v_5;
break 'lab6;
} else if among_var == 1 {
// (, line 132
// or, line 132
'lab7: loop {
let v_6 = env.limit - env.cursor;
'lab8: loop {
// (, line 132
// call R2, line 132
if !r_R2(env, context) {
break 'lab8;
}
// delete, line 132
if !env.slice_del() {
return false;
}
break 'lab7;
}
env.cursor = env.limit - v_6;
// <-, line 132
if !env.slice_from("abl") {
return false;
}
break 'lab7;
}
} else if among_var == 2 {
// (, line 133
// or, line 133
'lab9: loop {
let v_7 = env.limit - env.cursor;
'lab10: loop {
// (, line 133
// call R2, line 133
if !r_R2(env, context) {
break 'lab10;
}
// delete, line 133
if !env.slice_del() {
return false;
}
break 'lab9;
}
env.cursor = env.limit - v_7;
// <-, line 133
if !env.slice_from("iqU") {
return false;
}
break 'lab9;
}
} else if among_var == 3 {
// (, line 134
// call R2, line 134
if !r_R2(env, context) {
env.cursor = env.limit - v_5;
break 'lab6;
}
// delete, line 134
if !env.slice_del() {
return false;
}
}
break 'lab6;
}
} else if among_var == 8 {
// (, line 140
// call R2, line 141
if !r_R2(env, context) {
return false;
}
// delete, line 141
if !env.slice_del() {
return false;
}
// try, line 142
let v_8 = env.limit - env.cursor;
'lab11: loop {
// (, line 142
// [, line 142
env.ket = env.cursor;
// literal, line 142
if !env.eq_s_b(&"at") {
env.cursor = env.limit - v_8;
break 'lab11;
}
// ], line 142
env.bra = env.cursor;
// call R2, line 142
if !r_R2(env, context) {
env.cursor = env.limit - v_8;
break 'lab11;
}
// delete, line 142
if !env.slice_del() {
return false;
}
// [, line 142
env.ket = env.cursor;
// literal, line 142
if !env.eq_s_b(&"ic") {
env.cursor = env.limit - v_8;
break 'lab11;
}
// ], line 142
env.bra = env.cursor;
// or, line 142
'lab12: loop {
let v_9 = env.limit - env.cursor;
'lab13: loop {
// (, line 142
// call R2, line 142
if !r_R2(env, context) {
break 'lab13;
}
// delete, line 142
if !env.slice_del() {
return false;
}
break 'lab12;
}
env.cursor = env.limit - v_9;
// <-, line 142
if !env.slice_from("iqU") {
return false;
}
break 'lab12;
}
break 'lab11;
}
} else if among_var == 9 {
// (, line 144
// <-, line 144
if !env.slice_from("eau") {
return false;
}
} else if among_var == 10 {
// (, line 145
// call R1, line 145
if !r_R1(env, context) {
return false;
}
// <-, line 145
if !env.slice_from("al") {
return false;
}
} else if among_var == 11 {
// (, line 147
// or, line 147
'lab14: loop {
let v_10 = env.limit - env.cursor;
'lab15: loop {
// (, line 147
// call R2, line 147
if !r_R2(env, context) {
break 'lab15;
}
// delete, line 147
if !env.slice_del() {
return false;
}
break 'lab14;
}
env.cursor = env.limit - v_10;
// (, line 147
// call R1, line 147
if !r_R1(env, context) {
return false;
}
// <-, line 147
if !env.slice_from("eux") {
return false;
}
break 'lab14;
}
} else if among_var == 12 {
// (, line 150
// call R1, line 150
if !r_R1(env, context) {
return false;
}
if !env.out_grouping_b(G_v, 97, 251) {
return false;
}
// delete, line 150
if !env.slice_del() {
return false;
}
} else if among_var == 13 {
// (, line 155
// call RV, line 155
if !r_RV(env, context) {
return false;
}
// fail, line 155
// (, line 155
// <-, line 155
if !env.slice_from("ant") {
return false;
}
return false;
} else if among_var == 14 {
// (, line 156
// call RV, line 156
if !r_RV(env, context) {
return false;
}
// fail, line 156
// (, line 156
// <-, line 156
if !env.slice_from("ent") {
return false;
}
return false;
} else if among_var == 15 {
// (, line 158
// test, line 158
let v_11 = env.limit - env.cursor;
// (, line 158
if !env.in_grouping_b(G_v, 97, 251) {
return false;
}
// call RV, line 158
if !r_RV(env, context) {
return false;
}
env.cursor = env.limit - v_11;
// fail, line 158
// (, line 158
// delete, line 158
if !env.slice_del() {
return false;
}
return false;
}
return true;
}
fn r_i_verb_suffix(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// setlimit, line 163
let v_1 = env.limit - env.cursor;
// tomark, line 163
if env.cursor < context.i_pV {
return false;
}
env.cursor = context.i_pV;
let v_2 = env.limit_backward;
env.limit_backward = env.cursor;
env.cursor = env.limit - v_1;
// (, line 163
// [, line 164
env.ket = env.cursor;
// substring, line 164
among_var = env.find_among_b(A_5, context);
if among_var == 0 {
env.limit_backward = v_2;
return false;
}
// ], line 164
env.bra = env.cursor;
if among_var == 0 {
env.limit_backward = v_2;
return false;
} else if among_var == 1 {
// (, line 170
if !env.out_grouping_b(G_v, 97, 251) {
env.limit_backward = v_2;
return false;
}
// delete, line 170
if !env.slice_del() {
return false;
}
}
env.limit_backward = v_2;
return true;
}
fn r_verb_suffix(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// setlimit, line 174
let v_1 = env.limit - env.cursor;
// tomark, line 174
if env.cursor < context.i_pV {
return false;
}
env.cursor = context.i_pV;
let v_2 = env.limit_backward;
env.limit_backward = env.cursor;
env.cursor = env.limit - v_1;
// (, line 174
// [, line 175
env.ket = env.cursor;
// substring, line 175
among_var = env.find_among_b(A_6, context);
if among_var == 0 {
env.limit_backward = v_2;
return false;
}
// ], line 175
env.bra = env.cursor;
if among_var == 0 {
env.limit_backward = v_2;
return false;
} else if among_var == 1 {
// (, line 177
// call R2, line 177
if !r_R2(env, context) {
env.limit_backward = v_2;
| rust | MIT | 1fde09dfa08fb0fb07fbd6570aba8ecc98174edb | 2026-01-04T20:25:20.053159Z | true |
CurrySoftware/rust-stemmers | https://github.com/CurrySoftware/rust-stemmers/blob/1fde09dfa08fb0fb07fbd6570aba8ecc98174edb/src/snowball/algorithms/hungarian.rs | src/snowball/algorithms/hungarian.rs | //! This file was generated automatically by the Snowball to Rust compiler
//! http://snowballstem.org/
#![allow(non_upper_case_globals)]
#![allow(non_snake_case)]
#![allow(unused_variables)]
#![allow(unused_mut)]
use snowball::SnowballEnv;
use snowball::Among;
static A_0: &'static [Among<Context>; 8] = &[
Among("cs", -1, -1, None),
Among("dzs", -1, -1, None),
Among("gy", -1, -1, None),
Among("ly", -1, -1, None),
Among("ny", -1, -1, None),
Among("sz", -1, -1, None),
Among("ty", -1, -1, None),
Among("zs", -1, -1, None),
];
static A_1: &'static [Among<Context>; 2] = &[
Among("\u{00E1}", -1, 1, None),
Among("\u{00E9}", -1, 2, None),
];
static A_2: &'static [Among<Context>; 23] = &[
Among("bb", -1, -1, None),
Among("cc", -1, -1, None),
Among("dd", -1, -1, None),
Among("ff", -1, -1, None),
Among("gg", -1, -1, None),
Among("jj", -1, -1, None),
Among("kk", -1, -1, None),
Among("ll", -1, -1, None),
Among("mm", -1, -1, None),
Among("nn", -1, -1, None),
Among("pp", -1, -1, None),
Among("rr", -1, -1, None),
Among("ccs", -1, -1, None),
Among("ss", -1, -1, None),
Among("zzs", -1, -1, None),
Among("tt", -1, -1, None),
Among("vv", -1, -1, None),
Among("ggy", -1, -1, None),
Among("lly", -1, -1, None),
Among("nny", -1, -1, None),
Among("tty", -1, -1, None),
Among("ssz", -1, -1, None),
Among("zz", -1, -1, None),
];
static A_3: &'static [Among<Context>; 2] = &[
Among("al", -1, 1, None),
Among("el", -1, 2, None),
];
static A_4: &'static [Among<Context>; 44] = &[
Among("ba", -1, -1, None),
Among("ra", -1, -1, None),
Among("be", -1, -1, None),
Among("re", -1, -1, None),
Among("ig", -1, -1, None),
Among("nak", -1, -1, None),
Among("nek", -1, -1, None),
Among("val", -1, -1, None),
Among("vel", -1, -1, None),
Among("ul", -1, -1, None),
Among("b\u{0151}l", -1, -1, None),
Among("r\u{0151}l", -1, -1, None),
Among("t\u{0151}l", -1, -1, None),
Among("n\u{00E1}l", -1, -1, None),
Among("n\u{00E9}l", -1, -1, None),
Among("b\u{00F3}l", -1, -1, None),
Among("r\u{00F3}l", -1, -1, None),
Among("t\u{00F3}l", -1, -1, None),
Among("\u{00FC}l", -1, -1, None),
Among("n", -1, -1, None),
Among("an", 19, -1, None),
Among("ban", 20, -1, None),
Among("en", 19, -1, None),
Among("ben", 22, -1, None),
Among("k\u{00E9}ppen", 22, -1, None),
Among("on", 19, -1, None),
Among("\u{00F6}n", 19, -1, None),
Among("k\u{00E9}pp", -1, -1, None),
Among("kor", -1, -1, None),
Among("t", -1, -1, None),
Among("at", 29, -1, None),
Among("et", 29, -1, None),
Among("k\u{00E9}nt", 29, -1, None),
Among("ank\u{00E9}nt", 32, -1, None),
Among("enk\u{00E9}nt", 32, -1, None),
Among("onk\u{00E9}nt", 32, -1, None),
Among("ot", 29, -1, None),
Among("\u{00E9}rt", 29, -1, None),
Among("\u{00F6}t", 29, -1, None),
Among("hez", -1, -1, None),
Among("hoz", -1, -1, None),
Among("h\u{00F6}z", -1, -1, None),
Among("v\u{00E1}", -1, -1, None),
Among("v\u{00E9}", -1, -1, None),
];
static A_5: &'static [Among<Context>; 3] = &[
Among("\u{00E1}n", -1, 2, None),
Among("\u{00E9}n", -1, 1, None),
Among("\u{00E1}nk\u{00E9}nt", -1, 3, None),
];
static A_6: &'static [Among<Context>; 6] = &[
Among("stul", -1, 2, None),
Among("astul", 0, 1, None),
Among("\u{00E1}stul", 0, 3, None),
Among("st\u{00FC}l", -1, 2, None),
Among("est\u{00FC}l", 3, 1, None),
Among("\u{00E9}st\u{00FC}l", 3, 4, None),
];
static A_7: &'static [Among<Context>; 2] = &[
Among("\u{00E1}", -1, 1, None),
Among("\u{00E9}", -1, 2, None),
];
static A_8: &'static [Among<Context>; 7] = &[
Among("k", -1, 7, None),
Among("ak", 0, 4, None),
Among("ek", 0, 6, None),
Among("ok", 0, 5, None),
Among("\u{00E1}k", 0, 1, None),
Among("\u{00E9}k", 0, 2, None),
Among("\u{00F6}k", 0, 3, None),
];
static A_9: &'static [Among<Context>; 12] = &[
Among("\u{00E9}i", -1, 7, None),
Among("\u{00E1}\u{00E9}i", 0, 6, None),
Among("\u{00E9}\u{00E9}i", 0, 5, None),
Among("\u{00E9}", -1, 9, None),
Among("k\u{00E9}", 3, 4, None),
Among("ak\u{00E9}", 4, 1, None),
Among("ek\u{00E9}", 4, 1, None),
Among("ok\u{00E9}", 4, 1, None),
Among("\u{00E1}k\u{00E9}", 4, 3, None),
Among("\u{00E9}k\u{00E9}", 4, 2, None),
Among("\u{00F6}k\u{00E9}", 4, 1, None),
Among("\u{00E9}\u{00E9}", 3, 8, None),
];
static A_10: &'static [Among<Context>; 31] = &[
Among("a", -1, 18, None),
Among("ja", 0, 17, None),
Among("d", -1, 16, None),
Among("ad", 2, 13, None),
Among("ed", 2, 13, None),
Among("od", 2, 13, None),
Among("\u{00E1}d", 2, 14, None),
Among("\u{00E9}d", 2, 15, None),
Among("\u{00F6}d", 2, 13, None),
Among("e", -1, 18, None),
Among("je", 9, 17, None),
Among("nk", -1, 4, None),
Among("unk", 11, 1, None),
Among("\u{00E1}nk", 11, 2, None),
Among("\u{00E9}nk", 11, 3, None),
Among("\u{00FC}nk", 11, 1, None),
Among("uk", -1, 8, None),
Among("juk", 16, 7, None),
Among("\u{00E1}juk", 17, 5, None),
Among("\u{00FC}k", -1, 8, None),
Among("j\u{00FC}k", 19, 7, None),
Among("\u{00E9}j\u{00FC}k", 20, 6, None),
Among("m", -1, 12, None),
Among("am", 22, 9, None),
Among("em", 22, 9, None),
Among("om", 22, 9, None),
Among("\u{00E1}m", 22, 10, None),
Among("\u{00E9}m", 22, 11, None),
Among("o", -1, 18, None),
Among("\u{00E1}", -1, 19, None),
Among("\u{00E9}", -1, 20, None),
];
static A_11: &'static [Among<Context>; 42] = &[
Among("id", -1, 10, None),
Among("aid", 0, 9, None),
Among("jaid", 1, 6, None),
Among("eid", 0, 9, None),
Among("jeid", 3, 6, None),
Among("\u{00E1}id", 0, 7, None),
Among("\u{00E9}id", 0, 8, None),
Among("i", -1, 15, None),
Among("ai", 7, 14, None),
Among("jai", 8, 11, None),
Among("ei", 7, 14, None),
Among("jei", 10, 11, None),
Among("\u{00E1}i", 7, 12, None),
Among("\u{00E9}i", 7, 13, None),
Among("itek", -1, 24, None),
Among("eitek", 14, 21, None),
Among("jeitek", 15, 20, None),
Among("\u{00E9}itek", 14, 23, None),
Among("ik", -1, 29, None),
Among("aik", 18, 26, None),
Among("jaik", 19, 25, None),
Among("eik", 18, 26, None),
Among("jeik", 21, 25, None),
Among("\u{00E1}ik", 18, 27, None),
Among("\u{00E9}ik", 18, 28, None),
Among("ink", -1, 20, None),
Among("aink", 25, 17, None),
Among("jaink", 26, 16, None),
Among("eink", 25, 17, None),
Among("jeink", 28, 16, None),
Among("\u{00E1}ink", 25, 18, None),
Among("\u{00E9}ink", 25, 19, None),
Among("aitok", -1, 21, None),
Among("jaitok", 32, 20, None),
Among("\u{00E1}itok", -1, 22, None),
Among("im", -1, 5, None),
Among("aim", 35, 4, None),
Among("jaim", 36, 1, None),
Among("eim", 35, 4, None),
Among("jeim", 38, 1, None),
Among("\u{00E1}im", 35, 2, None),
Among("\u{00E9}im", 35, 3, None),
];
static G_v: &'static [u8; 35] = &[17, 65, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 17, 36, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1];
#[derive(Clone)]
struct Context {
i_p1: usize,
}
fn r_mark_regions(env: &mut SnowballEnv, context: &mut Context) -> bool {
// (, line 44
context.i_p1 = env.limit;
// or, line 51
'lab0: loop {
let v_1 = env.cursor;
'lab1: loop {
// (, line 48
if !env.in_grouping(G_v, 97, 369) {
break 'lab1;
}
// goto, line 48
'golab2: loop {
let v_2 = env.cursor;
'lab3: loop {
if !env.out_grouping(G_v, 97, 369) {
break 'lab3;
}
env.cursor = v_2;
break 'golab2;
}
env.cursor = v_2;
if env.cursor >= env.limit {
break 'lab1;
}
env.next_char();
}
// or, line 49
'lab4: loop {
let v_3 = env.cursor;
'lab5: loop {
// among, line 49
if env.find_among(A_0, context) == 0 {
break 'lab5;
}
break 'lab4;
}
env.cursor = v_3;
// next, line 49
if env.cursor >= env.limit {
break 'lab1;
}
env.next_char();
break 'lab4;
}
// setmark p1, line 50
context.i_p1 = env.cursor;
break 'lab0;
}
env.cursor = v_1;
// (, line 53
if !env.out_grouping(G_v, 97, 369) {
return false;
}
// gopast, line 53
'golab6: loop {
'lab7: loop {
if !env.in_grouping(G_v, 97, 369) {
break 'lab7;
}
break 'golab6;
}
if env.cursor >= env.limit {
return false;
}
env.next_char();
}
// setmark p1, line 53
context.i_p1 = env.cursor;
break 'lab0;
}
return true;
}
fn r_R1(env: &mut SnowballEnv, context: &mut Context) -> bool {
if !(context.i_p1 <= env.cursor){
return false;
}
return true;
}
fn r_v_ending(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 60
// [, line 61
env.ket = env.cursor;
// substring, line 61
among_var = env.find_among_b(A_1, context);
if among_var == 0 {
return false;
}
// ], line 61
env.bra = env.cursor;
// call R1, line 61
if !r_R1(env, context) {
return false;
}
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 62
// <-, line 62
if !env.slice_from("a") {
return false;
}
} else if among_var == 2 {
// (, line 63
// <-, line 63
if !env.slice_from("e") {
return false;
}
}
return true;
}
fn r_double(env: &mut SnowballEnv, context: &mut Context) -> bool {
// (, line 67
// test, line 68
let v_1 = env.limit - env.cursor;
// among, line 68
if env.find_among_b(A_2, context) == 0 {
return false;
}
env.cursor = env.limit - v_1;
return true;
}
fn r_undouble(env: &mut SnowballEnv, context: &mut Context) -> bool {
// (, line 72
// next, line 73
if env.cursor <= env.limit_backward {
return false;
}
env.previous_char();
// [, line 73
env.ket = env.cursor;
// hop, line 73
let c = env.byte_index_for_hop(-1);
if env.limit_backward as i32 > c || c > env.limit as i32 {
return false;
}
env.cursor = c as usize;
// ], line 73
env.bra = env.cursor;
// delete, line 73
if !env.slice_del() {
return false;
}
return true;
}
fn r_instrum(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 76
// [, line 77
env.ket = env.cursor;
// substring, line 77
among_var = env.find_among_b(A_3, context);
if among_var == 0 {
return false;
}
// ], line 77
env.bra = env.cursor;
// call R1, line 77
if !r_R1(env, context) {
return false;
}
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 78
// call double, line 78
if !r_double(env, context) {
return false;
}
} else if among_var == 2 {
// (, line 79
// call double, line 79
if !r_double(env, context) {
return false;
}
}
// delete, line 81
if !env.slice_del() {
return false;
}
// call undouble, line 82
if !r_undouble(env, context) {
return false;
}
return true;
}
fn r_case(env: &mut SnowballEnv, context: &mut Context) -> bool {
// (, line 86
// [, line 87
env.ket = env.cursor;
// substring, line 87
if env.find_among_b(A_4, context) == 0 {
return false;
}
// ], line 87
env.bra = env.cursor;
// call R1, line 87
if !r_R1(env, context) {
return false;
}
// delete, line 111
if !env.slice_del() {
return false;
}
// call v_ending, line 112
if !r_v_ending(env, context) {
return false;
}
return true;
}
fn r_case_special(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 115
// [, line 116
env.ket = env.cursor;
// substring, line 116
among_var = env.find_among_b(A_5, context);
if among_var == 0 {
return false;
}
// ], line 116
env.bra = env.cursor;
// call R1, line 116
if !r_R1(env, context) {
return false;
}
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 117
// <-, line 117
if !env.slice_from("e") {
return false;
}
} else if among_var == 2 {
// (, line 118
// <-, line 118
if !env.slice_from("a") {
return false;
}
} else if among_var == 3 {
// (, line 119
// <-, line 119
if !env.slice_from("a") {
return false;
}
}
return true;
}
fn r_case_other(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 123
// [, line 124
env.ket = env.cursor;
// substring, line 124
among_var = env.find_among_b(A_6, context);
if among_var == 0 {
return false;
}
// ], line 124
env.bra = env.cursor;
// call R1, line 124
if !r_R1(env, context) {
return false;
}
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 125
// delete, line 125
if !env.slice_del() {
return false;
}
} else if among_var == 2 {
// (, line 126
// delete, line 126
if !env.slice_del() {
return false;
}
} else if among_var == 3 {
// (, line 127
// <-, line 127
if !env.slice_from("a") {
return false;
}
} else if among_var == 4 {
// (, line 128
// <-, line 128
if !env.slice_from("e") {
return false;
}
}
return true;
}
fn r_factive(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 132
// [, line 133
env.ket = env.cursor;
// substring, line 133
among_var = env.find_among_b(A_7, context);
if among_var == 0 {
return false;
}
// ], line 133
env.bra = env.cursor;
// call R1, line 133
if !r_R1(env, context) {
return false;
}
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 134
// call double, line 134
if !r_double(env, context) {
return false;
}
} else if among_var == 2 {
// (, line 135
// call double, line 135
if !r_double(env, context) {
return false;
}
}
// delete, line 137
if !env.slice_del() {
return false;
}
// call undouble, line 138
if !r_undouble(env, context) {
return false;
}
return true;
}
fn r_plural(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 141
// [, line 142
env.ket = env.cursor;
// substring, line 142
among_var = env.find_among_b(A_8, context);
if among_var == 0 {
return false;
}
// ], line 142
env.bra = env.cursor;
// call R1, line 142
if !r_R1(env, context) {
return false;
}
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 143
// <-, line 143
if !env.slice_from("a") {
return false;
}
} else if among_var == 2 {
// (, line 144
// <-, line 144
if !env.slice_from("e") {
return false;
}
} else if among_var == 3 {
// (, line 145
// delete, line 145
if !env.slice_del() {
return false;
}
} else if among_var == 4 {
// (, line 146
// delete, line 146
if !env.slice_del() {
return false;
}
} else if among_var == 5 {
// (, line 147
// delete, line 147
if !env.slice_del() {
return false;
}
} else if among_var == 6 {
// (, line 148
// delete, line 148
if !env.slice_del() {
return false;
}
} else if among_var == 7 {
// (, line 149
// delete, line 149
if !env.slice_del() {
return false;
}
}
return true;
}
fn r_owned(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 153
// [, line 154
env.ket = env.cursor;
// substring, line 154
among_var = env.find_among_b(A_9, context);
if among_var == 0 {
return false;
}
// ], line 154
env.bra = env.cursor;
// call R1, line 154
if !r_R1(env, context) {
return false;
}
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 155
// delete, line 155
if !env.slice_del() {
return false;
}
} else if among_var == 2 {
// (, line 156
// <-, line 156
if !env.slice_from("e") {
return false;
}
} else if among_var == 3 {
// (, line 157
// <-, line 157
if !env.slice_from("a") {
return false;
}
} else if among_var == 4 {
// (, line 158
// delete, line 158
if !env.slice_del() {
return false;
}
} else if among_var == 5 {
// (, line 159
// <-, line 159
if !env.slice_from("e") {
return false;
}
} else if among_var == 6 {
// (, line 160
// <-, line 160
if !env.slice_from("a") {
return false;
}
} else if among_var == 7 {
// (, line 161
// delete, line 161
if !env.slice_del() {
return false;
}
} else if among_var == 8 {
// (, line 162
// <-, line 162
if !env.slice_from("e") {
return false;
}
} else if among_var == 9 {
// (, line 163
// delete, line 163
if !env.slice_del() {
return false;
}
}
return true;
}
fn r_sing_owner(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 167
// [, line 168
env.ket = env.cursor;
// substring, line 168
among_var = env.find_among_b(A_10, context);
if among_var == 0 {
return false;
}
// ], line 168
env.bra = env.cursor;
// call R1, line 168
if !r_R1(env, context) {
return false;
}
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 169
// delete, line 169
if !env.slice_del() {
return false;
}
} else if among_var == 2 {
// (, line 170
// <-, line 170
if !env.slice_from("a") {
return false;
}
} else if among_var == 3 {
// (, line 171
// <-, line 171
if !env.slice_from("e") {
return false;
}
} else if among_var == 4 {
// (, line 172
// delete, line 172
if !env.slice_del() {
return false;
}
} else if among_var == 5 {
// (, line 173
// <-, line 173
if !env.slice_from("a") {
return false;
}
} else if among_var == 6 {
// (, line 174
// <-, line 174
if !env.slice_from("e") {
return false;
}
} else if among_var == 7 {
// (, line 175
// delete, line 175
if !env.slice_del() {
return false;
}
} else if among_var == 8 {
// (, line 176
// delete, line 176
if !env.slice_del() {
return false;
}
} else if among_var == 9 {
// (, line 177
// delete, line 177
if !env.slice_del() {
return false;
}
} else if among_var == 10 {
// (, line 178
// <-, line 178
if !env.slice_from("a") {
return false;
}
} else if among_var == 11 {
// (, line 179
// <-, line 179
if !env.slice_from("e") {
return false;
}
} else if among_var == 12 {
// (, line 180
// delete, line 180
if !env.slice_del() {
return false;
}
} else if among_var == 13 {
// (, line 181
// delete, line 181
if !env.slice_del() {
return false;
}
} else if among_var == 14 {
// (, line 182
// <-, line 182
if !env.slice_from("a") {
return false;
}
} else if among_var == 15 {
// (, line 183
// <-, line 183
if !env.slice_from("e") {
return false;
}
} else if among_var == 16 {
// (, line 184
// delete, line 184
if !env.slice_del() {
return false;
}
} else if among_var == 17 {
// (, line 185
// delete, line 185
if !env.slice_del() {
return false;
}
} else if among_var == 18 {
// (, line 186
// delete, line 186
if !env.slice_del() {
return false;
}
} else if among_var == 19 {
// (, line 187
// <-, line 187
if !env.slice_from("a") {
return false;
}
} else if among_var == 20 {
// (, line 188
// <-, line 188
if !env.slice_from("e") {
return false;
}
}
return true;
}
fn r_plur_owner(env: &mut SnowballEnv, context: &mut Context) -> bool {
let mut among_var;
// (, line 192
// [, line 193
env.ket = env.cursor;
// substring, line 193
among_var = env.find_among_b(A_11, context);
if among_var == 0 {
return false;
}
// ], line 193
env.bra = env.cursor;
// call R1, line 193
if !r_R1(env, context) {
return false;
}
if among_var == 0 {
return false;
} else if among_var == 1 {
// (, line 194
// delete, line 194
if !env.slice_del() {
return false;
}
} else if among_var == 2 {
// (, line 195
// <-, line 195
if !env.slice_from("a") {
return false;
}
} else if among_var == 3 {
// (, line 196
// <-, line 196
if !env.slice_from("e") {
return false;
}
} else if among_var == 4 {
// (, line 197
// delete, line 197
if !env.slice_del() {
return false;
}
} else if among_var == 5 {
// (, line 198
// delete, line 198
if !env.slice_del() {
return false;
}
} else if among_var == 6 {
// (, line 199
// delete, line 199
if !env.slice_del() {
return false;
}
} else if among_var == 7 {
// (, line 200
// <-, line 200
if !env.slice_from("a") {
return false;
}
} else if among_var == 8 {
// (, line 201
// <-, line 201
if !env.slice_from("e") {
return false;
}
} else if among_var == 9 {
// (, line 202
// delete, line 202
if !env.slice_del() {
return false;
}
} else if among_var == 10 {
// (, line 203
// delete, line 203
if !env.slice_del() {
return false;
}
} else if among_var == 11 {
// (, line 204
// delete, line 204
if !env.slice_del() {
return false;
}
} else if among_var == 12 {
// (, line 205
// <-, line 205
if !env.slice_from("a") {
return false;
}
} else if among_var == 13 {
// (, line 206
// <-, line 206
if !env.slice_from("e") {
return false;
}
} else if among_var == 14 {
// (, line 207
// delete, line 207
if !env.slice_del() {
return false;
}
} else if among_var == 15 {
// (, line 208
// delete, line 208
if !env.slice_del() {
return false;
}
} else if among_var == 16 {
// (, line 209
// delete, line 209
if !env.slice_del() {
return false;
}
} else if among_var == 17 {
// (, line 210
// delete, line 210
if !env.slice_del() {
return false;
}
} else if among_var == 18 {
// (, line 211
// <-, line 211
if !env.slice_from("a") {
return false;
}
} else if among_var == 19 {
// (, line 212
// <-, line 212
if !env.slice_from("e") {
return false;
}
} else if among_var == 20 {
// (, line 214
// delete, line 214
if !env.slice_del() {
return false;
}
} else if among_var == 21 {
// (, line 215
// delete, line 215
if !env.slice_del() {
return false;
}
} else if among_var == 22 {
// (, line 216
// <-, line 216
if !env.slice_from("a") {
return false;
}
} else if among_var == 23 {
// (, line 217
// <-, line 217
if !env.slice_from("e") {
return false;
}
} else if among_var == 24 {
// (, line 218
// delete, line 218
if !env.slice_del() {
return false;
}
} else if among_var == 25 {
// (, line 219
// delete, line 219
if !env.slice_del() {
return false;
}
} else if among_var == 26 {
// (, line 220
// delete, line 220
if !env.slice_del() {
return false;
}
} else if among_var == 27 {
// (, line 221
// <-, line 221
if !env.slice_from("a") {
return false;
}
} else if among_var == 28 {
// (, line 222
// <-, line 222
if !env.slice_from("e") {
return false;
}
} else if among_var == 29 {
// (, line 223
// delete, line 223
if !env.slice_del() {
return false;
}
}
return true;
}
pub fn stem(env: &mut SnowballEnv) -> bool {
let mut context = &mut Context {
i_p1: 0,
};
// (, line 228
// do, line 229
let v_1 = env.cursor;
'lab0: loop {
// call mark_regions, line 229
if !r_mark_regions(env, context) {
break 'lab0;
}
break 'lab0;
}
env.cursor = v_1;
// backwards, line 230
env.limit_backward = env.cursor;
env.cursor = env.limit;
// (, line 230
// do, line 231
let v_2 = env.limit - env.cursor;
'lab1: loop {
// call instrum, line 231
if !r_instrum(env, context) {
break 'lab1;
}
break 'lab1;
}
env.cursor = env.limit - v_2;
// do, line 232
let v_3 = env.limit - env.cursor;
'lab2: loop {
// call case, line 232
if !r_case(env, context) {
break 'lab2;
}
break 'lab2;
}
env.cursor = env.limit - v_3;
// do, line 233
let v_4 = env.limit - env.cursor;
'lab3: loop {
// call case_special, line 233
if !r_case_special(env, context) {
break 'lab3;
}
break 'lab3;
}
env.cursor = env.limit - v_4;
// do, line 234
let v_5 = env.limit - env.cursor;
'lab4: loop {
// call case_other, line 234
if !r_case_other(env, context) {
break 'lab4;
}
break 'lab4;
}
env.cursor = env.limit - v_5;
// do, line 235
let v_6 = env.limit - env.cursor;
'lab5: loop {
// call factive, line 235
if !r_factive(env, context) {
break 'lab5;
}
break 'lab5;
}
env.cursor = env.limit - v_6;
// do, line 236
let v_7 = env.limit - env.cursor;
'lab6: loop {
// call owned, line 236
if !r_owned(env, context) {
break 'lab6;
}
break 'lab6;
}
env.cursor = env.limit - v_7;
// do, line 237
let v_8 = env.limit - env.cursor;
'lab7: loop {
// call sing_owner, line 237
if !r_sing_owner(env, context) {
break 'lab7;
}
break 'lab7;
}
env.cursor = env.limit - v_8;
// do, line 238
let v_9 = env.limit - env.cursor;
'lab8: loop {
// call plur_owner, line 238
if !r_plur_owner(env, context) {
break 'lab8;
}
break 'lab8;
}
env.cursor = env.limit - v_9;
// do, line 239
let v_10 = env.limit - env.cursor;
'lab9: loop {
// call plural, line 239
if !r_plural(env, context) {
break 'lab9;
}
break 'lab9;
}
env.cursor = env.limit - v_10;
env.cursor = env.limit_backward;
return true;
}
| rust | MIT | 1fde09dfa08fb0fb07fbd6570aba8ecc98174edb | 2026-01-04T20:25:20.053159Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.