oracle-rs 0.1.7

Pure Rust driver for Oracle databases - no OCI/ODPI-C required
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
//! Oracle NUMBER encoding and decoding
//!
//! Oracle NUMBER is stored in a variable-length format:
//! - First byte: exponent (with sign encoding)
//! - Subsequent bytes: mantissa digits in base-100
//!
//! For positive numbers: exponent byte has high bit set, mantissa bytes are value + 1
//! For negative numbers: exponent byte is inverted, mantissa bytes are 101 - value,
//!                       and a trailing 102 byte is added (if not at max digits)

use crate::error::{Error, Result};

/// Maximum number of digits in an Oracle NUMBER
const MAX_DIGITS: usize = 40;

/// Maximum characters in a number string representation
const MAX_STRING_CHARS: usize = 172;

/// Decoded Oracle NUMBER as a string representation
#[derive(Debug, Clone)]
pub struct OracleNumber {
    /// String representation of the number
    pub value: String,
    /// Whether the number is an integer (no decimal point)
    pub is_integer: bool,
    /// Whether this is the maximum negative value (-1e126)
    pub is_max_negative: bool,
}

impl OracleNumber {
    /// Create a new Oracle number from string representation
    pub fn new(value: impl Into<String>) -> Self {
        let value = value.into();
        let is_integer = !value.contains('.');
        Self {
            value,
            is_integer,
            is_max_negative: false,
        }
    }

    /// Get the string value
    pub fn as_str(&self) -> &str {
        &self.value
    }

    /// Try to convert to i64
    pub fn to_i64(&self) -> Result<i64> {
        if self.is_max_negative {
            return Err(Error::DataConversionError(
                "Maximum negative Oracle number cannot be represented as i64".to_string(),
            ));
        }
        self.value
            .parse()
            .map_err(|e| Error::DataConversionError(format!("Cannot parse as i64: {}", e)))
    }

    /// Try to convert to f64
    pub fn to_f64(&self) -> Result<f64> {
        if self.is_max_negative {
            return Ok(-1e126);
        }
        self.value
            .parse()
            .map_err(|e| Error::DataConversionError(format!("Cannot parse as f64: {}", e)))
    }
}

/// Decode an Oracle NUMBER from wire format bytes
///
/// Oracle NUMBER format:
/// - Byte 0: Exponent byte (with sign encoding)
/// - Bytes 1..n: Mantissa digits in base-100 format
pub fn decode_oracle_number(data: &[u8]) -> Result<OracleNumber> {
    if data.is_empty() {
        return Err(Error::DataConversionError(
            "Empty data for Oracle NUMBER".to_string(),
        ));
    }

    let exponent_byte = data[0];
    let is_positive = (exponent_byte & 0x80) != 0;

    // Decode the exponent
    let exponent = if is_positive {
        (exponent_byte as i16) - 193
    } else {
        (!exponent_byte as i16) - 193
    };

    let mut decimal_point_index = (exponent * 2 + 2) as i32;

    // Special case: single byte means zero (positive) or -1e126 (negative)
    if data.len() == 1 {
        if is_positive {
            return Ok(OracleNumber::new("0"));
        } else {
            return Ok(OracleNumber {
                value: String::new(),
                is_integer: false,
                is_max_negative: true,
            });
        }
    }

    // Check for trailing 102 byte in negative numbers
    let mantissa_len = if !is_positive && data.len() > 1 && data[data.len() - 1] == 102 {
        data.len() - 2
    } else {
        data.len() - 1
    };

    // Decode mantissa digits
    let mut digits = Vec::with_capacity(MAX_DIGITS);
    for i in 0..mantissa_len {
        let byte = data[i + 1];
        let value = if is_positive {
            byte.wrapping_sub(1)
        } else {
            101u8.wrapping_sub(byte)
        };

        // First digit of the pair
        let digit1 = value / 10;
        // Handle leading zeros
        if digit1 == 0 && digits.is_empty() {
            decimal_point_index -= 1;
        } else if digit1 == 10 {
            // Overflow case
            digits.push(1);
            digits.push(0);
            decimal_point_index += 1;
        } else if digit1 != 0 || !digits.is_empty() {
            digits.push(digit1);
        }

        // Second digit of the pair
        let digit2 = value % 10;
        if digit2 != 0 || i < mantissa_len - 1 {
            digits.push(digit2);
        }
    }

    // Remove trailing zeros (for integer detection)
    while !digits.is_empty() && digits[digits.len() - 1] == 0 {
        if (digits.len() as i32) <= decimal_point_index {
            break;
        }
        digits.pop();
    }

    // Build string representation
    let mut result = String::with_capacity(MAX_STRING_CHARS);

    if !is_positive {
        result.push('-');
    }

    let is_integer;
    if decimal_point_index <= 0 {
        result.push('0');
        result.push('.');
        is_integer = false;
        for _ in decimal_point_index..0 {
            result.push('0');
        }
        for d in &digits {
            result.push(char::from(b'0' + d));
        }
    } else {
        is_integer = decimal_point_index as usize >= digits.len();
        for (i, d) in digits.iter().enumerate() {
            if i > 0 && i as i32 == decimal_point_index {
                result.push('.');
            }
            result.push(char::from(b'0' + d));
        }
        // Add trailing zeros for integers
        if decimal_point_index as usize > digits.len() {
            for _ in digits.len()..decimal_point_index as usize {
                result.push('0');
            }
        }
    }

    if result.is_empty() || result == "-" {
        result = "0".to_string();
    }

    Ok(OracleNumber {
        value: result,
        is_integer,
        is_max_negative: false,
    })
}

/// Encode a number string to Oracle NUMBER wire format
pub fn encode_oracle_number(value: &str) -> Result<Vec<u8>> {
    let value = value.trim();

    if value.is_empty() {
        return Err(Error::DataConversionError(
            "Empty string cannot be encoded as Oracle NUMBER".to_string(),
        ));
    }

    if value.len() > MAX_STRING_CHARS {
        return Err(Error::DataConversionError(
            "Number string too long for Oracle NUMBER".to_string(),
        ));
    }

    let bytes = value.as_bytes();
    let mut pos = 0;

    // Check for negative sign
    let is_negative = bytes.first() == Some(&b'-');
    if is_negative {
        pos += 1;
    }

    // Parse digits before decimal point
    let mut digits = Vec::with_capacity(MAX_DIGITS);
    let mut decimal_point_index: i32;

    while pos < bytes.len() {
        let b = bytes[pos];
        if b == b'.' || b == b'e' || b == b'E' {
            break;
        }
        if !b.is_ascii_digit() {
            return Err(Error::DataConversionError(format!(
                "Invalid character '{}' in number",
                char::from(b)
            )));
        }
        let digit = b - b'0';
        if digit != 0 || !digits.is_empty() {
            digits.push(digit);
        }
        pos += 1;
    }
    decimal_point_index = digits.len() as i32;

    // Parse digits after decimal point
    if pos < bytes.len() && bytes[pos] == b'.' {
        pos += 1;
        while pos < bytes.len() {
            let b = bytes[pos];
            if b == b'e' || b == b'E' {
                break;
            }
            if !b.is_ascii_digit() {
                return Err(Error::DataConversionError(format!(
                    "Invalid character '{}' in number",
                    char::from(b)
                )));
            }
            let digit = b - b'0';
            if digit == 0 && digits.is_empty() {
                decimal_point_index -= 1;
            } else {
                digits.push(digit);
            }
            pos += 1;
        }
    }

    // Parse exponent
    if pos < bytes.len() && (bytes[pos] == b'e' || bytes[pos] == b'E') {
        pos += 1;
        let exp_negative = if pos < bytes.len() && bytes[pos] == b'-' {
            pos += 1;
            true
        } else {
            if pos < bytes.len() && bytes[pos] == b'+' {
                pos += 1;
            }
            false
        };

        let exp_start = pos;
        while pos < bytes.len() && bytes[pos].is_ascii_digit() {
            pos += 1;
        }

        if exp_start == pos {
            return Err(Error::DataConversionError(
                "Missing exponent value".to_string(),
            ));
        }

        let exp: i32 = std::str::from_utf8(&bytes[exp_start..pos])
            .unwrap()
            .parse()
            .map_err(|_| Error::DataConversionError("Invalid exponent".to_string()))?;

        decimal_point_index += if exp_negative { -exp } else { exp };
    }

    // Remove trailing zeros
    while !digits.is_empty() && digits[digits.len() - 1] == 0 {
        digits.pop();
    }

    // Check bounds
    if digits.len() > MAX_DIGITS || decimal_point_index > 126 || decimal_point_index < -129 {
        return Err(Error::DataConversionError(
            "Number out of range for Oracle NUMBER".to_string(),
        ));
    }

    // Zero is a special case
    if digits.is_empty() {
        return Ok(vec![128]);
    }

    // Adjust for odd exponent
    let prepend_zero = decimal_point_index % 2 == 1;
    if prepend_zero && !digits.is_empty() {
        digits.push(0);
        decimal_point_index += 1;
    }

    // Ensure even number of digits
    if digits.len() % 2 == 1 {
        digits.push(0);
    }

    let num_pairs = digits.len() / 2;

    // Build result
    let mut result = Vec::with_capacity(num_pairs + 2);

    // Encode exponent
    let exponent_on_wire = ((decimal_point_index / 2) + 192) as i8;
    let exponent_byte = if is_negative {
        !exponent_on_wire as u8
    } else {
        exponent_on_wire as u8
    };
    result.push(exponent_byte);

    // Encode mantissa
    let mut digit_pos = 0;
    for pair_num in 0..num_pairs {
        let pair_value = if pair_num == 0 && prepend_zero {
            let v = digits[digit_pos];
            digit_pos += 1;
            v
        } else {
            let v = digits[digit_pos] * 10 + digits[digit_pos + 1];
            digit_pos += 2;
            v
        };

        let encoded = if is_negative {
            101 - pair_value
        } else {
            pair_value + 1
        };
        result.push(encoded);
    }

    // Add trailing 102 for negative numbers (if not at max length)
    if is_negative && num_pairs < 20 {
        result.push(102);
    }

    Ok(result)
}

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

    #[test]
    fn test_decode_zero() {
        let data = vec![128];
        let num = decode_oracle_number(&data).unwrap();
        assert_eq!(num.value, "0");
        assert!(num.is_integer);
    }

    #[test]
    fn test_decode_positive_integer() {
        // 123 encoded
        let data = vec![0xc2, 0x02, 0x18]; // exponent=1, digits=[1,23]
        let num = decode_oracle_number(&data).unwrap();
        assert_eq!(num.value, "123");
        assert!(num.is_integer);
    }

    #[test]
    fn test_decode_negative_integer() {
        // -123 encoded
        let data = vec![0x3d, 0x64, 0x4e, 0x66]; // ~exponent, 101-digits, 102
        let num = decode_oracle_number(&data).unwrap();
        assert_eq!(num.value, "-123");
    }

    #[test]
    fn test_decode_decimal() {
        // 1.5 encoded
        let data = vec![0xc1, 0x02, 0x33]; // exponent=0, digits=[1,50]
        let num = decode_oracle_number(&data).unwrap();
        assert_eq!(num.value, "1.5");
        assert!(!num.is_integer);
    }

    #[test]
    fn test_encode_zero() {
        let encoded = encode_oracle_number("0").unwrap();
        assert_eq!(encoded, vec![128]);
    }

    #[test]
    fn test_encode_positive_integer() {
        let encoded = encode_oracle_number("123").unwrap();
        let decoded = decode_oracle_number(&encoded).unwrap();
        assert_eq!(decoded.value, "123");
    }

    #[test]
    fn test_encode_negative_integer() {
        let encoded = encode_oracle_number("-456").unwrap();
        let decoded = decode_oracle_number(&encoded).unwrap();
        assert_eq!(decoded.value, "-456");
    }

    #[test]
    fn test_encode_decimal() {
        let encoded = encode_oracle_number("3.14159").unwrap();
        let decoded = decode_oracle_number(&encoded).unwrap();
        assert!(decoded.value.starts_with("3.14159"));
    }

    #[test]
    fn test_encode_scientific() {
        let encoded = encode_oracle_number("1.5e10").unwrap();
        let decoded = decode_oracle_number(&encoded).unwrap();
        assert_eq!(decoded.value, "15000000000");
    }

    #[test]
    fn test_roundtrip_various_numbers() {
        let test_values = ["1", "99", "100", "999", "1000", "-1", "-99", "-100"];

        for val in test_values {
            let encoded = encode_oracle_number(val).unwrap();
            let decoded = decode_oracle_number(&encoded).unwrap();
            // Remove trailing zeros for comparison
            let expected = val.trim_start_matches('0');
            let got = decoded.value.trim_start_matches('0');
            assert!(
                expected == got || val == decoded.value,
                "Roundtrip failed for {}: got {}",
                val,
                decoded.value
            );
        }
    }

    #[test]
    fn test_oracle_number_to_i64() {
        let num = OracleNumber::new("12345");
        assert_eq!(num.to_i64().unwrap(), 12345);
    }

    #[test]
    fn test_oracle_number_to_f64() {
        let num = OracleNumber::new("3.14");
        let f = num.to_f64().unwrap();
        assert!((f - 3.14).abs() < 0.001);
    }

    // =========================================================================
    // WIRE-LEVEL PROTOCOL TESTS
    // These tests document specific protocol details learned during development.
    // They serve as reference for anyone implementing Oracle/TNS protocols.
    // =========================================================================

    /// Oracle NUMBER wire format:
    ///
    /// Byte 0: Exponent/sign byte
    ///   - Positive: 0x80 + (exponent + 65)
    ///   - Negative: ~(0x80 + (exponent + 65))
    ///   - Zero: 0x80
    ///
    /// Bytes 1+: Base-100 mantissa digits
    ///   - Positive: digit + 1 (so 00-99 becomes 01-100)
    ///   - Negative: 101 - digit (so 00-99 becomes 101-02)
    ///
    /// CRITICAL: Negative numbers require terminator byte 0x66 (102)
    /// unless all 20 mantissa positions are used.
    #[test]
    fn test_wire_number_negative_terminator_0x66() {
        // -123 should have terminator byte 0x66
        let encoded = encode_oracle_number("-123").unwrap();

        // Format: [exponent] [digit1] [digit2] [terminator]
        // -123 = -1.23 × 10² = exponent 2 (value 1, digits 01 23)
        // Exponent byte: ~(0x80 + 2 + 65) = ~0xC3 = 0x3C (but actual calc differs)

        // Last byte MUST be 0x66 (102) for negative numbers
        assert_eq!(*encoded.last().unwrap(), 0x66,
            "Negative numbers must end with terminator byte 0x66 (102)");

        // Verify it's not present for positive numbers
        let pos_encoded = encode_oracle_number("123").unwrap();
        assert_ne!(*pos_encoded.last().unwrap(), 0x66,
            "Positive numbers must NOT have terminator byte");
    }

    /// Oracle NUMBER exponent byte calculation:
    ///
    /// The exponent byte encodes both the exponent AND the sign:
    ///   - Base value: 0x80 (128)
    ///   - Exponent offset: 65
    ///   - Positive: 0x80 + exponent + 65 = 0xC1 + exponent
    ///   - Negative: ~(0x80 + exponent + 65) = 0x3E - exponent
    ///
    /// Zero is special: just 0x80 with no mantissa.
    #[test]
    fn test_wire_number_exponent_encoding() {
        // Zero
        let zero = encode_oracle_number("0").unwrap();
        assert_eq!(zero, vec![0x80], "Zero must be single byte 0x80");

        // Positive single-digit (exponent = 0)
        // 5 → exponent=0, mantissa=05 → [0xC1, 0x06] (5+1)
        let five = encode_oracle_number("5").unwrap();
        assert_eq!(five[0], 0xC1, "Single digit positive has exponent byte 0xC1");

        // Positive three-digit (exponent = 1)
        // 123 → exponent=1, mantissa=01 23 → [0xC2, 0x02, 0x18]
        let one23 = encode_oracle_number("123").unwrap();
        assert_eq!(one23[0], 0xC2, "Three digit positive has exponent byte 0xC2");

        // Negative (inverted)
        // -5 → exponent=0, mantissa=05 → [~0xC1, 101-5, 0x66] = [0x3E, 0x60, 0x66]
        let neg5 = encode_oracle_number("-5").unwrap();
        assert_eq!(neg5[0], 0x3E, "Single digit negative has exponent byte 0x3E (~0xC1)");
    }

    /// Oracle NUMBER mantissa uses base-100 encoding
    ///
    /// Each mantissa byte represents two decimal digits as base-100:
    ///   - 00-99 → stored as value (for positive: +1, for negative: 101-value)
    ///   - "12345" → [01, 23, 45] (three base-100 digits)
    ///
    /// For odd digit counts, implicit leading zero:
    ///   - "123" → [01, 23] (not [1, 23]!)
    #[test]
    fn test_wire_number_base100_encoding() {
        // 12 → single base-100 digit: 12
        // Encoded as [exponent, 12+1] = [0xC1, 0x0D]
        let twelve = encode_oracle_number("12").unwrap();
        assert_eq!(twelve.len(), 2);
        assert_eq!(twelve[1], 13, "12 encoded as base-100 digit 12, stored as 13 (12+1)");

        // 99 → single base-100 digit: 99
        // Encoded as [exponent, 99+1] = [0xC1, 0x64]
        let ninetynine = encode_oracle_number("99").unwrap();
        assert_eq!(ninetynine[1], 100, "99 encoded as base-100 digit 99, stored as 100 (99+1)");

        // 100 → CRITICAL: Oracle NUMBER removes trailing zeros!
        // The digits [1, 0, 0] become [1] after trailing zero removal.
        // Since decimal_point_index=3 is odd, prepend_zero=true, padding adds 0 → [1, 0]
        // But when prepend_zero is set and it's the first pair, only one digit is taken (1, not 10)
        // Exponent adjusted for decimal position: (3+1)/2 + 192 = 194 = 0xC2
        // Encoded as [0xC2, 0x02] where 0x02 = 2 = 1 + 1 (digit "1" encoded)
        let hundred = encode_oracle_number("100").unwrap();
        assert_eq!(hundred.len(), 2, "100 is just 2 bytes - trailing zeros removed");
        assert_eq!(hundred[0], 0xC2, "Exponent byte: 194 = (4/2) + 192");
        assert_eq!(hundred[1], 2, "Single digit 1 (with prepend_zero), stored as 2 (1+1)");

        // 1234 → two base-100 digits: 12, 34
        // No trailing zeros to remove
        // Encoded as [0xC2, 13, 35] (exponent 2, digits 12+1 and 34+1)
        let twelve34 = encode_oracle_number("1234").unwrap();
        assert_eq!(twelve34.len(), 3);
        assert_eq!(twelve34[1], 13, "First base-100 digit 12, stored as 13");
        assert_eq!(twelve34[2], 35, "Second base-100 digit 34, stored as 35");
    }
}