Skip to main content

oxirs_samm/
utils.rs

1//! Utility functions for common SAMM operations
2//!
3//! This module provides helper functions that simplify common tasks when working
4//! with SAMM models, including URN manipulation, naming conventions, and data type handling.
5
6use crate::error::{Result, SammError};
7use crate::metamodel::{Aspect, Characteristic, ModelElement, Property};
8
9/// URN manipulation utilities
10pub mod urn {
11    use super::*;
12
13    /// Extract the namespace from a SAMM URN
14    ///
15    /// Uses SIMD-accelerated extraction for optimal performance.
16    ///
17    /// # Example
18    /// ```
19    /// use oxirs_samm::utils::urn::extract_namespace;
20    ///
21    /// let namespace = extract_namespace("urn:samm:org.eclipse.examples:1.0.0#Movement").expect("URN should be valid");
22    /// assert_eq!(namespace, "org.eclipse.examples");
23    /// ```
24    pub fn extract_namespace(urn: &str) -> Result<String> {
25        validate_urn(urn)?;
26
27        // Use SIMD-accelerated extraction when possible
28        if let Some(namespace) = crate::simd_ops::extract_namespace_fast(urn) {
29            return Ok(namespace.to_string());
30        }
31
32        // Fallback to manual parsing
33        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    /// Extract the version from a SAMM URN
50    ///
51    /// Uses SIMD-accelerated extraction for optimal performance.
52    ///
53    /// # Example
54    /// ```
55    /// use oxirs_samm::utils::urn::extract_version;
56    ///
57    /// let version = extract_version("urn:samm:org.eclipse.examples:1.0.0#Movement").expect("URN should be valid");
58    /// assert_eq!(version, "1.0.0");
59    /// ```
60    pub fn extract_version(urn: &str) -> Result<String> {
61        validate_urn(urn)?;
62
63        // Use SIMD-accelerated extraction when possible
64        if let Some(version) = crate::simd_ops::extract_version_fast(urn) {
65            return Ok(version.to_string());
66        }
67
68        // Fallback to manual parsing
69        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    /// Extract the element name from a SAMM URN
86    ///
87    /// Uses SIMD-accelerated extraction for optimal performance.
88    ///
89    /// # Example
90    /// ```
91    /// use oxirs_samm::utils::urn::extract_element;
92    ///
93    /// let element = extract_element("urn:samm:org.eclipse.examples:1.0.0#Movement").expect("URN should be valid");
94    /// assert_eq!(element, "Movement");
95    /// ```
96    pub fn extract_element(urn: &str) -> Result<String> {
97        validate_urn(urn)?;
98
99        // Use SIMD-accelerated extraction when possible
100        if let Some(element) = crate::simd_ops::extract_element_fast(urn) {
101            return Ok(element.to_string());
102        }
103
104        // Fallback to manual parsing
105        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    /// Build a SAMM URN from its components
113    ///
114    /// # Example
115    /// ```
116    /// use oxirs_samm::utils::urn::build_urn;
117    ///
118    /// let urn = build_urn("org.eclipse.examples", "1.0.0", "Movement");
119    /// assert_eq!(urn, "urn:samm:org.eclipse.examples:1.0.0#Movement");
120    /// ```
121    pub fn build_urn(namespace: &str, version: &str, element: &str) -> String {
122        format!("urn:samm:{}:{}#{}", namespace, version, element)
123    }
124
125    /// Validate a SAMM URN format
126    ///
127    /// Returns `Ok(())` if the URN is valid, otherwise returns an error with details.
128    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    /// Check if two URNs refer to the same element
165    pub fn is_same_element(urn1: &str, urn2: &str) -> bool {
166        urn1 == urn2
167    }
168
169    /// Check if two URNs are in the same namespace
170    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
177/// Naming convention utilities
178pub mod naming {
179    /// Convert PascalCase to camelCase
180    ///
181    /// # Example
182    /// ```
183    /// use oxirs_samm::utils::naming::to_camel_case;
184    ///
185    /// assert_eq!(to_camel_case("Movement"), "movement");
186    /// assert_eq!(to_camel_case("IsMoving"), "isMoving");
187    /// ```
188    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    /// Convert camelCase to PascalCase
203    ///
204    /// # Example
205    /// ```
206    /// use oxirs_samm::utils::naming::to_pascal_case;
207    ///
208    /// assert_eq!(to_pascal_case("movement"), "Movement");
209    /// assert_eq!(to_pascal_case("isMoving"), "IsMoving");
210    /// ```
211    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    /// Convert to snake_case
226    ///
227    /// # Example
228    /// ```
229    /// use oxirs_samm::utils::naming::to_snake_case;
230    ///
231    /// assert_eq!(to_snake_case("Movement"), "movement");
232    /// assert_eq!(to_snake_case("IsMoving"), "is_moving");
233    /// assert_eq!(to_snake_case("HTTPResponse"), "http_response");
234    /// ```
235    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    /// Validate that a name follows SAMM naming conventions
258    ///
259    /// Properties should be camelCase, Characteristics and Entities should be PascalCase
260    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    /// Validate that a name follows PascalCase convention
274    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
288/// Model inspection utilities
289pub mod inspection {
290    use super::*;
291
292    /// Get all property names from an Aspect
293    ///
294    /// # Example
295    /// ```no_run
296    /// use oxirs_samm::utils::inspection::get_property_names;
297    /// # use oxirs_samm::metamodel::Aspect;
298    /// # fn example(aspect: &Aspect) {
299    /// let names = get_property_names(aspect);
300    /// println!("Properties: {:?}", names);
301    /// # }
302    /// ```
303    pub fn get_property_names(aspect: &Aspect) -> Vec<String> {
304        aspect.properties().iter().map(|p| p.name()).collect()
305    }
306
307    /// Find a property by name in an Aspect
308    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    /// Check if an Aspect has a specific property
313    pub fn has_property(aspect: &Aspect, name: &str) -> bool {
314        find_property(aspect, name).is_some()
315    }
316
317    /// Get all required properties (non-optional) from an Aspect
318    pub fn get_required_properties(aspect: &Aspect) -> Vec<&Property> {
319        aspect.properties().iter().filter(|p| !p.optional).collect()
320    }
321
322    /// Get all optional properties from an Aspect
323    pub fn get_optional_properties(aspect: &Aspect) -> Vec<&Property> {
324        aspect.properties().iter().filter(|p| p.optional).collect()
325    }
326
327    /// Count total properties in an Aspect
328    pub fn count_properties(aspect: &Aspect) -> usize {
329        aspect.properties().len()
330    }
331
332    /// Get the data type of a property's characteristic
333    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    /// Check if a characteristic is a collection type
341    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
352/// Data type utilities
353pub mod datatypes {
354    /// Check if an XSD type is numeric
355    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    /// Check if an XSD type is a string type
378    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    /// Check if an XSD type is a date/time type
386    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    /// Check if an XSD type is a boolean
394    pub fn is_boolean_type(xsd_type: &str) -> bool {
395        xsd_type == "xsd:boolean"
396    }
397
398    /// Get the Rust equivalent type for an XSD type
399    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", // Would use chrono in real code
414            _ => "String",                                        // Default fallback
415        }
416    }
417}
418
419/// Model statistics utilities
420pub mod statistics {
421    use super::*;
422
423    /// Model statistics
424    #[derive(Debug, Clone)]
425    pub struct ModelStatistics {
426        /// Total number of properties
427        pub total_properties: usize,
428        /// Number of required properties
429        pub required_properties: usize,
430        /// Number of optional properties
431        pub optional_properties: usize,
432        /// Number of operations
433        pub total_operations: usize,
434        /// Number of events
435        pub total_events: usize,
436        /// Properties with characteristics
437        pub properties_with_characteristics: usize,
438        /// Properties with example values
439        pub properties_with_examples: usize,
440    }
441
442    /// Calculate comprehensive statistics for an aspect model
443    ///
444    /// # Example
445    /// ```
446    /// use oxirs_samm::metamodel::{Aspect, Property};
447    /// use oxirs_samm::utils::statistics::calculate_statistics;
448    ///
449    /// let mut aspect = Aspect::new("urn:samm:test:1.0.0#Test".to_string());
450    /// aspect.add_property(Property::new("urn:samm:test:1.0.0#prop1".to_string()));
451    ///
452    /// let stats = calculate_statistics(&aspect);
453    /// assert_eq!(stats.total_properties, 1);
454    /// assert_eq!(stats.required_properties, 1);
455    /// ```
456    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    /// Get the ratio of required to total properties
483    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    /// Get the ratio of optional to total properties
493    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
503/// Serialization utilities for quick export
504pub mod serialization {
505    use super::*;
506    use serde_json;
507
508    /// Serialize an aspect to a JSON string
509    ///
510    /// # Example
511    /// ```
512    /// use oxirs_samm::metamodel::Aspect;
513    /// use oxirs_samm::utils::serialization::to_json_string;
514    ///
515    /// let aspect = Aspect::new("urn:samm:test:1.0.0#Test".to_string());
516    ///
517    /// let json = to_json_string(&aspect).expect("JSON serialization should succeed");
518    /// assert!(json.contains("Test"));
519    /// ```
520    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    /// Serialize an aspect to pretty-printed JSON
526    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    /// Deserialize an aspect from a JSON string
532    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
538/// Batch operation utilities for bulk modifications
539pub mod batch {
540    use super::*;
541
542    /// Make all properties in an aspect optional
543    ///
544    /// # Example
545    /// ```
546    /// use oxirs_samm::metamodel::{Aspect, Property};
547    /// use oxirs_samm::utils::batch::make_all_optional;
548    ///
549    /// let mut aspect = Aspect::new("urn:samm:test:1.0.0#Test".to_string());
550    /// aspect.add_property(Property::new("urn:samm:test:1.0.0#prop1".to_string()));
551    ///
552    /// make_all_optional(&mut aspect);
553    /// assert!(aspect.properties.iter().all(|p| p.optional));
554    /// ```
555    pub fn make_all_optional(aspect: &mut Aspect) {
556        for property in &mut aspect.properties {
557            property.optional = true;
558        }
559    }
560
561    /// Make all properties in an aspect required
562    pub fn make_all_required(aspect: &mut Aspect) {
563        for property in &mut aspect.properties {
564            property.optional = false;
565        }
566    }
567
568    /// Set example values for all properties that don't have one
569    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    /// Remove all example values from properties
578    pub fn clear_example_values(aspect: &mut Aspect) {
579        for property in &mut aspect.properties {
580            property.example_values.clear();
581        }
582    }
583
584    /// Apply a transformation function to all properties
585    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    /// Filter properties by a predicate and return a new aspect
595    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
615/// Model cloning and merging utilities
616pub mod merging {
617    use super::*;
618    use std::collections::HashSet;
619
620    /// Merge two aspects, combining their properties
621    ///
622    /// Properties from the second aspect are added to the first.
623    /// Duplicate properties (same URN) are kept from the first aspect.
624    pub fn merge_aspects(first: &Aspect, second: &Aspect) -> Aspect {
625        let mut merged = first.clone();
626
627        // Track existing property URNs
628        let existing_urns: HashSet<String> = merged
629            .properties
630            .iter()
631            .map(|p| p.urn().to_owned())
632            .collect();
633
634        // Add properties from second that don't exist in first
635        for property in &second.properties {
636            if !existing_urns.contains(property.urn()) {
637                merged.properties.push(property.clone());
638            }
639        }
640
641        // Merge operations (same logic)
642        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        // Merge events
655        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    /// Deep clone an aspect
668    pub fn deep_clone(aspect: &Aspect) -> Aspect {
669        aspect.clone()
670    }
671}
672
673/// Diff utilities for quick model comparison
674pub mod diff {
675    use super::*;
676
677    /// Quick diff summary between two aspects
678    #[derive(Debug, Clone)]
679    pub struct QuickDiff {
680        /// Number of properties added
681        pub properties_added: usize,
682        /// Number of properties removed
683        pub properties_removed: usize,
684        /// Number of properties modified
685        pub properties_modified: usize,
686        /// Number of operations added
687        pub operations_added: usize,
688        /// Number of operations removed
689        pub operations_removed: usize,
690    }
691
692    /// Generate a quick diff summary between two aspects
693    ///
694    /// This is a lightweight alternative to full ModelComparison for quick checks.
695    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        // Count modified properties (intersection but with different content)
705        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    /// Check if two aspects are identical
743    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}