Skip to main content

dissolve_python/
function_refactoring.rs

1// Copyright (C) 2024 Jelmer Vernooij <jelmer@samba.org>
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//    http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Refactored versions of large functions broken down into smaller, focused functions
16
17// Removed unused Result import
18use std::collections::{HashMap, HashSet};
19
20// Example of how to refactor the large dependency collection function
21// This breaks down the 246-line function into smaller, focused functions
22
23/// Configuration for dependency collection
24pub struct DependencyCollectionConfig<'a> {
25    pub max_depth: i32,
26    pub additional_paths: &'a [String],
27    pub visited_modules: &'a mut HashSet<String>,
28}
29
30/// Result of processing imports for a single module
31#[derive(Debug, Default)]
32pub struct ModuleProcessingResult {
33    pub replacements: HashMap<String, String>,
34    pub inheritance_map: HashMap<String, Vec<String>>,
35    pub class_methods: HashMap<String, Vec<String>>,
36    pub imports: Vec<String>,
37}
38
39// Group imports function removed - was placeholder only
40
41// Process single module function removed - was placeholder only
42
43/// Merges results from multiple modules
44pub fn merge_module_results(results: Vec<ModuleProcessingResult>) -> ModuleProcessingResult {
45    let mut merged = ModuleProcessingResult::default();
46
47    for result in results {
48        // Merge replacements
49        merged.replacements.extend(result.replacements);
50
51        // Merge inheritance maps
52        for (key, value) in result.inheritance_map {
53            merged.inheritance_map.insert(key, value);
54        }
55
56        // Merge class methods
57        for (key, value) in result.class_methods {
58            merged.class_methods.insert(key, value);
59        }
60
61        // Merge imports
62        merged.imports.extend(result.imports);
63    }
64
65    merged
66}
67
68// This function was removed as it contained only placeholder implementations
69
70// Helper function removed - was unused
71
72/// Example of how to refactor parameter mapping to reduce clones
73pub struct OptimizedParameterMapper<'a> {
74    // Use string references where possible
75    param_names: Vec<&'a str>,
76    // Only store owned strings when necessary
77    dynamic_params: HashMap<String, String>,
78}
79
80impl<'a> OptimizedParameterMapper<'a> {
81    pub fn new(param_names: Vec<&'a str>) -> Self {
82        Self {
83            param_names,
84            dynamic_params: HashMap::new(),
85        }
86    }
87
88    /// Map parameters without cloning the parameter names
89    pub fn map_parameters(&mut self, args: &[&'a str]) -> HashMap<&'a str, &'a str> {
90        let mut param_map = HashMap::new();
91
92        for (i, &arg) in args.iter().enumerate() {
93            if let Some(&param_name) = self.param_names.get(i) {
94                param_map.insert(param_name, arg);
95            }
96        }
97
98        param_map
99    }
100
101    /// Add a dynamic parameter (only when string ownership is required)
102    pub fn add_dynamic_param(&mut self, name: String, value: String) {
103        self.dynamic_params.insert(name, value);
104    }
105}
106
107/// Example of refactoring string replacement to use Cow<str>
108pub fn optimize_string_replacement<'a>(
109    template: &'a str,
110    replacements: &HashMap<&str, &str>,
111) -> std::borrow::Cow<'a, str> {
112    let mut needs_replacement = false;
113
114    // First pass: check if any replacements are needed
115    for key in replacements.keys() {
116        if template.contains(key) {
117            needs_replacement = true;
118            break;
119        }
120    }
121
122    if !needs_replacement {
123        // No replacements needed - return borrowed
124        return std::borrow::Cow::Borrowed(template);
125    }
126
127    // Replacements needed - create owned string
128    let mut result = template.to_string();
129    for (key, value) in replacements {
130        result = result.replace(key, value);
131    }
132
133    std::borrow::Cow::Owned(result)
134}
135
136#[cfg(test)]
137mod tests {
138    use super::*;
139
140    // Test for group_imports_by_module removed - function was placeholder only
141
142    #[test]
143    fn test_optimized_parameter_mapper() {
144        let param_names = vec!["param1", "param2", "param3"];
145        let mut mapper = OptimizedParameterMapper::new(param_names);
146
147        let args = vec!["value1", "value2", "value3"];
148        let mapped = mapper.map_parameters(&args);
149
150        assert_eq!(mapped.get("param1"), Some(&"value1"));
151        assert_eq!(mapped.get("param2"), Some(&"value2"));
152        assert_eq!(mapped.get("param3"), Some(&"value3"));
153    }
154
155    #[test]
156    fn test_optimize_string_replacement() {
157        let mut replacements = HashMap::new();
158        replacements.insert("{name}", "John");
159        replacements.insert("{age}", "30");
160
161        // Template with replacements needed
162        let result1 = optimize_string_replacement("Hello {name}, age {age}", &replacements);
163        assert!(matches!(result1, std::borrow::Cow::Owned(_)));
164        assert_eq!(result1, "Hello John, age 30");
165
166        // Template with no replacements needed
167        let result2 = optimize_string_replacement("Hello World", &replacements);
168        assert!(matches!(result2, std::borrow::Cow::Borrowed(_)));
169        assert_eq!(result2, "Hello World");
170    }
171
172    #[test]
173    fn test_merge_module_results() {
174        let results = vec![
175            ModuleProcessingResult {
176                replacements: [("func1".to_string(), "replacement1".to_string())].into(),
177                inheritance_map: [("class1".to_string(), vec!["base1".to_string()])].into(),
178                class_methods: HashMap::new(),
179                imports: vec!["module1".to_string()],
180            },
181            ModuleProcessingResult {
182                replacements: [("func2".to_string(), "replacement2".to_string())].into(),
183                inheritance_map: [("class2".to_string(), vec!["base2".to_string()])].into(),
184                class_methods: HashMap::new(),
185                imports: vec!["module2".to_string()],
186            },
187        ];
188
189        let merged = merge_module_results(results);
190        assert_eq!(merged.replacements.len(), 2);
191        assert_eq!(merged.inheritance_map.len(), 2);
192        assert_eq!(merged.imports.len(), 2);
193    }
194}