1use crate::error::{Result, SammError};
7use crate::metamodel::{Aspect, Characteristic, ModelElement, Property};
8
9pub mod urn {
11 use super::*;
12
13 pub fn extract_namespace(urn: &str) -> Result<String> {
25 validate_urn(urn)?;
26
27 if let Some(namespace) = crate::simd_ops::extract_namespace_fast(urn) {
29 return Ok(namespace.to_string());
30 }
31
32 let without_prefix = urn
34 .strip_prefix("urn:samm:")
35 .ok_or_else(|| SammError::InvalidUrn(format!("Invalid URN format: {}", urn)))?;
36
37 let parts: Vec<&str> = without_prefix.split('#').collect();
38 let namespace_version = parts
39 .first()
40 .ok_or_else(|| SammError::InvalidUrn("Missing namespace".to_string()))?;
41
42 let nv_parts: Vec<&str> = namespace_version.split(':').collect();
43 Ok(nv_parts
44 .first()
45 .ok_or_else(|| SammError::InvalidUrn("Missing namespace".to_string()))?
46 .to_string())
47 }
48
49 pub fn extract_version(urn: &str) -> Result<String> {
61 validate_urn(urn)?;
62
63 if let Some(version) = crate::simd_ops::extract_version_fast(urn) {
65 return Ok(version.to_string());
66 }
67
68 let without_prefix = urn
70 .strip_prefix("urn:samm:")
71 .ok_or_else(|| SammError::InvalidUrn(format!("Invalid URN format: {}", urn)))?;
72
73 let parts: Vec<&str> = without_prefix.split('#').collect();
74 let namespace_version = parts
75 .first()
76 .ok_or_else(|| SammError::InvalidUrn("Missing version".to_string()))?;
77
78 let nv_parts: Vec<&str> = namespace_version.split(':').collect();
79 Ok(nv_parts
80 .get(1)
81 .ok_or_else(|| SammError::InvalidUrn("Missing version".to_string()))?
82 .to_string())
83 }
84
85 pub fn extract_element(urn: &str) -> Result<String> {
97 validate_urn(urn)?;
98
99 if let Some(element) = crate::simd_ops::extract_element_fast(urn) {
101 return Ok(element.to_string());
102 }
103
104 let parts: Vec<&str> = urn.split('#').collect();
106 Ok(parts
107 .get(1)
108 .ok_or_else(|| SammError::InvalidUrn("Missing element name".to_string()))?
109 .to_string())
110 }
111
112 pub fn build_urn(namespace: &str, version: &str, element: &str) -> String {
122 format!("urn:samm:{}:{}#{}", namespace, version, element)
123 }
124
125 pub fn validate_urn(urn: &str) -> Result<()> {
129 if !urn.starts_with("urn:samm:") {
130 return Err(SammError::InvalidUrn(format!(
131 "URN must start with 'urn:samm:', got: {}",
132 urn
133 )));
134 }
135
136 let parts: Vec<&str> = urn.split('#').collect();
137 if parts.len() != 2 {
138 return Err(SammError::InvalidUrn(format!(
139 "URN must contain exactly one '#' separator, got: {}",
140 urn
141 )));
142 }
143
144 let namespace_version = parts[0]
145 .strip_prefix("urn:samm:")
146 .expect("URN should start with 'urn:samm:' prefix");
147 let nv_parts: Vec<&str> = namespace_version.split(':').collect();
148 if nv_parts.len() != 2 {
149 return Err(SammError::InvalidUrn(format!(
150 "URN must contain namespace and version separated by ':', got: {}",
151 urn
152 )));
153 }
154
155 if parts[1].is_empty() {
156 return Err(SammError::InvalidUrn(
157 "Element name cannot be empty".to_string(),
158 ));
159 }
160
161 Ok(())
162 }
163
164 pub fn is_same_element(urn1: &str, urn2: &str) -> bool {
166 urn1 == urn2
167 }
168
169 pub fn is_same_namespace(urn1: &str, urn2: &str) -> Result<bool> {
171 let ns1 = extract_namespace(urn1)?;
172 let ns2 = extract_namespace(urn2)?;
173 Ok(ns1 == ns2)
174 }
175}
176
177pub mod naming {
179 pub fn to_camel_case(s: &str) -> String {
189 if s.is_empty() {
190 return String::new();
191 }
192
193 let mut chars = s.chars();
194 let first = chars
195 .next()
196 .expect("string should not be empty")
197 .to_lowercase()
198 .to_string();
199 first + chars.as_str()
200 }
201
202 pub fn to_pascal_case(s: &str) -> String {
212 if s.is_empty() {
213 return String::new();
214 }
215
216 let mut chars = s.chars();
217 let first = chars
218 .next()
219 .expect("string should not be empty")
220 .to_uppercase()
221 .to_string();
222 first + chars.as_str()
223 }
224
225 pub fn to_snake_case(s: &str) -> String {
236 let mut result = String::new();
237 let mut chars = s.chars().peekable();
238
239 while let Some(ch) = chars.next() {
240 if ch.is_uppercase() {
241 if !result.is_empty() && chars.peek().is_some_and(|c| c.is_lowercase()) {
242 result.push('_');
243 }
244 result.push(
245 ch.to_lowercase()
246 .next()
247 .expect("to_lowercase should yield at least one char"),
248 );
249 } else {
250 result.push(ch);
251 }
252 }
253
254 result
255 }
256
257 pub fn is_valid_property_name(name: &str) -> bool {
261 if name.is_empty() {
262 return false;
263 }
264
265 let first_char = name.chars().next().expect("name should not be empty");
266 if !first_char.is_lowercase() && !first_char.is_ascii_digit() {
267 return false;
268 }
269
270 name.chars().all(|c| c.is_alphanumeric())
271 }
272
273 pub fn is_valid_characteristic_name(name: &str) -> bool {
275 if name.is_empty() {
276 return false;
277 }
278
279 let first_char = name.chars().next().expect("name should not be empty");
280 if !first_char.is_uppercase() {
281 return false;
282 }
283
284 name.chars().all(|c| c.is_alphanumeric())
285 }
286}
287
288pub mod inspection {
290 use super::*;
291
292 pub fn get_property_names(aspect: &Aspect) -> Vec<String> {
304 aspect.properties().iter().map(|p| p.name()).collect()
305 }
306
307 pub fn find_property<'a>(aspect: &'a Aspect, name: &str) -> Option<&'a Property> {
309 aspect.properties().iter().find(|p| p.name() == name)
310 }
311
312 pub fn has_property(aspect: &Aspect, name: &str) -> bool {
314 find_property(aspect, name).is_some()
315 }
316
317 pub fn get_required_properties(aspect: &Aspect) -> Vec<&Property> {
319 aspect.properties().iter().filter(|p| !p.optional).collect()
320 }
321
322 pub fn get_optional_properties(aspect: &Aspect) -> Vec<&Property> {
324 aspect.properties().iter().filter(|p| p.optional).collect()
325 }
326
327 pub fn count_properties(aspect: &Aspect) -> usize {
329 aspect.properties().len()
330 }
331
332 pub fn get_property_data_type(property: &Property) -> Option<String> {
334 property
335 .characteristic
336 .as_ref()
337 .and_then(|c| c.data_type.clone())
338 }
339
340 pub fn is_collection_characteristic(characteristic: &Characteristic) -> bool {
342 matches!(
343 characteristic.kind(),
344 crate::metamodel::CharacteristicKind::Collection { .. }
345 | crate::metamodel::CharacteristicKind::List { .. }
346 | crate::metamodel::CharacteristicKind::Set { .. }
347 | crate::metamodel::CharacteristicKind::SortedSet { .. }
348 )
349 }
350}
351
352pub mod datatypes {
354 pub fn is_numeric_type(xsd_type: &str) -> bool {
356 matches!(
357 xsd_type,
358 "xsd:int"
359 | "xsd:integer"
360 | "xsd:long"
361 | "xsd:short"
362 | "xsd:byte"
363 | "xsd:float"
364 | "xsd:double"
365 | "xsd:decimal"
366 | "xsd:positiveInteger"
367 | "xsd:negativeInteger"
368 | "xsd:nonNegativeInteger"
369 | "xsd:nonPositiveInteger"
370 | "xsd:unsignedLong"
371 | "xsd:unsignedInt"
372 | "xsd:unsignedShort"
373 | "xsd:unsignedByte"
374 )
375 }
376
377 pub fn is_string_type(xsd_type: &str) -> bool {
379 matches!(
380 xsd_type,
381 "xsd:string" | "xsd:token" | "xsd:normalizedString"
382 )
383 }
384
385 pub fn is_datetime_type(xsd_type: &str) -> bool {
387 matches!(
388 xsd_type,
389 "xsd:date" | "xsd:dateTime" | "xsd:time" | "xsd:gYear" | "xsd:gYearMonth"
390 )
391 }
392
393 pub fn is_boolean_type(xsd_type: &str) -> bool {
395 xsd_type == "xsd:boolean"
396 }
397
398 pub fn xsd_to_rust_type(xsd_type: &str) -> &'static str {
400 match xsd_type {
401 "xsd:int" | "xsd:integer" => "i32",
402 "xsd:long" => "i64",
403 "xsd:short" => "i16",
404 "xsd:byte" => "i8",
405 "xsd:unsignedInt" => "u32",
406 "xsd:unsignedLong" => "u64",
407 "xsd:unsignedShort" => "u16",
408 "xsd:unsignedByte" => "u8",
409 "xsd:float" => "f32",
410 "xsd:double" | "xsd:decimal" => "f64",
411 "xsd:boolean" => "bool",
412 "xsd:string" | "xsd:token" | "xsd:normalizedString" => "String",
413 "xsd:dateTime" | "xsd:date" | "xsd:time" => "String", _ => "String", }
416 }
417}
418
419pub mod statistics {
421 use super::*;
422
423 #[derive(Debug, Clone)]
425 pub struct ModelStatistics {
426 pub total_properties: usize,
428 pub required_properties: usize,
430 pub optional_properties: usize,
432 pub total_operations: usize,
434 pub total_events: usize,
436 pub properties_with_characteristics: usize,
438 pub properties_with_examples: usize,
440 }
441
442 pub fn calculate_statistics(aspect: &Aspect) -> ModelStatistics {
457 let total_properties = aspect.properties.len();
458 let required_properties = aspect.properties.iter().filter(|p| !p.optional).count();
459 let optional_properties = aspect.properties.iter().filter(|p| p.optional).count();
460 let properties_with_characteristics = aspect
461 .properties
462 .iter()
463 .filter(|p| p.characteristic.is_some())
464 .count();
465 let properties_with_examples = aspect
466 .properties
467 .iter()
468 .filter(|p| !p.example_values.is_empty())
469 .count();
470
471 ModelStatistics {
472 total_properties,
473 required_properties,
474 optional_properties,
475 total_operations: aspect.operations.len(),
476 total_events: aspect.events.len(),
477 properties_with_characteristics,
478 properties_with_examples,
479 }
480 }
481
482 pub fn required_ratio(aspect: &Aspect) -> f64 {
484 let stats = calculate_statistics(aspect);
485 if stats.total_properties == 0 {
486 0.0
487 } else {
488 stats.required_properties as f64 / stats.total_properties as f64
489 }
490 }
491
492 pub fn optional_ratio(aspect: &Aspect) -> f64 {
494 let stats = calculate_statistics(aspect);
495 if stats.total_properties == 0 {
496 0.0
497 } else {
498 stats.optional_properties as f64 / stats.total_properties as f64
499 }
500 }
501}
502
503pub mod serialization {
505 use super::*;
506 use serde_json;
507
508 pub fn to_json_string(aspect: &Aspect) -> Result<String> {
521 serde_json::to_string(aspect)
522 .map_err(|e| SammError::Other(format!("JSON serialization failed: {}", e)))
523 }
524
525 pub fn to_json_pretty(aspect: &Aspect) -> Result<String> {
527 serde_json::to_string_pretty(aspect)
528 .map_err(|e| SammError::Other(format!("JSON serialization failed: {}", e)))
529 }
530
531 pub fn from_json_string(json: &str) -> Result<Aspect> {
533 serde_json::from_str(json)
534 .map_err(|e| SammError::Other(format!("JSON deserialization failed: {}", e)))
535 }
536}
537
538pub mod batch {
540 use super::*;
541
542 pub fn make_all_optional(aspect: &mut Aspect) {
556 for property in &mut aspect.properties {
557 property.optional = true;
558 }
559 }
560
561 pub fn make_all_required(aspect: &mut Aspect) {
563 for property in &mut aspect.properties {
564 property.optional = false;
565 }
566 }
567
568 pub fn set_example_values(aspect: &mut Aspect, default_value: &str) {
570 for property in &mut aspect.properties {
571 if property.example_values.is_empty() {
572 property.example_values = vec![default_value.to_string()];
573 }
574 }
575 }
576
577 pub fn clear_example_values(aspect: &mut Aspect) {
579 for property in &mut aspect.properties {
580 property.example_values.clear();
581 }
582 }
583
584 pub fn apply_to_all_properties<F>(aspect: &mut Aspect, mut f: F)
586 where
587 F: FnMut(&mut Property),
588 {
589 for property in &mut aspect.properties {
590 f(property);
591 }
592 }
593
594 pub fn filter_properties<F>(aspect: &Aspect, predicate: F) -> Aspect
596 where
597 F: Fn(&Property) -> bool,
598 {
599 let filtered_properties: Vec<Property> = aspect
600 .properties
601 .iter()
602 .filter(|p| predicate(p))
603 .cloned()
604 .collect();
605
606 Aspect {
607 metadata: aspect.metadata.clone(),
608 properties: filtered_properties,
609 operations: aspect.operations.clone(),
610 events: aspect.events.clone(),
611 }
612 }
613}
614
615pub mod merging {
617 use super::*;
618 use std::collections::HashSet;
619
620 pub fn merge_aspects(first: &Aspect, second: &Aspect) -> Aspect {
625 let mut merged = first.clone();
626
627 let existing_urns: HashSet<String> = merged
629 .properties
630 .iter()
631 .map(|p| p.urn().to_owned())
632 .collect();
633
634 for property in &second.properties {
636 if !existing_urns.contains(property.urn()) {
637 merged.properties.push(property.clone());
638 }
639 }
640
641 let existing_op_urns: HashSet<String> = merged
643 .operations
644 .iter()
645 .map(|o| o.urn().to_owned())
646 .collect();
647
648 for operation in &second.operations {
649 if !existing_op_urns.contains(operation.urn()) {
650 merged.operations.push(operation.clone());
651 }
652 }
653
654 let existing_event_urns: HashSet<String> =
656 merged.events.iter().map(|e| e.urn().to_owned()).collect();
657
658 for event in &second.events {
659 if !existing_event_urns.contains(event.urn()) {
660 merged.events.push(event.clone());
661 }
662 }
663
664 merged
665 }
666
667 pub fn deep_clone(aspect: &Aspect) -> Aspect {
669 aspect.clone()
670 }
671}
672
673pub mod diff {
675 use super::*;
676
677 #[derive(Debug, Clone)]
679 pub struct QuickDiff {
680 pub properties_added: usize,
682 pub properties_removed: usize,
684 pub properties_modified: usize,
686 pub operations_added: usize,
688 pub operations_removed: usize,
690 }
691
692 pub fn quick_diff(old: &Aspect, new: &Aspect) -> QuickDiff {
696 use std::collections::HashSet;
697
698 let old_prop_urns: HashSet<_> = old.properties.iter().map(|p| p.urn()).collect();
699 let new_prop_urns: HashSet<_> = new.properties.iter().map(|p| p.urn()).collect();
700
701 let properties_added = new_prop_urns.difference(&old_prop_urns).count();
702 let properties_removed = old_prop_urns.difference(&new_prop_urns).count();
703
704 let common_urns: Vec<_> = old_prop_urns.intersection(&new_prop_urns).collect();
706 let mut properties_modified = 0;
707
708 for urn in common_urns {
709 let old_prop = old
710 .properties
711 .iter()
712 .find(|p| p.urn() == *urn)
713 .expect("property should exist in old aspect");
714 let new_prop = new
715 .properties
716 .iter()
717 .find(|p| p.urn() == *urn)
718 .expect("property should exist in new aspect");
719
720 if old_prop.optional != new_prop.optional
721 || old_prop.example_values != new_prop.example_values
722 {
723 properties_modified += 1;
724 }
725 }
726
727 let old_op_urns: HashSet<_> = old.operations.iter().map(|o| o.urn()).collect();
728 let new_op_urns: HashSet<_> = new.operations.iter().map(|o| o.urn()).collect();
729
730 let operations_added = new_op_urns.difference(&old_op_urns).count();
731 let operations_removed = old_op_urns.difference(&new_op_urns).count();
732
733 QuickDiff {
734 properties_added,
735 properties_removed,
736 properties_modified,
737 operations_added,
738 operations_removed,
739 }
740 }
741
742 pub fn are_identical(first: &Aspect, second: &Aspect) -> bool {
744 let diff = quick_diff(first, second);
745 diff.properties_added == 0
746 && diff.properties_removed == 0
747 && diff.properties_modified == 0
748 && diff.operations_added == 0
749 && diff.operations_removed == 0
750 }
751}
752
753#[cfg(test)]
754mod tests {
755 use super::*;
756
757 #[test]
758 fn test_extract_namespace() {
759 let urn = "urn:samm:org.eclipse.examples:1.0.0#Movement";
760 assert_eq!(
761 urn::extract_namespace(urn).expect("operation should succeed"),
762 "org.eclipse.examples"
763 );
764 }
765
766 #[test]
767 fn test_extract_version() {
768 let urn = "urn:samm:org.eclipse.examples:1.0.0#Movement";
769 assert_eq!(
770 urn::extract_version(urn).expect("operation should succeed"),
771 "1.0.0"
772 );
773 }
774
775 #[test]
776 fn test_extract_element() {
777 let urn = "urn:samm:org.eclipse.examples:1.0.0#Movement";
778 assert_eq!(
779 urn::extract_element(urn).expect("operation should succeed"),
780 "Movement"
781 );
782 }
783
784 #[test]
785 fn test_build_urn() {
786 let urn = urn::build_urn("org.eclipse.examples", "1.0.0", "Movement");
787 assert_eq!(urn, "urn:samm:org.eclipse.examples:1.0.0#Movement");
788 }
789
790 #[test]
791 fn test_validate_urn_valid() {
792 assert!(urn::validate_urn("urn:samm:org.eclipse:1.0.0#Test").is_ok());
793 }
794
795 #[test]
796 fn test_validate_urn_invalid_prefix() {
797 assert!(urn::validate_urn("urn:other:org.eclipse:1.0.0#Test").is_err());
798 }
799
800 #[test]
801 fn test_validate_urn_missing_hash() {
802 assert!(urn::validate_urn("urn:samm:org.eclipse:1.0.0").is_err());
803 }
804
805 #[test]
806 fn test_is_same_namespace() {
807 let urn1 = "urn:samm:org.eclipse:1.0.0#Test1";
808 let urn2 = "urn:samm:org.eclipse:2.0.0#Test2";
809 assert!(urn::is_same_namespace(urn1, urn2).expect("operation should succeed"));
810 }
811
812 #[test]
813 fn test_to_camel_case() {
814 assert_eq!(naming::to_camel_case("Movement"), "movement");
815 assert_eq!(naming::to_camel_case("IsMoving"), "isMoving");
816 }
817
818 #[test]
819 fn test_to_pascal_case() {
820 assert_eq!(naming::to_pascal_case("movement"), "Movement");
821 assert_eq!(naming::to_pascal_case("isMoving"), "IsMoving");
822 }
823
824 #[test]
825 fn test_to_snake_case() {
826 assert_eq!(naming::to_snake_case("Movement"), "movement");
827 assert_eq!(naming::to_snake_case("IsMoving"), "is_moving");
828 assert_eq!(naming::to_snake_case("HTTPResponse"), "http_response");
829 }
830
831 #[test]
832 fn test_is_valid_property_name() {
833 assert!(naming::is_valid_property_name("movement"));
834 assert!(naming::is_valid_property_name("isMoving"));
835 assert!(!naming::is_valid_property_name("Movement"));
836 assert!(!naming::is_valid_property_name(""));
837 assert!(!naming::is_valid_property_name("is-moving"));
838 }
839
840 #[test]
841 fn test_is_valid_characteristic_name() {
842 assert!(naming::is_valid_characteristic_name("Movement"));
843 assert!(naming::is_valid_characteristic_name("IsMoving"));
844 assert!(!naming::is_valid_characteristic_name("movement"));
845 assert!(!naming::is_valid_characteristic_name(""));
846 }
847
848 #[test]
849 fn test_is_numeric_type() {
850 assert!(datatypes::is_numeric_type("xsd:int"));
851 assert!(datatypes::is_numeric_type("xsd:float"));
852 assert!(datatypes::is_numeric_type("xsd:double"));
853 assert!(!datatypes::is_numeric_type("xsd:string"));
854 }
855
856 #[test]
857 fn test_is_string_type() {
858 assert!(datatypes::is_string_type("xsd:string"));
859 assert!(datatypes::is_string_type("xsd:token"));
860 assert!(!datatypes::is_string_type("xsd:int"));
861 }
862
863 #[test]
864 fn test_is_datetime_type() {
865 assert!(datatypes::is_datetime_type("xsd:date"));
866 assert!(datatypes::is_datetime_type("xsd:dateTime"));
867 assert!(!datatypes::is_datetime_type("xsd:string"));
868 }
869
870 #[test]
871 fn test_is_boolean_type() {
872 assert!(datatypes::is_boolean_type("xsd:boolean"));
873 assert!(!datatypes::is_boolean_type("xsd:string"));
874 }
875
876 #[test]
877 fn test_xsd_to_rust_type() {
878 assert_eq!(datatypes::xsd_to_rust_type("xsd:int"), "i32");
879 assert_eq!(datatypes::xsd_to_rust_type("xsd:long"), "i64");
880 assert_eq!(datatypes::xsd_to_rust_type("xsd:double"), "f64");
881 assert_eq!(datatypes::xsd_to_rust_type("xsd:boolean"), "bool");
882 assert_eq!(datatypes::xsd_to_rust_type("xsd:string"), "String");
883 }
884
885 #[test]
886 fn test_model_statistics() {
887 let mut aspect = Aspect::new("urn:samm:test:1.0.0#Test".to_string());
888 aspect.add_property(Property::new("urn:samm:test:1.0.0#prop1".to_string()));
889 aspect.add_property(Property::new("urn:samm:test:1.0.0#prop2".to_string()).as_optional());
890
891 let stats = statistics::calculate_statistics(&aspect);
892 assert_eq!(stats.total_properties, 2);
893 assert_eq!(stats.required_properties, 1);
894 assert_eq!(stats.optional_properties, 1);
895 }
896
897 #[test]
898 fn test_serialization_to_json() {
899 let aspect = Aspect::new("urn:samm:test:1.0.0#Test".to_string());
900
901 let json = serialization::to_json_string(&aspect).expect("operation should succeed");
902 assert!(json.contains("Test"));
903 assert!(json.contains("urn:samm:test:1.0.0"));
904 }
905
906 #[test]
907 fn test_batch_operations() {
908 let mut aspect = Aspect::new("urn:samm:test:1.0.0#Test".to_string());
909 aspect.add_property(Property::new("urn:samm:test:1.0.0#prop1".to_string()));
910 aspect.add_property(Property::new("urn:samm:test:1.0.0#prop2".to_string()));
911
912 batch::make_all_optional(&mut aspect);
913 assert!(aspect.properties.iter().all(|p| p.optional));
914 }
915}