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
//! # Fix Function
//!
//! Returns the integer portion of a number.
//!
//! ## Syntax
//!
//! ```vb
//! Fix(number)
//! ```
//!
//! ## Parameters
//!
//! - `number` (Required): Any valid numeric expression. If number contains Null, Null is returned
//!
//! ## Return Value
//!
//! Returns the integer portion of a number:
//! - For positive numbers: Returns the largest integer less than or equal to number
//! - For negative numbers: Returns the first negative integer greater than or equal to number
//! - If number is Null: Returns Null
//! - Return type matches the input type (Integer, Long, Single, Double, Currency, Decimal)
//!
//! ## Remarks
//!
//! The Fix function truncates toward zero:
//!
//! - Removes the fractional part of a number
//! - Always truncates toward zero (removes decimal without rounding)
//! - For positive numbers, behaves like `Int` (same result)
//! - For negative numbers, different from `Int` (`Int` rounds down, `Fix` truncates)
//! - `Fix`(-8.4) returns -8, `Int`(-8.4) returns -9
//! - `Fix`(8.4) returns 8, `Int`(8.4) returns 8
//! - Does not round to nearest integer (use `Round` for rounding)
//! - The return type preserves the input numeric type
//! - More intuitive for most developers (truncation toward zero)
//! - Commonly used when you want to discard fractional parts
//! - For financial calculations, consider using `Round` or `CCur` instead
//!
//! ## Typical Uses
//!
//! 1. **Truncate Decimals**: Remove fractional part without rounding
//! 2. **Integer Conversion**: Convert floating-point to integer values
//! 3. **Financial Calculations**: Remove cents from currency values
//! 4. **Data Normalization**: Ensure whole number values
//! 5. **Display Formatting**: Show only whole number portion
//! 6. **Loop Bounds**: Convert float bounds to integers
//! 7. **Array Indices**: Ensure valid integer indices
//! 8. **Coordinate Processing**: Truncate pixel coordinates
//!
//! ## Basic Usage Examples
//!
//! ```vb
//! ' Example 1: Truncate positive number
//! Dim result As Integer
//! result = Fix(8.7)
//! Debug.Print result  ' Prints: 8
//!
//! ' Example 2: Truncate negative number
//! Dim result As Integer
//! result = Fix(-8.7)
//! Debug.Print result  ' Prints: -8 (truncates toward zero, not down)
//!
//! ' Example 3: Remove cents from currency
//! Dim price As Currency
//! Dim dollars As Currency
//! price = 19.99
//! dollars = Fix(price)
//! Debug.Print dollars  ' Prints: 19
//!
//! ' Example 4: Ensure integer for array index
//! Dim index As Long
//! Dim ratio As Double
//! ratio = 4.7
//! index = Fix(ratio)
//! value = items(index)
//! ```
//!
//! ## Common Patterns
//!
//! ```vb
//! ' Pattern 1: Truncate toward zero
//! Function Truncate(value As Double) As Long
//!     Truncate = Fix(value)
//! End Function
//!
//! ' Pattern 2: Get whole dollars from currency
//! Function GetWholeDollars(amount As Currency) As Long
//!     GetWholeDollars = Fix(amount)
//! End Function
//!
//! ' Pattern 3: Get cents from currency
//! Function GetCents(amount As Currency) As Long
//!     Dim wholeDollars As Currency
//!     wholeDollars = Fix(amount)
//!     GetCents = Fix((amount - wholeDollars) * 100)
//! End Function
//!
//! ' Pattern 4: Split number into whole and fractional parts
//! Sub SplitNumber(value As Double, ByRef wholePart As Long, ByRef fractionalPart As Double)
//!     wholePart = Fix(value)
//!     fractionalPart = value - wholePart
//! End Sub
//!
//! ' Pattern 5: Ensure positive truncation
//! Function TruncatePositive(value As Double) As Long
//!     ' Fix truncates toward zero
//!     ' For negative values, this gives different result than Int
//!     TruncatePositive = Fix(Abs(value)) * Sgn(value)
//! End Function
//!
//! ' Pattern 6: Convert to integer without rounding
//! Function ToIntegerNoRound(value As Double) As Long
//!     ToIntegerNoRound = Fix(value)
//! End Function
//!
//! ' Pattern 7: Remove decimal places for display
//! Function FormatWholeNumber(value As Double) As String
//!     FormatWholeNumber = CStr(Fix(value))
//! End Function
//!
//! ' Pattern 8: Calculate whole units
//! Function GetWholeUnits(quantity As Double) As Long
//!     GetWholeUnits = Fix(quantity)
//! End Function
//!
//! ' Pattern 9: Truncate time to hours
//! Function GetWholeHours(timeValue As Double) As Long
//!     Dim hours As Double
//!     hours = timeValue * 24  ' Convert days to hours
//!     GetWholeHours = Fix(hours)
//! End Function
//!
//! ' Pattern 10: Floor for positive, ceiling for negative
//! Function TruncateTowardZero(value As Double) As Long
//!     ' Fix already does this
//!     TruncateTowardZero = Fix(value)
//! End Function
//! ```
//!
//! ## Advanced Usage Examples
//!
//! ```vb
//! ' Example 1: Currency formatter class
//! Public Class CurrencyFormatter
//!     Public Function FormatAsDollarsAndCents(amount As Currency) As String
//!         Dim dollars As Long
//!         Dim cents As Long
//!         
//!         dollars = Fix(amount)
//!         cents = Fix(Abs((amount - dollars) * 100))
//!         
//!         FormatAsDollarsAndCents = "$" & dollars & "." & _
//!                                   Format$(cents, "00")
//!     End Function
//!     
//!     Public Function GetDollarPart(amount As Currency) As Long
//!         GetDollarPart = Fix(amount)
//!     End Function
//!     
//!     Public Function GetCentPart(amount As Currency) As Long
//!         Dim dollars As Currency
//!         dollars = Fix(amount)
//!         GetCentPart = Fix(Abs((amount - dollars) * 100))
//!     End Function
//!     
//!     Public Function RoundToDollars(amount As Currency) As Currency
//!         RoundToDollars = Fix(amount)
//!     End Function
//! End Class
//!
//! ' Example 2: Number splitter utility
//! Public Class NumberSplitter
//!     Private m_wholePart As Long
//!     Private m_fractionalPart As Double
//!     
//!     Public Sub Split(value As Double)
//!         m_wholePart = Fix(value)
//!         m_fractionalPart = value - m_wholePart
//!     End Sub
//!     
//!     Public Property Get WholePart() As Long
//!         WholePart = m_wholePart
//!     End Property
//!     
//!     Public Property Get FractionalPart() As Double
//!         FractionalPart = m_fractionalPart
//!     End Property
//!     
//!     Public Property Get HasFraction() As Boolean
//!         HasFraction = (m_fractionalPart <> 0)
//!     End Property
//!     
//!     Public Function Reconstruct() As Double
//!         Reconstruct = m_wholePart + m_fractionalPart
//!     End Function
//! End Class
//!
//! ' Example 3: Data truncator for normalization
//! Public Class DataTruncator
//!     Public Function TruncateArray(values() As Double) As Long()
//!         Dim result() As Long
//!         Dim i As Long
//!         
//!         ReDim result(LBound(values) To UBound(values))
//!         
//!         For i = LBound(values) To UBound(values)
//!             result(i) = Fix(values(i))
//!         Next i
//!         
//!         TruncateArray = result
//!     End Function
//!     
//!     Public Function TruncateToInteger(value As Double) As Long
//!         TruncateToInteger = Fix(value)
//!     End Function
//!     
//!     Public Function TruncateCollection(values As Collection) As Collection
//!         Dim result As New Collection
//!         Dim value As Variant
//!         
//!         For Each value In values
//!             If IsNumeric(value) Then
//!                 result.Add Fix(CDbl(value))
//!             Else
//!                 result.Add value
//!             End If
//!         Next value
//!         
//!         Set TruncateCollection = result
//!     End Function
//! End Class
//!
//! ' Example 4: Coordinate truncator
//! Public Class CoordinateTruncator
//!     Public Sub TruncatePoint(x As Double, y As Double, _
//!                             ByRef truncX As Long, ByRef truncY As Long)
//!         truncX = Fix(x)
//!         truncY = Fix(y)
//!     End Sub
//!     
//!     Public Function TruncateRectangle(left As Double, top As Double, _
//!                                       right As Double, bottom As Double) As Variant
//!         Dim coords(0 To 3) As Long
//!         
//!         coords(0) = Fix(left)
//!         coords(1) = Fix(top)
//!         coords(2) = Fix(right)
//!         coords(3) = Fix(bottom)
//!         
//!         TruncateRectangle = coords
//!     End Function
//!     
//!     Public Function GetPixelCoordinate(value As Double) As Long
//!         GetPixelCoordinate = Fix(value)
//!     End Function
//! End Class
//! ```
//!
//! ## Error Handling
//!
//! The Fix function can raise errors or return Null:
//!
//! - **Type Mismatch (Error 13)**: If number is not a numeric expression
//! - **Invalid use of Null (Error 94)**: If number is Null and result is assigned to non-Variant
//! - **Overflow (Error 6)**: If result exceeds the range of the target data type
//!
//! ```vb
//! On Error GoTo ErrorHandler
//! Dim result As Long
//! Dim value As Double
//!
//! value = -12.75
//! result = Fix(value)
//!
//! Debug.Print "Truncated value: " & result  ' Prints: -12
//! Exit Sub
//!
//! ErrorHandler:
//!     MsgBox "Error in Fix: " & Err.Description, vbCritical
//! ```
//!
//! ## Performance Considerations
//!
//! - **Fast Operation**: Fix is a very fast built-in function
//! - **Type Preservation**: Return type matches input type
//! - **No Rounding**: Faster than Round (simple truncation)
//! - **Alternative**: For floor operation, use Int (rounds down)
//! - **Currency**: More intuitive than Int for currency truncation
//!
//! ## Best Practices
//!
//! 1. **Understand Difference**: Know that Fix truncates toward zero, Int rounds down
//! 2. **Negative Numbers**: Be aware Fix(-8.7) = -8, Int(-8.7) = -9
//! 3. **Currency Operations**: Fix is more intuitive for removing cents
//! 4. **Type Awareness**: Be aware of return type matching input type
//! 5. **Null Handling**: Use Variant if input might be Null
//! 6. **No Rounding**: Use Round if you need rounding, not truncation
//! 7. **Documentation**: Comment when Fix vs Int choice matters
//!
//! ## Comparison with Other Functions
//!
//! | Function | Behavior with -8.7 | Behavior with 8.7 | Description |
//! |----------|-------------------|-------------------|-------------|
//! | `Fix` | -8 | 8 | Truncates toward zero |
//! | `Int` | -9 | 8 | Rounds down (floor) |
//! | `Round` | -9 | 9 | Rounds to nearest |
//! | `CLng` | -9 | 9 | Converts to `Long` with rounding |
//! | `CInt` | -9 | 9 | Converts to `Integer` with rounding |
//! | `\` | N/A | N/A | `Integer` division operator |
//! ## Platform and Version Notes
//!
//! - Available in all VB6 versions
//! - Consistent behavior across platforms
//! - Return type matches input numeric type
//! - Truncates toward zero (like C/C++/Java integer truncation)
//! - More intuitive than Int for most developers from other languages
//!
//! ## Limitations
//!
//! - Does not round to nearest (use `Round` for that)
//! - Behavior with negative numbers differs from `Int`
//! - Return type depends on input type (can cause overflow)
//! - Cannot specify decimal places (always removes all decimals)
//! - No control over rounding direction (always toward zero)
//!
//! ## Related Functions
//!
//! - `Int`: Returns `Integer` portion, rounding down (floor)
//! - `Round`: Rounds to nearest integer or specified decimal places
//! - `CInt`: Converts to `Integer` with rounding
//! - `CLng`: Converts to `Long` with rounding
//! - `Abs`: Absolute value (often used with `Fix`)
//! - `Sgn`: Sign of number (often used with `Fix`)

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

/// Implementation of the truncate (Fix) function.
///
/// VB6 behavior:
/// - `Fix(Null)` returns `Null`
/// - other values are coerced with numeric conversion rules and return `Double`
pub fn fix(value: &VBDouble) -> VBResult<VBVariant> {
    let numeric = value.as_f64();
    Ok(VBVariant::from_double(numeric.trunc()))
}

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

    fn assert_approx_eq(actual: f64, expected: f64) {
        if (actual == f64::INFINITY && expected == f64::INFINITY)
            || (actual == f64::NEG_INFINITY && expected == f64::NEG_INFINITY)
        {
            return;
        }

        let diff = (actual - expected).abs();
        assert!(
            diff < 1e-12,
            "expected {expected}, got {actual}, diff {diff}"
        );
    }

    #[test]
    fn computes_expected_doubles() {
        let result = fix(&VBDouble::from(5.0)).unwrap();
        assert_eq!(result, VBVariant::from_double((5.0_f64).trunc()));

        let result = fix(&VBDouble::from(-12.5)).unwrap();
        assert_eq!(result, VBVariant::from_double((-12.5_f64).trunc()));
    }

    #[test]
    fn returns_expected_values() {
        let VBVariant::Double(v) = fix(&VBDouble::from(0.0)).unwrap() else {
            panic!("expected Double")
        };
        assert_approx_eq(v, (0.0_f64).trunc());

        let VBVariant::Double(v) = fix(&VBDouble::from(1.0)).unwrap() else {
            panic!("expected Double")
        };
        assert_approx_eq(v, (1.0_f64).trunc());

        let VBVariant::Double(v) = fix(&VBDouble::from(-1.0)).unwrap() else {
            panic!("expected Double")
        };
        assert_approx_eq(v, (-1.0_f64).trunc());

        let VBVariant::Double(v) = fix(&VBDouble::from(-8.4)).unwrap() else {
            panic!("expected Double")
        };
        assert_approx_eq(v, (-8.4_f64).trunc());
    }

    #[test]
    fn conversion_rejects_non_numeric_values() {
        let err = VBDouble::try_from(&VBVariant::from_string("not-a-number")).unwrap_err();
        assert_eq!(err.number, err_number::TYPE_MISMATCH);
    }

    #[test]
    fn conversion_accepts_numeric_strings() {
        assert_eq!(
            VBDouble::try_from(&VBVariant::from_string("1.5")).unwrap(),
            VBDouble::from(1.5)
        );
    }
}