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
//! # `Right$` Function
//!
//! The `Right$` function in Visual Basic 6 returns a string containing a specified number of
//! characters from the right side (end) of a string. The dollar sign (`$`) suffix indicates
//! that this function always returns a `String` type, never a `Variant`.
//!
//! ## Syntax
//!
//! ```vb6
//! Right$(string, length)
//! ```
//!
//! ## Parameters
//!
//! - `string` - Required. String expression from which the rightmost characters are returned.
//!   If `string` contains `Null`, `Null` is returned.
//! - `length` - Required. Numeric expression indicating how many characters to return. If 0,
//!   a zero-length string ("") is returned. If greater than or equal to the number of characters
//!   in `string`, the entire string is returned.
//!
//! ## Return Value
//!
//! Returns a `String` containing the rightmost `length` characters of `string`.
//!
//! ## Behavior and Characteristics
//!
//! ### Length Handling
//!
//! - If `length` = 0: Returns an empty string ("")
//! - If `length` >= `Len(string)`: Returns the entire string
//! - If `length` < 0: Generates a runtime error (Invalid procedure call or argument)
//! - If `string` is empty (""): Returns an empty string regardless of `length`
//!
//! ### Null Handling
//!
//! - If `string` contains `Null`: Returns `Null`
//! - If `length` is `Null`: Generates a runtime error (Invalid use of Null)
//!
//! ### Type Differences: `Right$` vs `Right`
//!
//! - `Right$`: Always returns `String` type (never `Variant`)
//! - `Right`: Returns `Variant` (can propagate `Null` values)
//! - Use `Right$` when you need guaranteed `String` return type
//! - Use `Right` when working with potentially `Null` values
//!
//! ## Common Usage Patterns
//!
//! ### 1. Extract File Extension
//!
//! ```vb6
//! Function GetExtension(fileName As String) As String
//!     Dim dotPos As Integer
//!     dotPos = InStrRev(fileName, ".")
//!     If dotPos > 0 Then
//!         GetExtension = Right$(fileName, Len(fileName) - dotPos)
//!     Else
//!         GetExtension = ""
//!     End If
//! End Function
//!
//! Dim ext As String
//! ext = GetExtension("document.txt")  ' Returns "txt"
//! ```
//!
//! ### 2. Get Last N Characters
//!
//! ```vb6
//! Dim text As String
//! Dim suffix As String
//! text = "Hello World"
//! suffix = Right$(text, 5)  ' Returns "World"
//! ```
//!
//! ### 3. Extract Account Number Suffix
//!
//! ```vb6
//! Function GetAccountSuffix(accountNum As String) As String
//!     ' Get last 4 digits of account number
//!     GetAccountSuffix = Right$(accountNum, 4)
//! End Function
//!
//! Dim lastFour As String
//! lastFour = GetAccountSuffix("1234567890")  ' Returns "7890"
//! ```
//!
//! ### 4. Pad String to Fixed Width
//!
//! ```vb6
//! Function PadLeft(text As String, width As Integer) As String
//!     Dim padded As String
//!     padded = Space(width) & text
//!     PadLeft = Right$(padded, width)
//! End Function
//!
//! Dim result As String
//! result = PadLeft("42", 5)  ' Returns "   42"
//! ```
//!
//! ### 5. Extract Trailing Digits
//!
//! ```vb6
//! Function GetTrailingNumber(text As String) As String
//!     Dim i As Integer
//!     Dim numChars As Integer
//!     For i = Len(text) To 1 Step -1
//!         If Not IsNumeric(Mid$(text, i, 1)) Then Exit For
//!         numChars = numChars + 1
//!     Next i
//!     If numChars > 0 Then
//!         GetTrailingNumber = Right$(text, numChars)
//!     Else
//!         GetTrailingNumber = ""
//!     End If
//! End Function
//!
//! Dim num As String
//! num = GetTrailingNumber("Item123")  ' Returns "123"
//! ```
//!
//! ### 6. Time Component Extraction
//!
//! ```vb6
//! Function GetSeconds(timeStr As String) As String
//!     ' Extract seconds from "HH:MM:SS" format
//!     GetSeconds = Right$(timeStr, 2)
//! End Function
//!
//! Dim secs As String
//! secs = GetSeconds("14:30:45")  ' Returns "45"
//! ```
//!
//! ### 7. Validate String Suffix
//!
//! ```vb6
//! Function HasExtension(fileName As String, ext As String) As Boolean
//!     Dim fileExt As String
//!     fileExt = Right$(fileName, Len(ext))
//!     HasExtension = (UCase$(fileExt) = UCase$(ext))
//! End Function
//!
//! If HasExtension("report.pdf", ".pdf") Then
//!     Debug.Print "PDF file detected"
//! End If
//! ```
//!
//! ### 8. Extract Domain from Email
//!
//! ```vb6
//! Function GetEmailDomain(email As String) As String
//!     Dim atPos As Integer
//!     atPos = InStr(email, "@")
//!     If atPos > 0 Then
//!         GetEmailDomain = Right$(email, Len(email) - atPos)
//!     Else
//!         GetEmailDomain = ""
//!     End If
//! End Function
//!
//! Dim domain As String
//! domain = GetEmailDomain("user@example.com")  ' Returns "example.com"
//! ```
//!
//! ### 9. Format Currency Display
//!
//! ```vb6
//! Function FormatAmount(amount As String) As String
//!     ' Align decimal values
//!     Dim formatted As String
//!     formatted = Space(15) & amount
//!     FormatAmount = Right$(formatted, 15)
//! End Function
//! ```
//!
//! ### 10. Extract Path Component
//!
//! ```vb6
//! Function GetFileName(fullPath As String) As String
//!     Dim slashPos As Integer
//!     slashPos = InStrRev(fullPath, "\")
//!     If slashPos > 0 Then
//!         GetFileName = Right$(fullPath, Len(fullPath) - slashPos)
//!     Else
//!         GetFileName = fullPath
//!     End If
//! End Function
//!
//! Dim fileName As String
//! fileName = GetFileName("C:\Documents\report.txt")  ' Returns "report.txt"
//! ```
//!
//! ## Related Functions
//!
//! - `Right()` - Returns a `Variant` containing the rightmost characters (can handle `Null`)
//! - `Left$()` - Returns a specified number of characters from the left side of a string
//! - `Mid$()` - Returns a specified number of characters from any position in a string
//! - `Len()` - Returns the number of characters in a string
//! - `InStrRev()` - Finds the position of a substring searching from the end
//! - `Trim$()` - Removes leading and trailing spaces from a string
//! - `LTrim$()` - Removes leading spaces from a string
//! - `RTrim$()` - Removes trailing spaces from a string
//!
//! ## Best Practices
//!
//! ### When to Use `Right$` vs `Right`
//!
//! ```vb6
//! ' Use Right$ when you need a String
//! Dim fileName As String
//! fileName = Right$(fullPath, 10)  ' Type-safe, always returns String
//!
//! ' Use Right when working with Variants or Null values
//! Dim result As Variant
//! result = Right(variantValue, 5)  ' Can propagate Null
//! ```
//!
//! ### Validate Length Parameter
//!
//! ```vb6
//! Function SafeRight(text As String, length As Integer) As String
//!     If length < 0 Then
//!         SafeRight = ""
//!     ElseIf length >= Len(text) Then
//!         SafeRight = text
//!     Else
//!         SafeRight = Right$(text, length)
//!     End If
//! End Function
//! ```
//!
//! ### Check for Empty Strings
//!
//! ```vb6
//! If Len(text) > 0 Then
//!     suffix = Right$(text, 3)
//! Else
//!     suffix = ""
//! End If
//! ```
//!
//! ### Use with `InStrRev` for Parsing
//!
//! ```vb6
//! ' Find last occurrence and extract everything after it
//! Dim pos As Integer
//! pos = InStrRev(fullPath, "\")
//! If pos > 0 Then
//!     fileName = Right$(fullPath, Len(fullPath) - pos)
//! End If
//! ```
//!
//! ## Performance Considerations
//!
//! - `Right$` is very efficient for small to moderate length strings
//! - For very large strings, consider if you really need to extract characters
//! - Using `Right$` in tight loops with large strings may impact performance
//! - Consider caching the length if calling `Len()` repeatedly
//!
//! ```vb6
//! ' Less efficient
//! For i = 1 To 1000
//!     result = Right$(largeString, Len(largeString) - 10)
//! Next i
//!
//! ' More efficient
//! Dim strLen As Long
//! strLen = Len(largeString)
//! For i = 1 To 1000
//!     result = Right$(largeString, strLen - 10)
//! Next i
//! ```
//!
//! ## Common Pitfalls
//!
//! ### 1. Negative Length Values
//!
//! ```vb6
//! ' Runtime error: Invalid procedure call or argument
//! text = Right$("Hello", -1)  ' ERROR!
//!
//! ' Validate first
//! If length >= 0 Then
//!     text = Right$(source, length)
//! End If
//! ```
//!
//! ### 2. Off-by-One Errors
//!
//! ```vb6
//! ' Common mistake: forgetting to account for delimiter position
//! Dim pos As Integer
//! pos = InStrRev(path, "\")
//! ' Wrong: includes the backslash
//! fileName = Right$(path, pos)
//! ' Correct: excludes the backslash
//! fileName = Right$(path, Len(path) - pos)
//! ```
//!
//! ### 3. Not Checking String Length
//!
//! ```vb6
//! ' Potential issue: what if text is shorter than 10 characters?
//! suffix = Right$(text, 10)  ' Returns entire string if text.Length < 10
//!
//! ' Better: check first
//! If Len(text) >= 10 Then
//!     suffix = Right$(text, 10)
//! Else
//!     ' Handle short string case
//!     suffix = text
//! End If
//! ```
//!
//! ### 4. Assuming Fixed Positions
//!
//! ```vb6
//! ' Fragile: assumes extension is always 3 characters
//! ext = Right$(fileName, 3)  ' Fails for ".html", ".jpeg"
//!
//! ' Better: find the dot
//! Dim dotPos As Integer
//! dotPos = InStrRev(fileName, ".")
//! If dotPos > 0 Then
//!     ext = Right$(fileName, Len(fileName) - dotPos)
//! End If
//! ```
//!
//! ### 5. Null Value Handling
//!
//! ```vb6
//! ' Right$ with Null causes runtime error
//! Dim result As String
//! result = Right$(nullValue, 5)  ' ERROR if nullValue is Null
//!
//! ' Protect against Null
//! If Not IsNull(value) Then
//!     result = Right$(value, 5)
//! Else
//!     result = ""
//! End If
//! ```
//!
//! ## Limitations
//!
//! - Cannot handle `Null` values (use `Right` variant function instead)
//! - No built-in trimming of whitespace (combine with `RTrim$` if needed)
//! - Negative `length` values cause runtime errors
//! - Works with characters, not bytes (use `RightB$` for byte-level operations)
//! - No Unicode-specific version (VB6 uses UCS-2 internally)
//! - Cannot extract from right based on delimiter (must calculate length manually)

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

/// Returns the specified number of characters from the right side of the string.
/// The `$` suffix indicates this function returns a `String` type (not `Variant`).
///
/// A `length` of 0 returns an empty string; a `length` greater than the number
/// of characters returns the entire string. Characters are counted as Unicode
/// scalar values.
///
/// # Errors
///
/// Returns error 5 (`Invalid procedure call or argument`) when `length` is negative.
pub fn right_dollar(input: &VBString, length: &VBLong) -> VBResult<VBString> {
    let length = length.as_i32();
    if length < 0 {
        return Err(VBError::with_description(
            err_number::INVALID_PROCEDURE_CALL,
            "Invalid length",
        ));
    }

    let chars: Vec<char> = input.as_str().chars().collect();
    let skip = chars.len().saturating_sub(length as usize);
    Ok(VBString::from(
        chars.into_iter().skip(skip).collect::<String>(),
    ))
}

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

    #[test]
    fn returns_rightmost_characters() {
        assert_eq!(
            right_dollar(&VBString::from("Hello"), &VBLong::from(3)).unwrap(),
            VBString::from("llo")
        );
        assert_eq!(
            right_dollar(&VBString::from("Hello"), &VBLong::from(0)).unwrap(),
            VBString::from("")
        );
    }

    #[test]
    fn length_greater_than_string_returns_all() {
        assert_eq!(
            right_dollar(&VBString::from("Hello"), &VBLong::from(10)).unwrap(),
            VBString::from("Hello")
        );
    }

    #[test]
    fn handles_unicode() {
        assert_eq!(
            right_dollar(&VBString::from("héllo"), &VBLong::from(2)).unwrap(),
            VBString::from("lo")
        );
    }

    #[test]
    fn rejects_negative_length() {
        assert_eq!(
            right_dollar(&VBString::from("Hello"), &VBLong::from(-1))
                .unwrap_err()
                .number,
            err_number::INVALID_PROCEDURE_CALL
        );
    }
}