vb6runtime 0.2.0

VB6 runtime library - value system, type conversions, and standard library implementations
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
//! # Trim Function
//!
//! Returns a String containing a copy of a specified string with both leading and trailing spaces removed.
//!
//! ## Syntax
//!
//! ```vb
//! Trim(string)
//! ```
//!
//! ## Parameters
//!
//! - `string` (Required): String expression from which leading and trailing spaces are to be removed
//!   - Can be any valid string expression
//!   - If string is Null, returns Null
//!   - Empty string returns empty string
//!
//! ## Return Value
//!
//! Returns a String (or Variant):
//! - Copy of string with both leading and trailing spaces removed
//! - Removes only spaces (ASCII 32) from both ends
//! - Does not remove tabs, newlines, or other whitespace characters
//! - Returns Null if input is Null
//! - Returns empty string if input is empty or all spaces
//! - Internal spaces between words are preserved
//! - Equivalent to LTrim(RTrim(string))
//!
//! ## Remarks
//!
//! The Trim function removes both leading and trailing spaces:
//!
//! - Removes only space characters (ASCII 32) from both ends
//! - Does not remove tabs (Chr(9)), line feeds (Chr(10)), or carriage returns (Chr(13))
//! - Does not remove non-breaking spaces or other Unicode whitespace
//! - Internal spaces between words are preserved
//! - Most commonly used string trimming function
//! - Equivalent to calling LTrim(RTrim(string))
//! - More efficient than using `LTrim` and `RTrim` separately
//! - Null input returns Null (propagates Null)
//! - Empty string input returns empty string
//! - String of only spaces returns empty string
//! - Does not modify the original string (returns new string)
//! - Can be used with Variant variables
//! - Essential for data validation and formatting
//! - Used to normalize user input
//! - Common in database operations
//! - Standard practice before comparing strings
//! - Required for cleaning imported data
//! - Part of the VB6 string manipulation library
//! - Available in all VB versions
//! - Related to `LTrim` (removes leading only) and `RTrim` (removes trailing only)
//!
//! ## Typical Uses
//!
//! 1. **Clean User Input**
//!    ```vb
//!    userName = Trim(txtUsername.Text)
//!    ```
//!
//! 2. **Validate Input**
//!    ```vb
//!    If Trim(txtEmail.Text) = "" Then
//!        MsgBox "Email required"
//!    End If
//!    ```
//!
//! 3. **Compare Strings**
//!    ```vb
//!    If Trim(input) = Trim(expected) Then
//!        result = "Match"
//!    End If
//!    ```
//!
//! 4. **Database Fields**
//!    ```vb
//!    customerName = Trim(rs("CustomerName"))
//!    ```
//!
//! 5. **Split Data**
//!    ```vb
//!    parts = Split(Trim(line), ",")
//!    ```
//!
//! 6. **Clean Array**
//!    ```vb
//!    For i = 0 To UBound(items)
//!        items(i) = Trim(items(i))
//!    Next i
//!    ```
//!
//! 7. **Form Validation**
//!    ```vb
//!    If Len(Trim(txtPassword.Text)) < 8 Then
//!        MsgBox "Password too short"
//!    End If
//!    ```
//!
//! 8. **Process CSV**
//!    ```vb
//!    fields = Split(line, ",")
//!    firstName = Trim(fields(0))
//!    lastName = Trim(fields(1))
//!    ```
//!
//! ## Basic Examples
//!
//! ### Example 1: Basic Usage
//! ```vb
//! Dim result As String
//!
//! result = Trim("   Hello   ")        ' Returns "Hello"
//! result = Trim("   Hello World   ")  ' Returns "Hello World"
//! result = Trim("NoSpaces")           ' Returns "NoSpaces"
//! result = Trim("     ")              ' Returns ""
//! result = Trim("")                   ' Returns ""
//! ```
//!
//! ### Example 2: Form Validation
//! ```vb
//! Private Sub cmdSubmit_Click()
//!     Dim userName As String
//!     Dim password As String
//!     
//!     ' Clean inputs
//!     userName = Trim(txtUsername.Text)
//!     password = Trim(txtPassword.Text)
//!     
//!     ' Validate
//!     If userName = "" Then
//!         MsgBox "Username is required", vbExclamation
//!         txtUsername.SetFocus
//!         Exit Sub
//!     End If
//!     
//!     If password = "" Then
//!         MsgBox "Password is required", vbExclamation
//!         txtPassword.SetFocus
//!         Exit Sub
//!     End If
//!     
//!     If Len(password) < 8 Then
//!         MsgBox "Password must be at least 8 characters", vbExclamation
//!         txtPassword.SetFocus
//!         Exit Sub
//!     End If
//!     
//!     ' Process login
//!     ProcessLogin userName, password
//! End Sub
//! ```
//!
//! ### Example 3: CSV Processing
//! ```vb
//! Sub ProcessCSVFile(ByVal filename As String)
//!     Dim fileNum As Integer
//!     Dim line As String
//!     Dim fields() As String
//!     Dim i As Integer
//!     
//!     fileNum = FreeFile
//!     Open filename For Input As #fileNum
//!     
//!     Do While Not EOF(fileNum)
//!         Line Input #fileNum, line
//!         
//!         ' Split and trim each field
//!         fields = Split(line, ",")
//!         For i = 0 To UBound(fields)
//!             fields(i) = Trim(fields(i))
//!         Next i
//!         
//!         ' Process the cleaned fields
//!         If UBound(fields) >= 2 Then
//!             Debug.Print "Name: " & fields(0) & ", " & fields(1)
//!             Debug.Print "Age: " & fields(2)
//!         End If
//!     Loop
//!     
//!     Close #fileNum
//! End Sub
//! ```
//!
//! ### Example 4: Database Operations
//! ```vb
//! Sub LoadCustomers()
//!     Dim rs As ADODB.Recordset
//!     Dim customerName As String
//!     
//!     Set rs = New ADODB.Recordset
//!     rs.Open "SELECT * FROM Customers", conn
//!     
//!     Do While Not rs.EOF
//!         ' Trim database fields (may have padding)
//!         customerName = Trim(rs("CustomerName") & "")
//!         
//!         If customerName <> "" Then
//!             lstCustomers.AddItem customerName
//!         End If
//!         
//!         rs.MoveNext
//!     Loop
//!     
//!     rs.Close
//!     Set rs = Nothing
//! End Sub
//! ```
//!
//! ## Common Patterns
//!
//! ### Pattern 1: `IsBlank`
//! ```vb
//! Function IsBlank(ByVal text As String) As Boolean
//!     IsBlank = (Trim(text) = "")
//! End Function
//! ```
//!
//! ### Pattern 2: `SafeTrim` (handle Null)
//! ```vb
//! Function SafeTrim(ByVal text As Variant) As String
//!     If IsNull(text) Then
//!         SafeTrim = ""
//!     Else
//!         SafeTrim = Trim(CStr(text))
//!     End If
//! End Function
//! ```
//!
//! ### Pattern 3: `TrimAndUpper`
//! ```vb
//! Function TrimAndUpper(ByVal text As String) As String
//!     TrimAndUpper = UCase(Trim(text))
//! End Function
//! ```
//!
//! ### Pattern 4: `ValidateRequired`
//! ```vb
//! Function ValidateRequired(ByVal value As String, _
//!                          ByVal fieldName As String) As Boolean
//!     If Trim(value) = "" Then
//!         MsgBox fieldName & " is required", vbExclamation
//!         ValidateRequired = False
//!     Else
//!         ValidateRequired = True
//!     End If
//! End Function
//! ```
//!
//! ### Pattern 5: `TrimArray`
//! ```vb
//! Sub TrimArray(arr() As String)
//!     Dim i As Integer
//!     For i = LBound(arr) To UBound(arr)
//!         arr(i) = Trim(arr(i))
//!     Next i
//! End Sub
//! ```
//!
//! ### Pattern 6: `CompareIgnoreSpaces`
//! ```vb
//! Function CompareIgnoreSpaces(ByVal str1 As String, _
//!                             ByVal str2 As String) As Boolean
//!     CompareIgnoreSpaces = (Trim(str1) = Trim(str2))
//! End Function
//! ```
//!
//! ### Pattern 7: `TrimAllControls`
//! ```vb
//! Sub TrimAllControls(ByVal frm As Form)
//!     Dim ctrl As Control
//!     
//!     For Each ctrl In frm.Controls
//!         If TypeOf ctrl Is TextBox Then
//!             ctrl.Text = Trim(ctrl.Text)
//!         ElseIf TypeOf ctrl Is ComboBox Then
//!             ctrl.Text = Trim(ctrl.Text)
//!         End If
//!     Next ctrl
//! End Sub
//! ```
//!
//! ### Pattern 8: `GetCleanValue`
//! ```vb
//! Function GetCleanValue(ByVal ctrl As Control) As String
//!     If TypeOf ctrl Is TextBox Or TypeOf ctrl Is ComboBox Then
//!         GetCleanValue = Trim(ctrl.Text)
//!     Else
//!         GetCleanValue = ""
//!     End If
//! End Function
//! ```
//!
//! ### Pattern 9: `SplitAndTrim`
//! ```vb
//! Function SplitAndTrim(ByVal text As String, _
//!                       ByVal delimiter As String) As String()
//!     Dim parts() As String
//!     Dim i As Integer
//!     
//!     parts = Split(text, delimiter)
//!     For i = 0 To UBound(parts)
//!         parts(i) = Trim(parts(i))
//!     Next i
//!     
//!     SplitAndTrim = parts
//! End Function
//! ```
//!
//! ### Pattern 10: `DefaultIfBlank`
//! ```vb
//! Function DefaultIfBlank(ByVal value As String, _
//!                         ByVal defaultValue As String) As String
//!     If Trim(value) = "" Then
//!         DefaultIfBlank = defaultValue
//!     Else
//!         DefaultIfBlank = Trim(value)
//!     End If
//! End Function
//! ```
//!
//! ## Advanced Examples
//!
//! ### Example 1: Form Validator Class
//! ```vb
//! ' Class: FormValidator
//! Private m_form As Form
//! Private m_errors As Collection
//!
//! Public Sub AttachForm(ByVal frm As Form)
//!     Set m_form = frm
//! End Sub
//!
//! Public Function Validate() As Boolean
//!     Set m_errors = New Collection
//!     
//!     Dim ctrl As Control
//!     For Each ctrl In m_form.Controls
//!         If TypeOf ctrl Is TextBox Then
//!             ValidateTextBox ctrl
//!         End If
//!     Next ctrl
//!     
//!     Validate = (m_errors.Count = 0)
//! End Function
//!
//! Private Sub ValidateTextBox(ByVal txt As TextBox)
//!     Dim value As String
//!     value = Trim(txt.Text)
//!     
//!     ' Check required
//!     If txt.Tag Like "*Required*" Then
//!         If value = "" Then
//!             m_errors.Add "Field '" & txt.Name & "' is required"
//!             Exit Sub
//!         End If
//!     End If
//!     
//!     ' Check minimum length
//!     If txt.Tag Like "*MinLen:*" Then
//!         Dim minLen As Integer
//!         minLen = ExtractNumber(txt.Tag, "MinLen:")
//!         
//!         If Len(value) < minLen Then
//!             m_errors.Add "Field '" & txt.Name & "' must be at least " & _
//!                         minLen & " characters"
//!         End If
//!     End If
//!     
//!     ' Check email format
//!     If txt.Tag Like "*Email*" Then
//!         If value <> "" And InStr(value, "@") = 0 Then
//!             m_errors.Add "Field '" & txt.Name & "' must be a valid email"
//!         End If
//!     End If
//! End Sub
//!
//! Public Property Get Errors() As Collection
//!     Set Errors = m_errors
//! End Property
//!
//! Public Sub ShowErrors()
//!     Dim msg As String
//!     Dim err As Variant
//!     
//!     For Each err In m_errors
//!         msg = msg & err & vbCrLf
//!     Next err
//!     
//!     If msg <> "" Then
//!         MsgBox msg, vbExclamation, "Validation Errors"
//!     End If
//! End Sub
//! ```
//!
//! ### Example 2: Data Cleaner Class
//! ```vb
//! ' Class: DataCleaner
//! Private m_trimSpaces As Boolean
//! Private m_removeLineBreaks As Boolean
//! Private m_collapseSpaces As Boolean
//!
//! Private Sub Class_Initialize()
//!     m_trimSpaces = True
//!     m_removeLineBreaks = False
//!     m_collapseSpaces = False
//! End Sub
//!
//! Public Property Let TrimSpaces(ByVal value As Boolean)
//!     m_trimSpaces = value
//! End Property
//!
//! Public Property Let RemoveLineBreaks(ByVal value As Boolean)
//!     m_removeLineBreaks = value
//! End Property
//!
//! Public Property Let CollapseSpaces(ByVal value As Boolean)
//!     m_collapseSpaces = value
//! End Property
//!
//! Public Function CleanString(ByVal text As String) As String
//!     Dim result As String
//!     result = text
//!     
//!     ' Remove line breaks if requested
//!     If m_removeLineBreaks Then
//!         result = Replace(result, vbCrLf, " ")
//!         result = Replace(result, vbCr, " ")
//!         result = Replace(result, vbLf, " ")
//!     End If
//!     
//!     ' Collapse multiple spaces if requested
//!     If m_collapseSpaces Then
//!         Do While InStr(result, "  ") > 0
//!             result = Replace(result, "  ", " ")
//!         Loop
//!     End If
//!     
//!     ' Trim spaces if requested
//!     If m_trimSpaces Then
//!         result = Trim(result)
//!     End If
//!     
//!     CleanString = result
//! End Function
//!
//! Public Function CleanArray(arr() As String) As String()
//!     Dim result() As String
//!     Dim i As Integer
//!     
//!     ReDim result(LBound(arr) To UBound(arr))
//!     
//!     For i = LBound(arr) To UBound(arr)
//!         result(i) = CleanString(arr(i))
//!     Next i
//!     
//!     CleanArray = result
//! End Function
//! ```
//!
//! ### Example 3: CSV Parser
//! ```vb
//! ' Class: CSVParser
//! Private m_rows As Collection
//!
//! Public Sub ParseFile(ByVal filename As String)
//!     Dim fileNum As Integer
//!     Dim line As String
//!     
//!     Set m_rows = New Collection
//!     
//!     fileNum = FreeFile
//!     Open filename For Input As #fileNum
//!     
//!     Do While Not EOF(fileNum)
//!         Line Input #fileNum, line
//!         
//!         If Trim(line) <> "" Then
//!             m_rows.Add ParseLine(line)
//!         End If
//!     Loop
//!     
//!     Close #fileNum
//! End Sub
//!
//! Private Function ParseLine(ByVal line As String) As Collection
//!     Dim fields As Collection
//!     Dim parts() As String
//!     Dim i As Integer
//!     Dim field As String
//!     
//!     Set fields = New Collection
//!     parts = Split(line, ",")
//!     
//!     For i = 0 To UBound(parts)
//!         field = Trim(parts(i))
//!         
//!         ' Remove quotes if present
//!         If Left(field, 1) = """" And Right(field, 1) = """" Then
//!             field = Mid(field, 2, Len(field) - 2)
//!         End If
//!         
//!         fields.Add field
//!     Next i
//!     
//!     Set ParseLine = fields
//! End Function
//!
//! Public Property Get RowCount() As Long
//!     RowCount = m_rows.Count
//! End Property
//!
//! Public Function GetRow(ByVal index As Long) As Collection
//!     Set GetRow = m_rows(index)
//! End Function
//!
//! Public Function GetField(ByVal row As Long, _
//!                          ByVal col As Long) As String
//!     Dim rowData As Collection
//!     Set rowData = m_rows(row)
//!     GetField = rowData(col)
//! End Function
//! ```
//!
//! ### Example 4: String Utilities Module
//! ```vb
//! ' Module: StringUtils
//!
//! Public Function IsNullOrWhitespace(ByVal text As Variant) As Boolean
//!     If IsNull(text) Then
//!         IsNullOrWhitespace = True
//!     ElseIf VarType(text) = vbString Then
//!         IsNullOrWhitespace = (Trim(text) = "")
//!     Else
//!         IsNullOrWhitespace = False
//!     End If
//! End Function
//!
//! Public Function CoalesceString(ParamArray values() As Variant) As String
//!     Dim i As Integer
//!     Dim value As String
//!     
//!     For i = LBound(values) To UBound(values)
//!         If Not IsNull(values(i)) Then
//!             value = Trim(CStr(values(i)))
//!             If value <> "" Then
//!                 CoalesceString = value
//!                 Exit Function
//!             End If
//!         End If
//!     Next i
//!     
//!     CoalesceString = ""
//! End Function
//!
//! Public Function JoinTrimmed(arr() As String, _
//!                            ByVal delimiter As String) As String
//!     Dim result As String
//!     Dim i As Integer
//!     Dim value As String
//!     
//!     For i = LBound(arr) To UBound(arr)
//!         value = Trim(arr(i))
//!         If value <> "" Then
//!             If result <> "" Then
//!                 result = result & delimiter
//!             End If
//!             result = result & value
//!         End If
//!     Next i
//!     
//!     JoinTrimmed = result
//! End Function
//!
//! Public Function NormalizeWhitespace(ByVal text As String) As String
//!     Dim result As String
//!     
//!     ' Replace all whitespace with single space
//!     result = text
//!     result = Replace(result, vbTab, " ")
//!     result = Replace(result, vbCrLf, " ")
//!     result = Replace(result, vbCr, " ")
//!     result = Replace(result, vbLf, " ")
//!     
//!     ' Collapse multiple spaces
//!     Do While InStr(result, "  ") > 0
//!         result = Replace(result, "  ", " ")
//!     Loop
//!     
//!     ' Trim
//!     NormalizeWhitespace = Trim(result)
//! End Function
//!
//! Public Function TruncateWithEllipsis(ByVal text As String, _
//!                                      ByVal maxLength As Integer) As String
//!     text = Trim(text)
//!     
//!     If Len(text) <= maxLength Then
//!         TruncateWithEllipsis = text
//!     Else
//!         TruncateWithEllipsis = Left(text, maxLength - 3) & "..."
//!     End If
//! End Function
//! ```
//!
//! ## Error Handling
//!
//! ```vb
//! ' Trim handles Null gracefully
//! Dim result As Variant
//! result = Trim(Null)  ' Returns Null
//!
//! ' Safe trimming with Null check
//! Function SafeTrim(ByVal value As Variant) As String
//!     If IsNull(value) Then
//!         SafeTrim = ""
//!     Else
//!         SafeTrim = Trim(CStr(value))
//!     End If
//! End Function
//! ```
//!
//! ## Performance Considerations
//!
//! - **Fast Operation**: String trimming is highly optimized
//! - **Creates New String**: Does not modify original (immutable)
//! - **More Efficient**: Using `Trim()` is faster than LTrim(RTrim())
//! - **Cache Results**: Don't call repeatedly in tight loops
//!
//! ## Best Practices
//!
//! 1. **Always trim user input** - Before validation or storage
//! 2. **Trim before comparison** - Ensure consistent string matching
//! 3. **Use with database fields** - Clean data from external sources
//! 4. **Validate after trimming** - Check if empty after removing spaces
//! 5. **Combine with other operations** - Trim then convert case, etc.
//! 6. **Cache trimmed values** - Don't call repeatedly
//! 7. **Handle Null gracefully** - Use `SafeTrim` for Variant types
//! 8. **Document expectations** - Clarify if other whitespace should be removed
//! 9. **Standardize input early** - Trim at entry point
//! 10. **Test edge cases** - Empty strings, all spaces, Null values
//!
//! ## Comparison with Related Functions
//!
//! | Function | Removes Leading | Removes Trailing | Removes Both |
//! |----------|----------------|------------------|--------------|
//! | **Trim** | Yes | Yes | Yes |
//! | **`LTrim`** | Yes | No | No |
//! | **`RTrim`** | No | Yes | No |
//!
//! ## Trim vs `LTrim` vs `RTrim`
//!
//! ```vb
//! Dim text As String
//! text = "   Hello World   "
//!
//! ' Trim - removes both leading and trailing
//! Debug.Print "[" & Trim(text) & "]"       ' [Hello World]
//!
//! ' LTrim - removes leading spaces only
//! Debug.Print "[" & LTrim(text) & "]"      ' [Hello World   ]
//!
//! ' RTrim - removes trailing spaces only
//! Debug.Print "[" & RTrim(text) & "]"      ' [   Hello World]
//!
//! ' Trim is equivalent to LTrim(RTrim())
//! Debug.Print "[" & LTrim(RTrim(text)) & "]"  ' [Hello World]
//! ```
//!
//! ## Whitespace Characters
//!
//! ```vb
//! ' Trim only removes space (ASCII 32)
//! Dim text As String
//!
//! text = "   Hello   "     ' Spaces - REMOVED
//! text = Chr(9) & "Hello" & Chr(9)  ' Tabs - NOT REMOVED
//! text = Chr(10) & "Hello" & Chr(10) ' Line feeds - NOT REMOVED
//! text = Chr(13) & "Hello" & Chr(13) ' CR - NOT REMOVED
//!
//! ' To remove all whitespace:
//! Function TrimAllWhitespace(ByVal text As String) As String
//!     ' Remove line breaks
//!     text = Replace(text, vbCrLf, "")
//!     text = Replace(text, vbCr, "")
//!     text = Replace(text, vbLf, "")
//!     text = Replace(text, vbTab, "")
//!     
//!     ' Trim spaces
//!     TrimAllWhitespace = Trim(text)
//! End Function
//! ```
//!
//! ## Platform Notes
//!
//! - Available in all VB6 versions
//! - Part of VBA core library
//! - Works with ANSI and Unicode strings
//! - Only removes ASCII space character (32)
//! - Returns new string (original unchanged)
//! - Handles Null by returning Null
//! - Available in `VBScript`
//! - Same behavior across all Windows versions
//! - More efficient than LTrim(RTrim())
//!
//! ## Limitations
//!
//! - **Only Space Character**: Does not remove tabs, line feeds, etc.
//! - **No Unicode Whitespace**: Does not remove non-breaking spaces, em spaces, etc.
//! - **Creates New String**: Cannot modify string in place
//! - **No Custom Characters**: Cannot specify which characters to remove
//! - **Null Propagation**: Returns Null if input is Null
//!
//! ## Related Functions
//!
//! - `LTrim`: Removes leading spaces from string
//! - `RTrim`: Removes trailing spaces from string
//! - `Left`: Returns leftmost characters
//! - `Right`: Returns rightmost characters
//! - `Mid`: Returns substring from middle
//! - `Replace`: Replaces occurrences of substring
//! - `Space`: Creates string of spaces
//! - `Len`: Returns string length

use crate::{error::VBResult, value::VBString, value::VBVariant};

use super::trim_dollar::trim_dollar;

/// Returns the string with leading and trailing spaces (ASCII 32) removed.
///
/// Only the space character is trimmed, matching VB6; tabs and other
/// whitespace are preserved.
///
/// `Trim` is the Variant-returning counterpart of `Trim$`; a `Null` input
/// propagates as `Null`.
pub fn trim(input: &VBString) -> VBResult<VBVariant> {
    trim_dollar(input).map(VBVariant::from)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn trims_both_ends() {
        assert_eq!(
            trim(&VBString::from("  Hello World  ")).unwrap(),
            VBVariant::from_string("Hello World")
        );
        assert_eq!(
            trim(&VBString::from("Hello")).unwrap(),
            VBVariant::from_string("Hello")
        );
    }

    #[test]
    fn trims_leading_spaces() {
        assert_eq!(
            trim(&VBString::from("  Hello World")).unwrap(),
            VBVariant::from_string("Hello World")
        );
        assert_eq!(
            trim(&VBString::from(" Hello")).unwrap(),
            VBVariant::from_string("Hello")
        );
    }

    #[test]
    fn trims_trailing_spaces() {
        assert_eq!(
            trim(&VBString::from("Hello World  ")).unwrap(),
            VBVariant::from_string("Hello World")
        );
        assert_eq!(
            trim(&VBString::from("Hello ")).unwrap(),
            VBVariant::from_string("Hello")
        );
    }

    #[test]
    fn handles_empty_and_all_spaces() {
        assert_eq!(
            trim(&VBString::from("")).unwrap(),
            VBVariant::from_string("")
        );
        assert_eq!(
            trim(&VBString::from("   ")).unwrap(),
            VBVariant::from_string("")
        );
    }

    #[test]
    fn preserves_inner_and_other_whitespace() {
        assert_eq!(
            trim(&VBString::from("  a b  ")).unwrap(),
            VBVariant::from_string("a b")
        );
        assert_eq!(
            trim(&VBString::from("\tHello\t")).unwrap(),
            VBVariant::from_string("\tHello\t")
        );
    }

    #[test]
    fn empty_string_preserved() {
        assert_eq!(
            trim(&VBString::from("")).unwrap(),
            VBVariant::from_string("")
        );
    }
}