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
//! # `AscB` Function
//!
//! Returns an `Integer` representing the byte value (ANSI code) of the first byte in a string.
//! The "B" suffix indicates this is the byte (ANSI) version of the `Asc` function.
//!
//! ## Syntax
//!
//! ```vb
//! AscB(string)
//! ```
//!
//! ## Parameters
//!
//! - **string**: Required. Any valid string expression. If the string contains no characters,
//!   a runtime error occurs (Error 5: Invalid procedure call or argument).
//!
//! ## Returns
//!
//! Returns an `Integer` (0-255) representing the byte value of the first byte in the string.
//!
//! ## Remarks
//!
//! - `AscB` returns the ANSI byte value of the first byte in a string, not the character code.
//! - The B suffix stands for "Byte", distinguishing it from the Unicode `AscW` function.
//! - For single-byte character sets (ANSI), `AscB` and `Asc` return the same value.
//! - For multi-byte character sets (like DBCS), `AscB` returns only the first byte of a multi-byte character.
//! - The return value is always in the range 0-255.
//! - If the string is empty (`""`), a runtime error occurs (Error 5).
//! - `AscB` is useful for low-level byte operations and working with binary data.
//! - The inverse function is `ChrB`, which converts a byte value back to a character.
//! - For Unicode code points, use `AscW` instead of `AscB`.
//!
//! ## Typical Uses
//!
//! 1. **Byte-level text analysis** - Examine individual bytes in ANSI strings
//! 2. **Binary data processing** - Extract byte values from binary strings
//! 3. **File format parsing** - Read byte values from file headers or data structures
//! 4. **Legacy protocol support** - Work with protocols that use ANSI byte values
//! 5. **Character encoding detection** - Analyze byte patterns in text
//! 6. **Checksum calculations** - Use byte values for checksums or hash calculations
//! 7. **Low-level string comparison** - Compare strings at the byte level
//!
//! ## Basic Examples
//!
//! ```vb
//! ' Example 1: Simple byte value
//! Dim byteVal As Integer
//! byteVal = AscB("A")  ' Returns 65
//! ```
//!
//! ```vb
//! ' Example 2: Extended ANSI character
//! Dim code As Integer
//! code = AscB("é")  ' Returns 233 (in Windows-1252 code page)
//! ```
//!
//! ```vb
//! ' Example 3: First byte of multi-byte character
//! ' In DBCS (Double Byte Character Set) systems
//! Dim firstByte As Integer
//! firstByte = AscB("中")  ' Returns first byte only (varies by encoding)
//! ```
//!
//! ```vb
//! ' Example 4: Control character
//! Dim tabByte As Integer
//! tabByte = AscB(vbTab)  ' Returns 9
//! ```
//!
//! ## Common Patterns
//!
//! ### Validate ASCII Range
//! ```vb
//! Function IsASCII(char As String) As Boolean
//!     If Len(char) = 0 Then Exit Function
//!     IsASCII = (AscB(char) < 128)
//! End Function
//! ```
//!
//! ### Check for Control Characters
//! ```vb
//! Function IsControlChar(char As String) As Boolean
//!     If Len(char) = 0 Then Exit Function
//!     Dim byteVal As Integer
//!     byteVal = AscB(char)
//!     IsControlChar = (byteVal < 32 Or byteVal = 127)
//! End Function
//! ```
//!
//! ### Compare Byte Values
//! ```vb
//! Function CompareBytes(str1 As String, str2 As String) As Integer
//!     If Len(str1) = 0 Or Len(str2) = 0 Then Exit Function
//!     CompareBytes = AscB(str1) - AscB(str2)
//! End Function
//! ```
//!
//! ### Extract Byte Array
//! ```vb
//! Function GetByteArray(text As String) As Variant
//!     Dim bytes() As Integer
//!     Dim i As Long
//!     
//!     If Len(text) = 0 Then Exit Function
//!     
//!     ReDim bytes(1 To Len(text))
//!     For i = 1 To Len(text)
//!         bytes(i) = AscB(Mid(text, i, 1))
//!     Next i
//!     
//!     GetByteArray = bytes
//! End Function
//! ```
//!
//! ### Calculate Simple Checksum
//! ```vb
//! Function SimpleChecksum(text As String) As Long
//!     Dim i As Long
//!     Dim checksum As Long
//!     
//!     For i = 1 To Len(text)
//!         checksum = checksum + AscB(Mid(text, i, 1))
//!     Next i
//!     
//!     SimpleChecksum = checksum Mod 256
//! End Function
//! ```
//!
//! ### Detect Line Endings
//! ```vb
//! Function DetectLineEnding(text As String) As String
//!     Dim i As Long
//!     Dim byteVal As Integer
//!     
//!     For i = 1 To Len(text)
//!         byteVal = AscB(Mid(text, i, 1))
//!         If byteVal = 13 Then  ' CR
//!             If i < Len(text) And AscB(Mid(text, i + 1, 1)) = 10 Then
//!                 DetectLineEnding = "CRLF"
//!             Else
//!                 DetectLineEnding = "CR"
//!             End If
//!             Exit Function
//!         ElseIf byteVal = 10 Then  ' LF
//!             DetectLineEnding = "LF"
//!             Exit Function
//!         End If
//!     Next i
//! End Function
//! ```
//!
//! ### Hex Dump Generator
//! ```vb
//! Function ByteToHex(char As String) As String
//!     If Len(char) = 0 Then Exit Function
//!     Dim byteVal As Integer
//!     byteVal = AscB(char)
//!     ByteToHex = Right("0" & Hex(byteVal), 2)
//! End Function
//! ```
//!
//! ### Case-Insensitive Byte Compare
//! ```vb
//! Function ByteEqualsIgnoreCase(char1 As String, char2 As String) As Boolean
//!     If Len(char1) = 0 Or Len(char2) = 0 Then Exit Function
//!     
//!     Dim byte1 As Integer, byte2 As Integer
//!     byte1 = AscB(char1)
//!     byte2 = AscB(char2)
//!     
//!     ' Convert uppercase to lowercase (65-90 to 97-122)
//!     If byte1 >= 65 And byte1 <= 90 Then byte1 = byte1 + 32
//!     If byte2 >= 65 And byte2 <= 90 Then byte2 = byte2 + 32
//!     
//!     ByteEqualsIgnoreCase = (byte1 = byte2)
//! End Function
//! ```
//!
//! ### Filter Printable Characters
//! ```vb
//! Function FilterPrintable(text As String) As String
//!     Dim result As String
//!     Dim i As Long
//!     Dim byteVal As Integer
//!     
//!     For i = 1 To Len(text)
//!         byteVal = AscB(Mid(text, i, 1))
//!         If byteVal >= 32 And byteVal <= 126 Then
//!             result = result & Mid(text, i, 1)
//!         End If
//!     Next i
//!     
//!     FilterPrintable = result
//! End Function
//! ```
//!
//! ### Encode for URL
//! ```vb
//! Function NeedsURLEncoding(char As String) As Boolean
//!     If Len(char) = 0 Then Exit Function
//!     
//!     Dim byteVal As Integer
//!     byteVal = AscB(char)
//!     
//!     ' Check if character needs encoding
//!     If (byteVal >= 48 And byteVal <= 57) Or _
//!        (byteVal >= 65 And byteVal <= 90) Or _
//!        (byteVal >= 97 And byteVal <= 122) Then
//!         NeedsURLEncoding = False
//!     Else
//!         NeedsURLEncoding = True
//!     End If
//! End Function
//! ```
//!
//! ## Advanced Examples
//!
//! ### Binary Data Parser
//! ```vb
//! Function ParseBinaryHeader(data As String) As Variant
//!     ' Parse a binary file header (example: BMP format)
//!     Dim header As Variant
//!     ReDim header(1 To 4)
//!     
//!     If Len(data) < 4 Then Exit Function
//!     
//!     ' Read signature bytes
//!     header(1) = AscB(Mid(data, 1, 1))  ' 'B' = 66
//!     header(2) = AscB(Mid(data, 2, 1))  ' 'M' = 77
//!     
//!     ' Read size bytes (little-endian)
//!     header(3) = AscB(Mid(data, 3, 1))
//!     header(4) = AscB(Mid(data, 4, 1))
//!     
//!     ParseBinaryHeader = header
//! End Function
//! ```
//!
//! ### XOR Encryption/Decryption
//! ```vb
//! Function XOREncrypt(text As String, key As String) As String
//!     Dim result As String
//!     Dim i As Long, keyPos As Long
//!     Dim textByte As Integer, keyByte As Integer
//!     
//!     If Len(text) = 0 Or Len(key) = 0 Then Exit Function
//!     
//!     keyPos = 1
//!     For i = 1 To Len(text)
//!         textByte = AscB(Mid(text, i, 1))
//!         keyByte = AscB(Mid(key, keyPos, 1))
//!         
//!         result = result & ChrB(textByte Xor keyByte)
//!         
//!         keyPos = keyPos + 1
//!         If keyPos > Len(key) Then keyPos = 1
//!     Next i
//!     
//!     XOREncrypt = result
//! End Function
//! ```
//!
//! ### CSV Field Parser with Byte Analysis
//! ```vb
//! Function ParseCSVField(field As String) As String
//!     Dim result As String
//!     Dim i As Long
//!     Dim byteVal As Integer
//!     Dim inQuotes As Boolean
//!     
//!     For i = 1 To Len(field)
//!         byteVal = AscB(Mid(field, i, 1))
//!         
//!         Select Case byteVal
//!             Case 34  ' Double quote
//!                 inQuotes = Not inQuotes
//!             Case 44  ' Comma
//!                 If Not inQuotes Then Exit Function
//!                 result = result & Chr(byteVal)
//!             Case Else
//!                 result = result & Chr(byteVal)
//!         End Select
//!     Next i
//!     
//!     ParseCSVField = result
//! End Function
//! ```
//!
//! ### Character Set Validator
//! ```vb
//! Function ValidateCharacterSet(text As String, validSet As String) As Boolean
//!     Dim i As Long, j As Long
//!     Dim textByte As Integer
//!     Dim found As Boolean
//!     
//!     For i = 1 To Len(text)
//!         textByte = AscB(Mid(text, i, 1))
//!         found = False
//!         
//!         For j = 1 To Len(validSet)
//!             If textByte = AscB(Mid(validSet, j, 1)) Then
//!                 found = True
//!                 Exit For
//!             End If
//!         Next j
//!         
//!         If Not found Then
//!             ValidateCharacterSet = False
//!             Exit Function
//!         End If
//!     Next i
//!     
//!     ValidateCharacterSet = True
//! End Function
//! ```
//!
//! ## Error Handling
//!
//! ```vb
//! Function SafeAscB(text As String) As Integer
//!     On Error GoTo ErrorHandler
//!     
//!     If Len(text) = 0 Then
//!         SafeAscB = -1  ' Error indicator
//!         Exit Function
//!     End If
//!     
//!     SafeAscB = AscB(text)
//!     Exit Function
//!     
//! ErrorHandler:
//!     SafeAscB = -1
//! End Function
//! ```
//!
//! ## Performance Notes
//!
//! - `AscB` is a very fast operation with minimal overhead
//! - When processing long strings byte-by-byte, consider using `Mid` function efficiently
//! - For repeated byte extraction, the performance is generally good
//! - Avoid calling `AscB` in tight loops if the value can be cached
//! - `AscB` is faster than string comparison for byte-level operations
//!
//! ## Best Practices
//!
//! 1. **Validate input** - Always check for empty strings before calling `AscB`
//! 2. **Use for byte operations** - Prefer `AscB` over `Asc` when working with binary data
//! 3. **Handle errors** - Wrap `AscB` calls in error handlers when processing untrusted input
//! 4. **Document byte values** - Use constants or comments to explain non-obvious byte values
//! 5. **Consider encoding** - Be aware of system code page when working with extended ANSI
//! 6. **Use with `ChrB`** - Pair with `ChrB` for byte-to-character conversions
//! 7. **Test edge cases** - Verify behavior with empty strings, control characters, and extended ANSI
//!
//! ## Comparison with Related Functions
//!
//! | Function | Returns | Character Set | Use Case |
//! |----------|---------|---------------|----------|
//! | `Asc` | Integer (0-255 or Unicode) | System default | General character codes |
//! | `AscB` | Integer (0-255) | ANSI byte value | Byte-level operations |
//! | `AscW` | Integer (0-65535) | Unicode code point | International text |
//! | `ChrB` | String (ANSI) | ANSI (inverse) | Convert byte to character |
//!
//! ## Common Byte Values Reference
//!
//! Some commonly used byte values with `AscB`:
//!
//! - **0**: Null character (NUL)
//! - **9**: Tab (HT)
//! - **10**: Line feed (LF)
//! - **13**: Carriage return (CR)
//! - **32**: Space
//! - **48-57**: Digits '0'-'9'
//! - **65-90**: Uppercase letters 'A'-'Z'
//! - **97-122**: Lowercase letters 'a'-'z'
//! - **127**: Delete (DEL)
//! - **128-255**: Extended ANSI (varies by code page)
//!
//! ## Platform Notes
//!
//! - On Windows systems, `AscB` uses the system's ANSI code page (e.g., Windows-1252)
//! - Different code pages may interpret bytes 128-255 differently
//! - For portable code, stick to ASCII range (0-127) when possible
//! - On older systems (Windows 95/98/ME), ANSI encoding is the native string format
//! - On modern Windows (NT-based), strings are Unicode internally but `AscB` still returns ANSI bytes
//!
//! ## Limitations
//!
//! - Returns only the first byte, not the full character in multi-byte encodings
//! - Cannot handle Unicode characters outside the ANSI range (0-255) properly
//! - Runtime error occurs with empty strings
//! - Code page dependent for extended ANSI characters (128-255)
//! - Not suitable for Unicode text processing (use `AscW` instead)

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

/// Returns the Windows-1252 (ANSI) byte value of the first byte in the string.
///
/// Because Windows-1252 is a single-byte code page, this is identical to
/// [`super::asc::asc`]; it exists to mirror the VB6 API for byte-level code.
///
/// # Errors
///
/// Returns error 5 (`Invalid procedure call or argument`) when `input` is empty
/// or its first character cannot be represented in Windows-1252.
pub fn ascb(input: &VBString) -> VBResult<VBLong> {
    Ok(VBLong::from(
        super::ansi::encode_first_byte(input.as_str()).map(i32::from)?,
    ))
}

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

    #[test]
    fn returns_first_byte_of_ascii() {
        assert_eq!(ascb(&VBString::from("A")).unwrap(), VBLong::from(65));
        assert_eq!(ascb(&VBString::from("Apple")).unwrap(), VBLong::from(65));
    }

    #[test]
    fn returns_first_byte_of_ansi_extended() {
        assert_eq!(ascb(&VBString::from("é")).unwrap(), VBLong::from(233));
        assert_eq!(ascb(&VBString::from("")).unwrap(), VBLong::from(128));
    }

    #[test]
    fn rejects_unrepresentable_characters() {
        assert_eq!(
            ascb(&VBString::from("😀")).unwrap_err().number,
            err_number::INVALID_PROCEDURE_CALL
        );
    }

    #[test]
    fn rejects_empty_string() {
        assert_eq!(
            ascb(&VBString::from("")).unwrap_err().number,
            err_number::INVALID_PROCEDURE_CALL
        );
    }
}