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
//! # `Len` Function
//!
//! Returns a `Long` containing the number of characters in a string or the number of bytes required to store a variable.
//!
//! ## Syntax
//!
//! ```vb
//! Len(string | varname)
//! ```
//!
//! ## Parameters
//!
//! - `string` (Optional): Any valid string expression
//!   - If string contains `Null`, `Null` is returned
//! - `varname` (Optional): Any valid variable name
//!   - For user-defined types, returns size in bytes
//!   - For objects, may return implementation-defined value
//!
//! ## Return Value
//!
//! Returns a Long:
//! - For strings: Number of characters in the string
//! - For variables: Number of bytes required to store the variable
//! - Returns 0 for empty string ("")
//! - Returns `Null` if string argument is `Null`
//! - For fixed-length strings: Returns declared length
//! - For Variant containing string: Returns length of string
//! - For user-defined types: Returns total size in bytes
//!
//! ## Remarks
//!
//! The `Len` function measures string length or variable size:
//!
//! - Most commonly used for string length
//! - Returns character count, not byte count (for strings)
//! - Empty string ("") returns 0
//! - Null propagates through the function
//! - Spaces and special characters are counted
//! - For fixed-length strings (e.g., String * 10), returns declared length
//! - Variable-length strings return actual content length
//! - `LenB` function returns byte count (useful for Unicode/DBCS)
//! - Cannot determine array size (use UBound/LBound instead)
//! - Essential for string manipulation and validation
//! - Used with Left, Right, Mid for substring operations
//! - Common in loops iterating through string characters
//! - Efficient operation with minimal overhead
//! - For user-defined types, returns structure size
//! - Object variables may return unpredictable values
//!
//! ## Typical Uses
//!
//! 1. **Validate Input**: Check if string is empty or within length limits
//! 2. **String Iteration**: Loop through each character in string
//! 3. **Substring Extraction**: Calculate positions for Left/Right/Mid
//! 4. **Text Processing**: Measure text before truncation or padding
//! 5. **File I/O**: Determine buffer sizes for string data
//! 6. **Data Validation**: Ensure fields meet length requirements
//! 7. **Format Verification**: Check string format compliance
//! 8. **Memory Calculation**: Determine structure sizes
//!
//! ## Basic Usage Examples
//!
//! ```vb
//! ' Example 1: Basic string length
//! Dim text As String
//! text = "Hello World"
//!
//! Debug.Print Len(text)                ' 11 - includes space
//! Debug.Print Len("VB6")               ' 3
//! Debug.Print Len("")                  ' 0 - empty string
//!
//! ' Example 2: Validation
//! Dim password As String
//! password = "secret123"
//!
//! If Len(password) < 8 Then
//!     MsgBox "Password must be at least 8 characters"
//! End If
//!
//! ' Example 3: String iteration
//! Dim i As Long
//! Dim char As String
//! text = "ABC"
//!
//! For i = 1 To Len(text)
//!     char = Mid(text, i, 1)
//!     Debug.Print char
//! Next i
//!
//! ' Example 4: Null handling
//! Dim value As Variant
//! value = Null
//!
//! Debug.Print IsNull(Len(value))       ' True - Null propagates
//! ```
//!
//! ## Common Patterns
//!
//! ```vb
//! ' Pattern 1: Check if string is empty
//! Function IsEmpty(text As String) As Boolean
//!     IsEmpty = (Len(text) = 0)
//! End Function
//!
//! ' Pattern 2: Validate string length range
//! Function ValidateLength(text As String, minLen As Long, maxLen As Long) As Boolean
//!     Dim length As Long
//!     length = Len(text)
//!     ValidateLength = (length >= minLen And length <= maxLen)
//! End Function
//!
//! ' Pattern 3: Pad string to fixed width
//! Function PadRight(text As String, width As Long, Optional padChar As String = " ") As String
//!     If Len(text) >= width Then
//!         PadRight = Left(text, width)
//!     Else
//!         PadRight = text & String(width - Len(text), padChar)
//!     End If
//! End Function
//!
//! ' Pattern 4: Center text in field
//! Function CenterText(text As String, width As Long) As String
//!     Dim padding As Long
//!     
//!     If Len(text) >= width Then
//!         CenterText = Left(text, width)
//!     Else
//!         padding = (width - Len(text)) \ 2
//!         CenterText = String(padding, " ") & text & _
//!                      String(width - Len(text) - padding, " ")
//!     End If
//! End Function
//!
//! ' Pattern 5: Reverse string
//! Function ReverseString(text As String) As String
//!     Dim i As Long
//!     Dim result As String
//!     
//!     result = ""
//!     For i = Len(text) To 1 Step -1
//!         result = result & Mid(text, i, 1)
//!     Next i
//!     
//!     ReverseString = result
//! End Function
//!
//! ' Pattern 6: Count occurrences of character
//! Function CountChar(text As String, searchChar As String) As Long
//!     Dim i As Long
//!     Dim count As Long
//!     
//!     count = 0
//!     For i = 1 To Len(text)
//!         If Mid(text, i, 1) = searchChar Then
//!             count = count + 1
//!         End If
//!     Next i
//!     
//!     CountChar = count
//! End Function
//!
//! ' Pattern 7: Truncate with ellipsis
//! Function TruncateText(text As String, maxLength As Long) As String
//!     If Len(text) <= maxLength Then
//!         TruncateText = text
//!     ElseIf maxLength <= 3 Then
//!         TruncateText = Left(text, maxLength)
//!     Else
//!         TruncateText = Left(text, maxLength - 3) & "..."
//!     End If
//! End Function
//!
//! ' Pattern 8: Extract last N characters
//! Function GetLastChars(text As String, count As Long) As String
//!     If count >= Len(text) Then
//!         GetLastChars = text
//!     Else
//!         GetLastChars = Right(text, count)
//!     End If
//! End Function
//!
//! ' Pattern 9: Check minimum length
//! Function HasMinLength(text As String, minLength As Long) As Boolean
//!     HasMinLength = (Len(text) >= minLength)
//! End Function
//!
//! ' Pattern 10: Calculate character position from end
//! Function GetCharFromEnd(text As String, posFromEnd As Long) As String
//!     Dim pos As Long
//!     pos = Len(text) - posFromEnd + 1
//!     
//!     If pos >= 1 And pos <= Len(text) Then
//!         GetCharFromEnd = Mid(text, pos, 1)
//!     Else
//!         GetCharFromEnd = ""
//!     End If
//! End Function
//! ```
//!
//! ## Advanced Usage Examples
//!
//! ```vb
//! ' Example 1: String analyzer
//! Public Class StringAnalyzer
//!     Public Function GetStats(text As String) As String
//!         Dim length As Long
//!         Dim words As Long
//!         Dim lines As Long
//!         Dim result As String
//!         
//!         length = Len(text)
//!         words = UBound(Split(text, " ")) + 1
//!         lines = UBound(Split(text, vbCrLf)) + 1
//!         
//!         result = "Length: " & length & vbCrLf
//!         result = result & "Words: " & words & vbCrLf
//!         result = result & "Lines: " & lines
//!         
//!         GetStats = result
//!     End Function
//!     
//!     Public Function GetCharFrequency(text As String) As Object
//!         Dim dict As Object
//!         Dim i As Long
//!         Dim char As String
//!         
//!         Set dict = CreateObject("Scripting.Dictionary")
//!         
//!         For i = 1 To Len(text)
//!             char = Mid(text, i, 1)
//!             If dict.Exists(char) Then
//!                 dict(char) = dict(char) + 1
//!             Else
//!                 dict.Add char, 1
//!             End If
//!         Next i
//!         
//!         Set GetCharFrequency = dict
//!     End Function
//!     
//!     Public Function IsPalindrome(text As String) As Boolean
//!         Dim i As Long
//!         Dim length As Long
//!         
//!         length = Len(text)
//!         For i = 1 To length \ 2
//!             If Mid(text, i, 1) <> Mid(text, length - i + 1, 1) Then
//!                 IsPalindrome = False
//!                 Exit Function
//!             End If
//!         Next i
//!         
//!         IsPalindrome = True
//!     End Function
//! End Class
//!
//! ' Example 2: Text formatter
//! Public Class TextFormatter
//!     Public Function WordWrap(text As String, lineWidth As Long) As String
//!         Dim result As String
//!         Dim currentLine As String
//!         Dim words() As String
//!         Dim i As Long
//!         Dim word As String
//!         
//!         result = ""
//!         currentLine = ""
//!         words = Split(text, " ")
//!         
//!         For i = LBound(words) To UBound(words)
//!             word = words(i)
//!             
//!             If Len(currentLine) = 0 Then
//!                 currentLine = word
//!             ElseIf Len(currentLine) + 1 + Len(word) <= lineWidth Then
//!                 currentLine = currentLine & " " & word
//!             Else
//!                 result = result & currentLine & vbCrLf
//!                 currentLine = word
//!             End If
//!         Next i
//!         
//!         If Len(currentLine) > 0 Then
//!             result = result & currentLine
//!         End If
//!         
//!         WordWrap = result
//!     End Function
//!     
//!     Public Function JustifyText(text As String, width As Long) As String
//!         Dim words() As String
//!         Dim totalLen As Long
//!         Dim gaps As Long
//!         Dim extraSpaces As Long
//!         Dim spacesPerGap As Long
//!         Dim result As String
//!         Dim i As Long
//!         
//!         words = Split(text, " ")
//!         If UBound(words) = 0 Then
//!             JustifyText = text
//!             Exit Function
//!         End If
//!         
//!         ' Calculate total word length
//!         totalLen = 0
//!         For i = LBound(words) To UBound(words)
//!             totalLen = totalLen + Len(words(i))
//!         Next i
//!         
//!         gaps = UBound(words) - LBound(words)
//!         extraSpaces = width - totalLen
//!         spacesPerGap = extraSpaces \ gaps
//!         
//!         result = ""
//!         For i = LBound(words) To UBound(words)
//!             result = result & words(i)
//!             If i < UBound(words) Then
//!                 result = result & String(spacesPerGap, " ")
//!             End If
//!         Next i
//!         
//!         JustifyText = result
//!     End Function
//! End Class
//!
//! ' Example 3: Input validator
//! Public Class InputValidator
//!     Public Function ValidateEmail(email As String) As Boolean
//!         ' Basic email validation
//!         If Len(email) = 0 Then
//!             ValidateEmail = False
//!             Exit Function
//!         End If
//!         
//!         If InStr(email, "@") = 0 Then
//!             ValidateEmail = False
//!             Exit Function
//!         End If
//!         
//!         If InStr(email, ".") = 0 Then
//!             ValidateEmail = False
//!             Exit Function
//!         End If
//!         
//!         ValidateEmail = True
//!     End Function
//!     
//!     Public Function ValidatePassword(password As String) As String
//!         Dim errors As Collection
//!         Dim i As Long
//!         Dim char As String
//!         Dim hasUpper As Boolean
//!         Dim hasLower As Boolean
//!         Dim hasDigit As Boolean
//!         
//!         Set errors = New Collection
//!         
//!         If Len(password) < 8 Then
//!             errors.Add "Password must be at least 8 characters"
//!         End If
//!         
//!         If Len(password) > 128 Then
//!             errors.Add "Password must not exceed 128 characters"
//!         End If
//!         
//!         hasUpper = False
//!         hasLower = False
//!         hasDigit = False
//!         
//!         For i = 1 To Len(password)
//!             char = Mid(password, i, 1)
//!             If char >= "A" And char <= "Z" Then hasUpper = True
//!             If char >= "a" And char <= "z" Then hasLower = True
//!             If char >= "0" And char <= "9" Then hasDigit = True
//!         Next i
//!         
//!         If Not hasUpper Then errors.Add "Password must contain uppercase letter"
//!         If Not hasLower Then errors.Add "Password must contain lowercase letter"
//!         If Not hasDigit Then errors.Add "Password must contain digit"
//!         
//!         If errors.Count = 0 Then
//!             ValidatePassword = ""
//!         Else
//!             Dim msg As String
//!             msg = ""
//!             For i = 1 To errors.Count
//!                 msg = msg & errors(i) & vbCrLf
//!             Next i
//!             ValidatePassword = msg
//!         End If
//!     End Function
//!     
//!     Public Function ValidateLength(text As String, fieldName As String, _
//!                                    minLen As Long, maxLen As Long) As String
//!         Dim length As Long
//!         length = Len(text)
//!         
//!         If length < minLen Then
//!             ValidateLength = fieldName & " must be at least " & minLen & " characters"
//!         ElseIf length > maxLen Then
//!             ValidateLength = fieldName & " must not exceed " & maxLen & " characters"
//!         Else
//!             ValidateLength = ""
//!         End If
//!     End Function
//! End Class
//!
//! ' Example 4: String builder with size tracking
//! Public Class StringBuilder
//!     Private m_buffer As String
//!     Private m_length As Long
//!     
//!     Private Sub Class_Initialize()
//!         m_buffer = ""
//!         m_length = 0
//!     End Sub
//!     
//!     Public Sub Append(text As String)
//!         m_buffer = m_buffer & text
//!         m_length = m_length + Len(text)
//!     End Sub
//!     
//!     Public Sub AppendLine(Optional text As String = "")
//!         Append text & vbCrLf
//!     End Sub
//!     
//!     Public Function ToString() As String
//!         ToString = m_buffer
//!     End Function
//!     
//!     Public Property Get Length() As Long
//!         Length = m_length
//!     End Property
//!     
//!     Public Sub Clear()
//!         m_buffer = ""
//!         m_length = 0
//!     End Sub
//!     
//!     Public Function Substring(startIndex As Long, length As Long) As String
//!         If startIndex < 0 Or startIndex >= m_length Then
//!             Substring = ""
//!             Exit Function
//!         End If
//!         
//!         Substring = Mid(m_buffer, startIndex + 1, length)
//!     End Function
//! End Class
//! ```
//!
//! ## Error Handling
//!
//! Len handles special cases gracefully:
//!
//! ```vb
//! ' Empty string returns 0
//! Debug.Print Len("")                  ' 0
//!
//! ' Null propagates
//! Dim value As Variant
//! value = Null
//! Debug.Print IsNull(Len(value))       ' True
//!
//! ' Spaces are counted
//! Debug.Print Len("   ")               ' 3
//!
//! ' Special characters are counted
//! Debug.Print Len(vbCrLf)              ' 2 - CR + LF
//! Debug.Print Len(vbTab)               ' 1
//!
//! ' Safe pattern with Null check
//! Function SafeLen(value As Variant) As Long
//!     If IsNull(value) Then
//!         SafeLen = 0
//!     Else
//!         SafeLen = Len(value)
//!     End If
//! End Function
//! ```
//!
//! ## Performance Considerations
//!
//! - **Fast Operation**: `Len` is very fast, minimal overhead
//! - **Cache Result**: If checking length multiple times, cache the value
//! - **String Iteration**: For large strings, cache `Len` result in loop variable
//! - **No Side Effects**: `Len` does not modify the string
//!
//! Performance tips:
//! ```vb
//! ' Less efficient - calls Len every iteration
//! For i = 1 To Len(text)
//!     ' process
//! Next i
//!
//! ' More efficient - cache length
//! Dim length As Long
//! length = Len(text)
//! For i = 1 To length
//!     ' process
//! Next i
//! ```
//!
//! ## Best Practices
//!
//! 1. **Validate Input**: Always check string length for validation
//! 2. **`Null` Safety**: Handle `Null` values before calling `Len` if needed
//! 3. **Cache Results**: Store length in variable when used multiple times
//! 4. **Empty Check**: Use ```Len(str) = 0``` to check for empty strings
//! 5. **Loop Optimization**: Cache `Len` result before loops
//! 6. **Bounds Checking**: Verify length before substring operations
//! 7. **Fixed-Length Strings**: Remember `Len` returns declared length, not content
//! 8. **Database Fields**: Validate field lengths before database inserts
//!
//! ## Comparison with Related Functions
//!
//! | Function | Purpose | Returns | Use Case |
//! |----------|---------|---------|----------|
//! | `Len` | Get string length | `Long` | Character count |
//! | `LenB` | Get byte length | `Long` | Byte count (Unicode/DBCS) |
//! | `UBound` | Get array upper bound | `Long` | Array size calculation |
//! | `InStr` | Find substring | `Long` | Substring position |
//! | `Left`/`Right`/`Mid` | Extract substring | `String` | Substring extraction |
//! ## `Len` vs `LenB`
//!
//! ```vb
//! Dim text As String
//! text = "Hello"
//!
//! ' Len - character count
//! Debug.Print Len(text)                ' 5 characters
//!
//! ' LenB - byte count (may differ for Unicode)
//! Debug.Print LenB(text)               ' 10 bytes (2 bytes per char in Unicode)
//!
//! ' For ASCII characters, LenB is typically 2 * Len
//! ' For DBCS characters, varies by character
//! ```
//!
//! ## Fixed-Length vs Variable-Length Strings
//!
//! ```vb
//! ' Variable-length string - Len returns actual content length
//! Dim varStr As String
//! varStr = "ABC"
//! Debug.Print Len(varStr)              ' 3
//!
//! ' Fixed-length string - Len returns declared length
//! Dim fixStr As String * 10
//! fixStr = "ABC"
//! Debug.Print Len(fixStr)              ' 10 (includes padding spaces)
//! ```
//!
//! ## Platform and Version Notes
//!
//! - Available in all VB6 versions
//! - Part of VBA core functions
//! - Returns Long type
//! - Maximum string length in VB6 is approximately 2GB (theoretical)
//! - Practical limit much lower due to memory constraints
//! - For user-defined types, returns total structure size in bytes
//!
//! ## Limitations
//!
//! - Returns character count, not byte count (use `LenB` for bytes)
//! - Cannot measure array size directly (use ```UBound - LBound + 1```)
//! - For objects, may return unpredictable values
//! - For fixed-length strings, returns declared length, not trimmed length
//! - Does not distinguish between different whitespace characters
//! - No built-in way to get "visible" length (excluding control characters)
//!
//! ## Related Functions
//!
//! - `LenB`: Get byte length of string or variable
//! - `Left`/`Right`/`Mid`: Extract substrings (often used with Len)
//! - `InStr`/`InStrRev`: Find substring positions
//! - `Trim`/`LTrim`/`RTrim`: Remove whitespace
//! - `String`: Create string of repeated characters

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

/// Returns the number of characters in the string.
///
/// Characters are counted as Unicode scalar values (grapheme-breaking surrogate
/// pairs each count as one character, unlike VB6 which counts UTF-16 code units).
///
/// # Examples
///
/// ```
/// use vb6runtime::library::string::len;
/// use vb6runtime::value::{VBLong, VBString};
/// assert_eq!(len(&VBString::from("Hello")).unwrap(), VBLong::from(5));
/// assert_eq!(len(&VBString::from("")).unwrap(), VBLong::from(0));
/// ```
pub fn len(input: &VBString) -> VBResult<VBLong> {
    Ok(VBLong::from(input.as_str().chars().count() as i32))
}

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

    #[test]
    fn counts_characters() {
        assert_eq!(len(&VBString::from("Hello")).unwrap(), VBLong::from(5));
        assert_eq!(len(&VBString::from("")), Ok(VBLong::from(0)));
        assert_eq!(len(&VBString::from("A")).unwrap(), VBLong::from(1));
    }

    #[test]
    fn counts_unicode_characters() {
        assert_eq!(len(&VBString::from("héllo")).unwrap(), VBLong::from(5));
        assert_eq!(len(&VBString::from("")).unwrap(), VBLong::from(1));
    }
}