Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add Rust support #46

Merged
merged 8 commits into from
Jan 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion rust/.gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
target
target
src/_data
82 changes: 82 additions & 0 deletions rust/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@ name = "kuliya"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
serde = { version = "1.0.194", features = ["derive"] }
serde_json = "1.0.110"
19 changes: 19 additions & 0 deletions rust/build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
use std::{fs, io, path::Path};

fn copy_dir_all(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> io::Result<()> {
fs::create_dir_all(&dst)?;
for entry in fs::read_dir(src)? {
let entry = entry?;
let ty = entry.file_type()?;
if ty.is_dir() {
copy_dir_all(entry.path(), dst.as_ref().join(entry.file_name()))?;
} else {
fs::copy(entry.path(), dst.as_ref().join(entry.file_name()))?;
}
}
Ok(())
}

fn main() {
copy_dir_all(Path::new("../_data"), Path::new("./src/_data")).unwrap();
}
207 changes: 200 additions & 7 deletions rust/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,207 @@
pub fn add(left: usize, right: usize) -> usize {
left + right
use std::fs;

use serde::{Deserialize, Serialize};
use serde_json::json;

static DATA_FOLDER: &'static str = "src/_data";
static CARGO_MANIFEST_DIR: &'static str = env!("CARGO_MANIFEST_DIR");

#[derive(Debug, Serialize, Deserialize)]
pub struct Name {
pub ar: String,
pub en: String,
pub fr: String,
}

impl std::fmt::Display for Name {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let obj = json!({"ar": self.ar, "en": self.en, "fr": self.fr});
write!(f, "{}", serde_json::to_string_pretty(&obj).unwrap())
}
}

#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub enum Type {
#[serde(rename = "UNIVERSITY")]
University,
#[serde(rename = "ACADEMY")]
Academy,
#[serde(rename = "PRIVATE_SCHOOL")]
PrivateSchool,
#[serde(rename = "INSTITUTE")]
Institute,
#[serde(rename = "FACULTY")]
Faculty,
#[serde(rename = "DEPARTMENT")]
Department,
#[serde(rename = "SPECIALTY")]
Specialty,
#[serde(rename = "SECTOR")]
Sector,
}

impl std::fmt::Display for Type {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Type::University => write!(f, "UNIVERSITY"),
Type::Academy => write!(f, "ACADEMY"),
Type::PrivateSchool => write!(f, "PRIVATE_SCHOOL"),
Type::Institute => write!(f, "INSTITUTE"),
Type::Faculty => write!(f, "FACULTY"),
Type::Department => write!(f, "DEPARTMENT"),
Type::Specialty => write!(f, "SPECIALTY"),
Type::Sector => write!(f, "SECTOR"),
}
}
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct Terms {
#[serde(rename = "perYear")]
pub per_year: usize,
pub slots: Vec<usize>,
}

impl std::fmt::Display for Terms {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let obj = json!({"perYear": self.per_year, "slots": self.slots});
write!(f, "{}", serde_json::to_string_pretty(&obj).unwrap())
}
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Schema {
pub name: Name,
pub r#type: Type,
pub terms: Option<Terms>,
ZibanPirate marked this conversation as resolved.
Show resolved Hide resolved
}

impl std::fmt::Display for Schema {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.terms.is_some() {
let obj = json!({
"name": self.name,
"type": self.r#type,
"terms": self.terms.clone().unwrap()
});
return write!(f, "{}", serde_json::to_string_pretty(&obj).unwrap());
} else {
let obj = json!({
"name": self.name,
"type": self.r#type
});
return write!(f, "{}", serde_json::to_string_pretty(&obj).unwrap());
}
}
}

pub fn get_node_by_path(path: &str) -> Option<Schema> {
let fs_path = format!("{}/{}/{}/info.json", CARGO_MANIFEST_DIR, DATA_FOLDER, path);
let Ok(info) = fs::read_to_string(fs_path) else {
return None;
};
let Ok(schema) = serde_json::from_str::<Schema>(info.as_str()) else {
return None;
};
Some(schema)
}

#[cfg(test)]
mod tests {
use super::*;
mod test {
use crate::{get_node_by_path, Name, Schema, Terms, Type};

struct TestCase<'a> {
path: &'a str,
expected: Schema,
}

impl<'a> TestCase<'a> {
pub fn new(path: &'a str, expected: Schema) -> Self {
Self { path, expected }
}
}

#[test]
fn should_get_expected_info() {
let tests: Vec<TestCase> = vec![
TestCase::new(
"umkb",
Schema {
name: Name {
ar: "جامعة محمد خيضر بسكرة".to_string(),
en: "University of Mohamed Khider Biskra".to_string(),
fr: "Université Mohamed Khider Biskra".to_string(),
},
r#type: Type::University,
terms: None,
},
),
TestCase::new(
"umkb/fst",
Schema {
name: Name {
ar: "كلية العلوم والتكنلوجيا".to_string(),
en: "Faculty of Science and Technology".to_string(),
fr: "Faculté des Sciences et de la Technologie".to_string(),
},
r#type: Type::Faculty,
terms: None,
},
),
TestCase::new(
"umkb/fst/dee/sec",
Schema {
name: Name {
ar: "تخصص التحكم الكهربائي".to_string(),
en: "Specialy of Electrical Control".to_string(),
fr: "Spécialité de commande électrique".to_string(),
},
r#type: Type::Specialty,
terms: Some(Terms {
per_year: 2,
slots: vec![7, 8, 9, 10],
}),
},
),
];

for tc in tests {
let actual = get_node_by_path(tc.path).unwrap();
assert_schema(&tc.expected, &actual);
}
}

#[test]
fn it_works() {
let result = add(2, 2);
assert_eq!(result, 4);
fn should_get_none_when_path_does_not_exist() {
let res = get_node_by_path("does/not/exist");
assert!(res.is_none());
}

fn assert_schema(expected: &Schema, actual: &Schema) {
assert_eq!(
expected.name.ar, actual.name.ar,
"Expected ar name to be '{}', but got '{}'",
expected.name.ar, actual.name.ar
);
assert_eq!(
expected.name.en, actual.name.en,
"Expected en name to be '{}', but got '{}'",
expected.name.en, actual.name.en
);
assert_eq!(
expected.name.fr, actual.name.fr,
"Expected fr name to be '{}', but got '{}'",
expected.name.fr, actual.name.fr
);
assert_eq!(
expected.r#type, actual.r#type,
"Expected ty to be '{:?}', but got '{:?}'",
expected.r#type, actual.r#type
);
assert_eq!(
expected.terms, actual.terms,
"Expeted terms to be '{:?}', but got '{:?}'",
expected.terms, actual.terms
)
}
}