strs_tools 0.44.0

Tools to manipulate strings.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
use core::default::Default;

// Import standard collections with proper precedence
#[ cfg( feature = "std" ) ]
use std::collections::HashMap;
#[ cfg( all( feature = "use_alloc", not( feature = "std" ) ) ) ]
use alloc::collections::BTreeMap as HashMap;

// Import vec macro and common types
#[ cfg( feature = "std" ) ]
use std::{ vec, vec::Vec, string::String };
#[ cfg( all( feature = "use_alloc", not( feature = "std" ) ) ) ]
use alloc::{ vec, vec::Vec, string::String };

/// Internal implementation details exposed for testing
pub mod private {
  #[ cfg( all( feature = "string_split", feature = "string_isolate", feature = "std" ) ) ]
  use crate::string::split::split;

  // Fix(compilation-error-strs-tools): Import Src and Delimiter from isolate::private
  // Root cause: Src and Delimiter types are in isolate::private module, not re-exported to isolate::
  // Pitfall: Module re-export structure must match imports - types in private submodules require explicit private:: path
  #[ cfg( all( feature = "string_split", feature = "string_isolate", feature = "std" ) ) ]
  use crate::string::{
    isolate::isolate_right,
    isolate::private::Src,
    isolate::private::Delimiter,
  };
  use super::*;

  ///
  /// Wrapper types to make transformation.
  ///
  #[ derive( Debug, Clone, PartialEq, Eq ) ]
  pub enum OpType<T> {
    /// Wrapper over single element of type `<T>`.
    Primitive(T),
    /// Wrapper over vector of elements of type `<T>`.
    Vector(Vec< T >),
    /// Wrapper over hash map of elements of type `<T>`.
    Map(HashMap<String, T>),
  }

  impl<T: Default> Default for OpType<T> {
    fn default() -> Self {
      OpType::Primitive(T::default())
    }
  }

  impl<T> From<T> for OpType<T> {
    fn from(value: T) -> Self {
      OpType::Primitive(value)
    }
  }

  impl<T> From<Vec< T >> for OpType<T> {
    fn from(value: Vec< T >) -> Self {
      OpType::Vector(value)
    }
  }

  #[ allow( clippy::from_over_into ) ]
  impl<T> Into<Vec< T >> for OpType<T> {
    fn into(self) -> Vec< T > {
      match self {
        OpType::Vector(vec) => vec,
        _ => unimplemented!("not implemented"),
      }
    }
  }

  impl<T: Clone> OpType<T> {
    /// Append item of `OpType` to current value. If current type is `Primitive`, then it will be converted to
    /// `Vector`.
    /// # Panics
    /// qqq: doc
    #[ must_use ]
    pub fn append(mut self, item: OpType<T>) -> OpType<T> {
      let mut mut_item = item;
      match self {
        OpType::Primitive(value) => match mut_item {
          OpType::Primitive(ins) => {
            let vector = vec![value, ins];
            OpType::Vector(vector)
          }
          OpType::Vector(ref mut vector) => {
            vector.insert(0, value);
            mut_item
          }
          OpType::Map(_) => panic!("Unexpected operation. Please, use method `insert` to insert item in hash map."),
        },
        OpType::Vector(ref mut vector) => match mut_item {
          OpType::Primitive(ins) => {
            vector.push(ins);
            self
          }
          OpType::Vector(ref mut ins_vec) => {
            vector.append(ins_vec);
            self
          }
          OpType::Map(_) => panic!("Unexpected operation. Please, use method `insert` to insert item in hash map."),
        },
        OpType::Map(_) => panic!("Unexpected operation. Please, use method `insert` to insert item in hash map."),
      }
    }

    /// Unwrap primitive value. Consumes self.
    pub fn primitive(self) -> Option< T > {
      match self {
        OpType::Primitive(v) => Some(v),
        _ => None,
      }
    }

    /// Unwrap vector value. Consumes self.
    pub fn vector(self) -> Option<Vec< T >> {
      match self {
        OpType::Vector(vec) => Some(vec),
        _ => None,
      }
    }
  }

  ///
  /// Parsed request data.
  ///
  #[ allow( dead_code ) ]
  #[ derive( Debug, Default, PartialEq, Eq ) ]
  pub struct Request<'a> {
    /// Original request string.
    pub original: &'a str,
    /// Delimiter for pairs `key:value`.
    pub key_val_delimeter: &'a str,
    /// Delimiter for commands.
    pub commands_delimeter: &'a str,
    /// Parsed subject of first command.
    pub subject: String,
    /// All subjects of the commands in request.
    pub subjects: Vec< String >,
    /// Options map of first command.
    pub map: HashMap<String, OpType<String>>,
    /// All options maps of the commands in request.
    pub maps: Vec<HashMap<String, OpType<String>>>,
  }

  /// Newtype for the source string slice in `ParseOptions`.
  #[ derive( Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default ) ]
  pub struct ParseSrc<'a>(pub &'a str);

  // impl Default for ParseSrc<'_>
  // {
  //   fn default() -> Self
  //   {
  //     Self( "" )
  //   }
  // }

  /// Newtype for the key-value delimiter string slice in `ParseOptions`.
  #[ derive( Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash ) ]
  pub struct ParseKeyValDelimeter<'a>(pub &'a str);

  impl Default for ParseKeyValDelimeter<'_>
  {
    fn default() -> Self
    {
      Self( ": " )
    }
  }

  /// Newtype for the commands delimiter string slice in `ParseOptions`.
  #[ derive( Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash ) ]
  pub struct ParseCommandsDelimeter<'a>(pub &'a str);

  impl Default for ParseCommandsDelimeter<'_>
  {
    fn default() -> Self
    {
      Self( ";" )
    }
  }

  /// Newtype for the quoting boolean flag in `ParseOptions`.
  #[ derive( Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash ) ]
  pub struct ParseQuoting(pub bool);

  impl Default for ParseQuoting
  {
    fn default() -> Self
    {
      Self( true )
    }
  }

  /// Newtype for the unquoting boolean flag in `ParseOptions`.
  #[ derive( Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash ) ]
  pub struct ParseUnquoting(pub bool);

  impl Default for ParseUnquoting
  {
    fn default() -> Self
    {
      Self( true )
    }
  }

  /// Newtype for the `parsing_arrays` boolean flag in `ParseOptions`.
  #[ derive( Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash ) ]
  pub struct ParseParsingArrays(pub bool);

  impl Default for ParseParsingArrays
  {
    fn default() -> Self
    {
      Self( true )
    }
  }

  /// Newtype for the `several_values` boolean flag in `ParseOptions`.
  #[ derive( Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default ) ]
  pub struct ParseSeveralValues(pub bool);

  // impl Default for ParseSeveralValues
  // {
  //   fn default() -> Self
  //   {
  //     Self( false )
  //   }
  // }

  /// Newtype for the `subject_win_paths_maybe` boolean flag in `ParseOptions`.
  #[ derive( Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default ) ]
  pub struct ParseSubjectWinPathsMaybe(pub bool);

  // impl Default for ParseSubjectWinPathsMaybe
  // {
  //   fn default() -> Self
  //   {
  //     Self( false )
  //   }
  // }

  ///
  /// Options for parser.
  ///
  #[ allow( clippy::struct_excessive_bools ) ]
  #[ derive( Debug, Default ) ] // Added Default here, Removed former::Former derive
  pub struct ParseOptions<'a> {
    /// Source string slice.
    pub src: ParseSrc<'a>,
    /// Delimiter for pairs `key:value`.
    pub key_val_delimeter: ParseKeyValDelimeter<'a>,
    /// Delimeter for commands.
    pub commands_delimeter: ParseCommandsDelimeter<'a>,
    /// Quoting of strings.
    pub quoting: ParseQuoting,
    /// Unquoting of string.
    pub unquoting: ParseUnquoting,
    /// Parse arrays of values.
    pub parsing_arrays: ParseParsingArrays,
    /// Append to a vector a values.
    pub several_values: ParseSeveralValues,
    /// Parse subject on Windows taking into account colon in path.
    pub subject_win_paths_maybe: ParseSubjectWinPathsMaybe,
  }

  // impl Default for ParseOptions<'_> // Removed manual impl
  // {
  //   fn default() -> Self
  //   {
  //     Self
  //     {
  //       src : ParseSrc::default(),
  //       key_val_delimeter : ParseKeyValDelimeter::default(),
  //       commands_delimeter : ParseCommandsDelimeter::default(),
  //       quoting : ParseQuoting::default(),
  //       unquoting : ParseUnquoting::default(),
  //       parsing_arrays : ParseParsingArrays::default(),
  //       several_values : ParseSeveralValues::default(),
  //       subject_win_paths_maybe : ParseSubjectWinPathsMaybe::default(),
  //     }
  //   }
  // }

  impl<'a> ParseOptions<'a> {
    /// Do parsing.
    #[ allow( clippy::assigning_clones, clippy::too_many_lines, clippy::collapsible_if ) ]
    /// # Panics
    /// Panics if `map_entries.1` is `None` when `join.push_str` is called.
    #[ cfg( all( feature = "string_split", feature = "string_isolate", feature = "std" ) ) ]
    pub fn parse(&mut self) -> Request<'a> // Changed to inherent method, takes &mut self
    {
      let mut result = Request {
        original: self.src.0,                          // Accessing newtype field
        key_val_delimeter: self.key_val_delimeter.0,   // Accessing newtype field
        commands_delimeter: self.commands_delimeter.0, // Accessing newtype field
        ..Default::default()
      };

      self.src.0 = self.src.0.trim(); // Accessing newtype field

      if self.src.0.is_empty()
      // Accessing newtype field
      {
        return result;
      }

      let commands = if self.commands_delimeter.0.trim().is_empty()
      // Accessing newtype field
      {
        vec![self.src.0.to_string()] // Accessing newtype field
      } else {
        let iter = split()
        .src( self.src.0 ) // Accessing newtype field
        .delimeter( self.commands_delimeter.0 ) // Accessing newtype field
        .quoting( self.quoting.0 ) // Accessing newtype field
        .stripping( true )
        .preserving_empty( false )
        .preserving_delimeters( false )
        .perform();
        iter.map(String::from).collect::<Vec< _ >>()
      };

      for command in commands {
        let mut map_entries;
        if self.key_val_delimeter.0.trim().is_empty()
        // Accessing newtype field
        {
          map_entries = (command.as_str(), None, "");
        } else {
          map_entries = match command.split_once( self.key_val_delimeter.0 ) // Accessing newtype field
          {
            Some( entries ) => ( entries.0, Some( self.key_val_delimeter.0 ), entries.1 ), // Accessing newtype field
            None => ( command.as_str(), None, "" ),
          };
        }

        let subject;
        let mut map: HashMap<String, OpType<String>> = HashMap::new();

        if let Some(map_entry_1) = map_entries.1 {
          let mut options = isolate_right();
          options.src = Src( map_entries.0 );
          options.delimiter = Delimiter( " " );
          let subject_and_key = options.isolate();
          subject = subject_and_key.0;
          map_entries.0 = subject_and_key.2;

          let mut join = String::from(map_entries.0);
          join.push_str(map_entry_1);
          join.push_str(map_entries.2);

          let mut splits = split()
          .src( join.as_str() )
          .delimeter( self.key_val_delimeter.0 ) // Accessing newtype field
          .stripping( false )
          .quoting( self.quoting.0 ) // Accessing newtype field
          .preserving_empty( true )
          .preserving_delimeters( true )
          .preserving_quoting( true )
          .perform()
          .map( String::from ).collect::< Vec<  _  > >();

          let mut pairs = vec![];
          for a in (0..splits.len() - 2).step_by(2) {
            let mut right = splits[a + 2].clone();

            while a < (splits.len() - 3) {
              let mut options = isolate_right();
              options.src = Src( &splits[a + 2] );
              options.delimiter = Delimiter( " " );
              let cuts = options.isolate();

              if cuts.1.is_none() {
                let mut joined = splits[a + 2].clone();
                joined.push_str(splits[a + 3].as_str());
                joined.push_str(splits[a + 4].as_str());

                splits[a + 2] = joined;
                right = splits[a + 2].clone();
                splits.remove(a + 3);
                splits.remove(a + 4);
                continue;
              }

              let cuts_2_owned = cuts.2.to_string();
              let cuts_0_owned = cuts.0.to_string();
              splits[a + 2] = cuts_2_owned;
              right = cuts_0_owned;
              break;
            }

            let left = splits[a].clone();
            let right = right.trim().to_string();
            if self.unquoting.0
            // Accessing newtype field
            {
              if left.contains('\"') || left.contains('\'') || right.contains('\"') || right.contains('\'') {
                unimplemented!("not implemented");
              }
              // left = str_unquote( left );
              // right = str_unquote( right );
            }

            pairs.push(left);
            pairs.push(right);
          }

          /* */

          let str_to_vec_maybe = |src: &str| -> Option<Vec< String >> {
            if !src.starts_with('[') || !src.ends_with(']') {
              return None;
            }

            let splits = split()
            .src( &src[ 1..src.len() - 1 ] )
            .delimeter( "," )
            .stripping( true )
            .quoting( self.quoting.0 ) // Accessing newtype field
            .preserving_empty( false )
            .preserving_delimeters( false )
            .preserving_quoting( false )
            .perform()
            .map( | e | String::from( e ).trim().to_owned() ).collect::< Vec<  String  > >();
            Some(splits)
          };

          /* */

          for a in (0..pairs.len() - 1).step_by(2) {
            let left = &pairs[a];
            let right_str = &pairs[a + 1];
            let mut right = OpType::Primitive(pairs[a + 1].clone());

            if self.parsing_arrays.0
            // Accessing newtype field
            {
              if let Some(vector) = str_to_vec_maybe(right_str) {
                right = OpType::Vector(vector);
              }
            }

            if self.several_values.0
            // Accessing newtype field
            {
              if let Some(op) = map.get(left) {
                let value = op.clone().append(right);
                map.insert(left.clone(), value);
              } else {
                map.insert(left.clone(), right);
              }
            } else {
              map.insert(left.clone(), right);
            }
          }
        } else {
          subject = map_entries.0;
        }

        if self.unquoting.0
        // Accessing newtype field
        {
          if subject.contains('\"') || subject.contains('\'') {
            unimplemented!("not implemented");
          }
          // subject = _.strUnquote( subject );
        }

        if self.subject_win_paths_maybe.0
        // Accessing newtype field
        {
          unimplemented!("not implemented");
          // subject = win_path_subject_check( subject, map );
        }

        result.subjects.push(subject.to_string());
        result.maps.push(map);
      }

      if !result.subjects.is_empty() {
        result.subject = result.subjects[0].clone();
      }
      if !result.maps.is_empty() {
        result.map = result.maps[0].clone();
      }

      result
    }
  }

  ///
  /// Function to parse a string with command request.
  ///
  /// It produces `former`. To convert `former` into options and run algorithm of splitting call `perform()`.
  ///
  ///
  ///
  #[ must_use ]
  #[ cfg( all( feature = "string_split", feature = "string_isolate", feature = "std" ) ) ]
  pub fn request_parse<'a>() -> ParseOptions<'a> // Return ParseOptions directly
  {
    ParseOptions::default()
  }
}

#[ doc( inline ) ]
#[ allow( unused_imports ) ]
pub use own::*;


/// Own namespace of the module.
#[ allow( unused_imports ) ]
pub mod own {
  #[ allow( unused_imports ) ]
  use super::*;
  pub use orphan::*;
  pub use private::{
    OpType,
    Request,
    ParseOptions,
    ParseSrc,
    ParseKeyValDelimeter,
    ParseCommandsDelimeter,
    ParseQuoting,
    ParseUnquoting,
    ParseParsingArrays,
    ParseSeveralValues,
    ParseSubjectWinPathsMaybe,
    // ParseOptionsAdapter, // Removed
  };
  #[ cfg( all( feature = "string_split", feature = "string_isolate", feature = "std" ) ) ]
  pub use private::request_parse;
}

/// Parented namespace of the module.
#[ allow( unused_imports ) ]
pub mod orphan {
  #[ allow( unused_imports ) ]
  use super::*;
  pub use exposed::*;
}

/// Exposed namespace of the module.
#[ allow( unused_imports ) ]
pub mod exposed {
  #[ allow( unused_imports ) ]
  use super::*;
  pub use prelude::*; // Added
  pub use super::own as parse_request;

  #[ cfg( all( feature = "string_split", feature = "string_isolate", feature = "std" ) ) ]
  pub use private::request_parse;
}

/// Namespace of the module to include with `use module::*`.
#[ allow( unused_imports ) ]
pub mod prelude {
  #[ allow( unused_imports ) ]
  use super::*;
  // pub use private::ParseOptionsAdapter; // Removed
}