gemstone-gci 0.2.0

Low-level dynamic GemStone/S GCI loader and raw ABI bindings.
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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
//! Low-level GemStone/S GCI dynamic loader and raw ABI bindings.
//!
//! This crate intentionally does not require GemStone headers at build time.
//! It loads `libgcirpc` at runtime and keeps all unsafe C ABI calls in one
//! small layer that higher-level Rust and PyO3 crates can share.

use libloading::{Library, Symbol};
use std::env;
use std::error::Error as StdError;
use std::ffi::{c_char, c_double, c_int, c_uint, c_void, CStr};
use std::fmt;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Arc;

pub type RawOop = u64;
pub type Result<T> = std::result::Result<T, GciError>;

pub const OOP_ILLEGAL: RawOop = 0x01;
pub const OOP_NIL: RawOop = 0x14;
pub const OOP_FALSE: RawOop = 0x0C;
pub const OOP_TRUE: RawOop = 0x10C;
pub const OOP_ASCII_NUL: RawOop = 0x1C;
pub const GCI_INVALID_SESSION: RawOop = 0;
pub const GCI_ENCRYPT_BUF_SIZE: usize = 1024;
pub const GCI_LOGIN_PW_ENCRYPTED: RawOop = 0x1;
pub const GCI_LOGIN_IS_GCSTS: RawOop = 0x2;
pub const GCI_ERR_STR_SIZE: usize = 1024;
pub const GCI_MAX_ERR_ARGS: usize = 10;

const TAG_SMALLINT: RawOop = 0x2;
const TAG_SMALLDOUBLE: RawOop = 0x6;
const TAG_SPECIAL: RawOop = 0x4;
const SMALLINT_SHIFT: u32 = 3;
const CHAR_TAG_BYTE: RawOop = 0x1C;

#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub struct Oop(pub RawOop);

impl Oop {
    pub const ILLEGAL: Self = Self(OOP_ILLEGAL);
    pub const NIL: Self = Self(OOP_NIL);
    pub const FALSE: Self = Self(OOP_FALSE);
    pub const TRUE: Self = Self(OOP_TRUE);

    pub fn from_smallint(value: i64) -> Self {
        Self(i64_to_smallint(value))
    }

    pub fn from_bool(value: bool) -> Self {
        if value {
            Self::TRUE
        } else {
            Self::FALSE
        }
    }

    pub fn from_char(value: char) -> Self {
        Self(char_to_oop(value))
    }

    pub fn raw(self) -> RawOop {
        self.0
    }

    pub fn is_illegal(self) -> bool {
        self.0 == OOP_ILLEGAL
    }

    pub fn is_nil(self) -> bool {
        self.0 == OOP_NIL
    }

    pub fn is_boolean(self) -> bool {
        matches!(self.0, OOP_TRUE | OOP_FALSE)
    }

    pub fn as_bool(self) -> Option<bool> {
        match self.0 {
            OOP_TRUE => Some(true),
            OOP_FALSE => Some(false),
            _ => None,
        }
    }

    pub fn is_smallint(self) -> bool {
        is_smallint(self.0)
    }

    pub fn as_smallint(self) -> Option<i64> {
        self.is_smallint().then(|| smallint_to_i64(self.0))
    }

    pub fn is_char(self) -> bool {
        is_char(self.0)
    }

    pub fn as_char(self) -> Result<Option<char>> {
        if self.is_char() {
            char_from_oop(self.0).map(Some)
        } else {
            Ok(None)
        }
    }
}

impl From<RawOop> for Oop {
    fn from(value: RawOop) -> Self {
        Self(value)
    }
}

impl From<Oop> for RawOop {
    fn from(value: Oop) -> Self {
        value.0
    }
}

#[repr(C)]
#[derive(Clone, Copy)]
pub struct GciErrSType {
    pub category: RawOop,
    pub context: RawOop,
    pub exception_obj: RawOop,
    pub args: [RawOop; GCI_MAX_ERR_ARGS],
    pub number: c_int,
    pub arg_count: c_int,
    pub fatal: u8,
    pub message: [c_char; GCI_ERR_STR_SIZE + 1],
    pub reason: [c_char; GCI_ERR_STR_SIZE + 1],
}

impl Default for GciErrSType {
    fn default() -> Self {
        // SAFETY: GciErrSType is a plain C layout buffer. The all-zero state is
        // the same initialization pattern used by ctypes before GciErr fills it.
        unsafe { std::mem::zeroed() }
    }
}

impl GciErrSType {
    pub fn message_text(&self) -> String {
        c_char_array_to_string(&self.message)
    }

    pub fn reason_text(&self) -> String {
        c_char_array_to_string(&self.reason)
    }

    pub fn full_message(&self) -> String {
        let message = self.message_text();
        let reason = self.reason_text();
        if reason.is_empty() || reason == message {
            message
        } else {
            format!("{message} [{reason}]")
        }
    }
}

#[derive(Debug)]
pub enum GciError {
    LibraryNotFound,
    LibraryLoad {
        path: PathBuf,
        source: libloading::Error,
    },
    Symbol {
        path: PathBuf,
        symbol: String,
        source: libloading::Error,
    },
    ReadDir {
        path: PathBuf,
        source: std::io::Error,
    },
    InvalidCharOop(RawOop),
}

impl fmt::Display for GciError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::LibraryNotFound => write!(
                f,
                "Cannot find libgcirpc. Pass a library path or set GS_LIB_PATH/GS_LIB/GEMSTONE."
            ),
            Self::LibraryLoad { path, source } => {
                write!(f, "cannot load {}: {source}", path.display())
            }
            Self::Symbol {
                path,
                symbol,
                source,
            } => write!(f, "{symbol} not found in {}: {source}", path.display()),
            Self::ReadDir { path, source } => {
                write!(f, "cannot read {}: {source}", path.display())
            }
            Self::InvalidCharOop(oop) => write!(f, "invalid GemStone character OOP {oop}"),
        }
    }
}

impl StdError for GciError {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        match self {
            Self::LibraryLoad { source, .. } => Some(source),
            Self::Symbol { source, .. } => Some(source),
            Self::ReadDir { source, .. } => Some(source),
            Self::LibraryNotFound | Self::InvalidCharOop(_) => None,
        }
    }
}

#[derive(Clone)]
pub struct GciLibrary {
    library: Arc<Library>,
    path: PathBuf,
}

impl GciLibrary {
    pub fn load(lib_path: Option<PathBuf>) -> Result<Self> {
        let path = resolve_library_path(lib_path)?;
        // SAFETY: Loading a dynamic library can execute platform loader hooks.
        // Callers opt into this by selecting the GemStone GCI library path.
        unsafe { Self::load_path(path) }
    }

    /// Load a specific dynamic library path.
    ///
    /// # Safety
    ///
    /// The caller must ensure `path` points to a trusted GemStone GCI library
    /// compatible with this ABI wrapper.
    pub unsafe fn load_path(path: PathBuf) -> Result<Self> {
        let library = Library::new(&path).map_err(|source| GciError::LibraryLoad {
            path: path.clone(),
            source,
        })?;
        Ok(Self {
            library: Arc::new(library),
            path,
        })
    }

    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Call `GciInit`.
    ///
    /// # Safety
    ///
    /// The loaded library must be a compatible GemStone GCI library.
    pub unsafe fn gci_init(&self) -> Result<c_int> {
        let init: Symbol<unsafe extern "C" fn() -> c_int> = self.symbol(b"GciInit")?;
        Ok(init())
    }

    /// Call `GciSetNet`.
    ///
    /// # Safety
    ///
    /// All C strings and optional password buffer pointers must remain valid
    /// for the duration of the call.
    pub unsafe fn gci_set_net(
        &self,
        stone_nrs: &CStr,
        host_username: &CStr,
        encrypted_host_password: *const c_char,
        gem_service: &CStr,
    ) -> Result<()> {
        let set_net: Symbol<
            unsafe extern "C" fn(*const c_char, *const c_char, *const c_char, *const c_char),
        > = self.symbol(b"GciSetNet")?;
        set_net(
            stone_nrs.as_ptr(),
            host_username.as_ptr(),
            encrypted_host_password,
            gem_service.as_ptr(),
        );
        Ok(())
    }

    /// Call `GciEncrypt`.
    ///
    /// # Safety
    ///
    /// `buffer` must point to writable memory of at least `buffer_size` bytes.
    pub unsafe fn gci_encrypt(
        &self,
        password: &CStr,
        buffer: *mut c_char,
        buffer_size: c_uint,
    ) -> Result<*mut c_char> {
        let encrypt: Symbol<
            unsafe extern "C" fn(*const c_char, *mut c_char, c_uint) -> *mut c_char,
        > = self.symbol(b"GciEncrypt")?;
        Ok(encrypt(password.as_ptr(), buffer, buffer_size))
    }

    /// Call `GciLoginEx`.
    ///
    /// # Safety
    ///
    /// The credential strings must remain valid for the duration of the call,
    /// and `GciSetNet` should already have configured the target stone.
    pub unsafe fn gci_login_ex(
        &self,
        username: &CStr,
        password: &CStr,
        flags: c_uint,
        halt_on_error: c_int,
    ) -> Result<c_int> {
        let login: Symbol<
            unsafe extern "C" fn(*const c_char, *const c_char, c_uint, c_int) -> c_int,
        > = self.symbol(b"GciLoginEx")?;
        Ok(login(
            username.as_ptr(),
            password.as_ptr(),
            flags,
            halt_on_error,
        ))
    }

    /// Call `GciLogout`.
    ///
    /// # Safety
    ///
    /// The current GCI session id must refer to the session to log out.
    pub unsafe fn gci_logout(&self) -> Result<c_int> {
        let logout: Symbol<unsafe extern "C" fn() -> c_int> = self.symbol(b"GciLogout")?;
        Ok(logout())
    }

    /// Call `GciCommit` with a typed error buffer.
    ///
    /// # Safety
    ///
    /// The current GCI session id must refer to an active session.
    pub unsafe fn gci_commit(&self, err: &mut GciErrSType) -> Result<c_int> {
        self.gci_commit_ptr(err as *mut GciErrSType as *mut c_void)
    }

    /// Call `GciCommit` with a raw error buffer.
    ///
    /// # Safety
    ///
    /// `err` must be null or point to a writable `GciErrSType`-compatible
    /// buffer expected by the loaded GCI library.
    pub unsafe fn gci_commit_ptr(&self, err: *mut c_void) -> Result<c_int> {
        let commit: Symbol<unsafe extern "C" fn(*mut c_void) -> c_int> =
            self.symbol(b"GciCommit")?;
        Ok(commit(err))
    }

    /// Call `GciAbort` with a typed error buffer.
    ///
    /// # Safety
    ///
    /// The current GCI session id must refer to an active session.
    pub unsafe fn gci_abort(&self, err: &mut GciErrSType) -> Result<c_int> {
        self.gci_abort_ptr(err as *mut GciErrSType as *mut c_void)
    }

    /// Call `GciAbort` with a raw error buffer.
    ///
    /// # Safety
    ///
    /// `err` must be null or point to a writable `GciErrSType`-compatible
    /// buffer expected by the loaded GCI library.
    pub unsafe fn gci_abort_ptr(&self, err: *mut c_void) -> Result<c_int> {
        let abort: Symbol<unsafe extern "C" fn(*mut c_void) -> c_int> = self.symbol(b"GciAbort")?;
        Ok(abort(err))
    }

    /// Call `GciErr` with a typed error buffer.
    ///
    /// # Safety
    ///
    /// The current GCI session id must be valid when querying session errors.
    pub unsafe fn gci_err(&self, err: &mut GciErrSType) -> Result<c_int> {
        self.gci_err_ptr(err as *mut GciErrSType as *mut c_void)
    }

    /// Call `GciErr` with a raw error buffer.
    ///
    /// # Safety
    ///
    /// `err` must point to a writable `GciErrSType`-compatible buffer.
    pub unsafe fn gci_err_ptr(&self, err: *mut c_void) -> Result<c_int> {
        let gci_err: Symbol<unsafe extern "C" fn(*mut c_void) -> c_int> = self.symbol(b"GciErr")?;
        Ok(gci_err(err))
    }

    /// Call `GciExecuteStr`.
    ///
    /// # Safety
    ///
    /// `source` must be valid for the duration of the call and `receiver` must
    /// be a valid OOP in the current session, or `OOP_NIL`.
    pub unsafe fn gci_execute_str(&self, source: &CStr, receiver: RawOop) -> Result<RawOop> {
        let execute: Symbol<unsafe extern "C" fn(*const c_char, RawOop) -> RawOop> =
            self.symbol(b"GciExecuteStr")?;
        Ok(execute(source.as_ptr(), receiver))
    }

    /// Call `GciNewString`.
    ///
    /// # Safety
    ///
    /// `value` must be valid for the duration of the call and a session must be
    /// active.
    pub unsafe fn gci_new_string(&self, value: &CStr) -> Result<RawOop> {
        let new_string: Symbol<unsafe extern "C" fn(*const c_char) -> RawOop> =
            self.symbol(b"GciNewString")?;
        Ok(new_string(value.as_ptr()))
    }

    /// Call `GciNewSymbol`.
    ///
    /// # Safety
    ///
    /// `value` must be valid for the duration of the call and a session must be
    /// active.
    pub unsafe fn gci_new_symbol(&self, value: &CStr) -> Result<RawOop> {
        let new_symbol: Symbol<unsafe extern "C" fn(*const c_char) -> RawOop> =
            self.symbol(b"GciNewSymbol")?;
        Ok(new_symbol(value.as_ptr()))
    }

    /// Call `GciFltToOop`.
    ///
    /// # Safety
    ///
    /// A compatible GCI session must be active.
    pub unsafe fn gci_flt_to_oop(&self, value: c_double) -> Result<RawOop> {
        let flt_to_oop: Symbol<unsafe extern "C" fn(c_double) -> RawOop> =
            self.symbol(b"GciFltToOop")?;
        Ok(flt_to_oop(value))
    }

    /// Call `GciOopToFlt_`.
    ///
    /// # Safety
    ///
    /// `value` must point to writable memory for one `c_double`; `oop` must be
    /// meaningful in the current session.
    pub unsafe fn gci_oop_to_flt(&self, oop: RawOop, value: *mut c_double) -> Result<c_int> {
        let oop_to_flt: Symbol<unsafe extern "C" fn(RawOop, *mut c_double) -> c_int> =
            self.symbol(b"GciOopToFlt_")?;
        Ok(oop_to_flt(oop, value))
    }

    /// Call `GciFetchSize_`.
    ///
    /// # Safety
    ///
    /// `oop` must be meaningful in the current session.
    pub unsafe fn gci_fetch_size(&self, oop: RawOop) -> Result<i64> {
        let fetch_size: Symbol<unsafe extern "C" fn(RawOop) -> i64> =
            self.symbol(b"GciFetchSize_")?;
        Ok(fetch_size(oop))
    }

    /// Call `GciFetchBytes_`.
    ///
    /// # Safety
    ///
    /// `buffer` must point to writable memory for at least `count` bytes;
    /// `oop` must be meaningful in the current session.
    pub unsafe fn gci_fetch_bytes(
        &self,
        oop: RawOop,
        start: i64,
        buffer: *mut c_char,
        count: i64,
    ) -> Result<i64> {
        let fetch_bytes: Symbol<unsafe extern "C" fn(RawOop, i64, *mut c_char, i64) -> i64> =
            self.symbol(b"GciFetchBytes_")?;
        Ok(fetch_bytes(oop, start, buffer, count))
    }

    /// Call `GciFetchClass`.
    ///
    /// # Safety
    ///
    /// `oop` must be meaningful in the current session.
    pub unsafe fn gci_fetch_class(&self, oop: RawOop) -> Result<RawOop> {
        let fetch_class: Symbol<unsafe extern "C" fn(RawOop) -> RawOop> =
            self.symbol(b"GciFetchClass")?;
        Ok(fetch_class(oop))
    }

    /// Call `GciPerform`.
    ///
    /// # Safety
    ///
    /// `receiver` and each argument OOP must be meaningful in the current
    /// session; `args` must point to at least `argc` OOPs unless `argc` is 0.
    pub unsafe fn gci_perform(
        &self,
        receiver: RawOop,
        selector: &CStr,
        args: *const RawOop,
        argc: c_int,
    ) -> Result<RawOop> {
        let perform: Symbol<
            unsafe extern "C" fn(RawOop, *const c_char, *const RawOop, c_int) -> RawOop,
        > = self.symbol(b"GciPerform")?;
        Ok(perform(receiver, selector.as_ptr(), args, argc))
    }

    /// Call `GciNewOop`.
    ///
    /// # Safety
    ///
    /// `class_oop` must be a valid GemStone class OOP in the current session.
    pub unsafe fn gci_new_oop(&self, class_oop: RawOop) -> Result<RawOop> {
        let new_oop: Symbol<unsafe extern "C" fn(RawOop) -> RawOop> = self.symbol(b"GciNewOop")?;
        Ok(new_oop(class_oop))
    }

    /// Call `GciResolveSymbol`.
    ///
    /// # Safety
    ///
    /// `name` must be valid for the duration of the call; `symbol_list` must be
    /// a valid symbol list OOP or `OOP_NIL`.
    pub unsafe fn gci_resolve_symbol(&self, name: &CStr, symbol_list: RawOop) -> Result<RawOop> {
        let resolve: Symbol<unsafe extern "C" fn(*const c_char, RawOop) -> RawOop> =
            self.symbol(b"GciResolveSymbol")?;
        Ok(resolve(name.as_ptr(), symbol_list))
    }

    /// Call `GciSymDictAtPut`.
    ///
    /// # Safety
    ///
    /// `dict` must be a valid symbol dictionary OOP and `value` must be valid
    /// in the current session.
    pub unsafe fn gci_sym_dict_at_put(
        &self,
        dict: RawOop,
        key: &CStr,
        value: RawOop,
    ) -> Result<()> {
        let at_put: Symbol<unsafe extern "C" fn(RawOop, *const c_char, RawOop)> =
            self.symbol(b"GciSymDictAtPut")?;
        at_put(dict, key.as_ptr(), value);
        Ok(())
    }

    /// Call `GciSymDictAtObjPut`.
    ///
    /// # Safety
    ///
    /// `dict`, `key`, and `value` must be valid OOPs in the current session.
    pub unsafe fn gci_sym_dict_at_obj_put(
        &self,
        dict: RawOop,
        key: RawOop,
        value: RawOop,
    ) -> Result<()> {
        let at_put: Symbol<unsafe extern "C" fn(RawOop, RawOop, RawOop)> =
            self.symbol(b"GciSymDictAtObjPut")?;
        at_put(dict, key, value);
        Ok(())
    }

    /// Call `GciStrKeyValueDictAtPut`.
    ///
    /// # Safety
    ///
    /// `dict` and `value` must be valid OOPs in the current session; `key`
    /// must remain valid for the duration of the call.
    pub unsafe fn gci_str_key_value_dict_at_put(
        &self,
        dict: RawOop,
        key: &CStr,
        value: RawOop,
    ) -> Result<()> {
        let at_put: Symbol<unsafe extern "C" fn(RawOop, *const c_char, RawOop)> =
            self.symbol(b"GciStrKeyValueDictAtPut")?;
        at_put(dict, key.as_ptr(), value);
        Ok(())
    }

    /// Call `GciStrKeyValueDictAt`.
    ///
    /// # Safety
    ///
    /// `dict` must be valid in the current session; `key` must remain valid and
    /// `value` must point to writable memory for one OOP.
    pub unsafe fn gci_str_key_value_dict_at(
        &self,
        dict: RawOop,
        key: &CStr,
        value: *mut RawOop,
    ) -> Result<()> {
        let at: Symbol<unsafe extern "C" fn(RawOop, *const c_char, *mut RawOop)> =
            self.symbol(b"GciStrKeyValueDictAt")?;
        at(dict, key.as_ptr(), value);
        Ok(())
    }

    /// Call `GciSymDictAt`.
    ///
    /// # Safety
    ///
    /// `dict` must be valid in the current session; `key` must remain valid and
    /// `value`/`assoc` must point to writable memory for one OOP each.
    pub unsafe fn gci_sym_dict_at(
        &self,
        dict: RawOop,
        key: &CStr,
        value: *mut RawOop,
        assoc: *mut RawOop,
    ) -> Result<()> {
        let at: Symbol<unsafe extern "C" fn(RawOop, *const c_char, *mut RawOop, *mut RawOop)> =
            self.symbol(b"GciSymDictAt")?;
        at(dict, key.as_ptr(), value, assoc);
        Ok(())
    }

    /// Call `GciGetSessionId`.
    ///
    /// # Safety
    ///
    /// The loaded library must be a compatible GemStone GCI library.
    pub unsafe fn gci_get_session_id(&self) -> Result<c_int> {
        let get_session_id: Symbol<unsafe extern "C" fn() -> c_int> =
            self.symbol(b"GciGetSessionId")?;
        Ok(get_session_id())
    }

    /// Call `GciSetSessionId`.
    ///
    /// # Safety
    ///
    /// `session_id` must be an id returned by GCI for this process, or the
    /// caller must otherwise know it is valid.
    pub unsafe fn gci_set_session_id(&self, session_id: c_int) -> Result<()> {
        let set_session_id: Symbol<unsafe extern "C" fn(c_int)> =
            self.symbol(b"GciSetSessionId")?;
        set_session_id(session_id);
        Ok(())
    }

    /// Call `GciNeedsCommit`.
    ///
    /// # Safety
    ///
    /// The current GCI session id must refer to an active session.
    pub unsafe fn gci_needs_commit(&self) -> Result<c_int> {
        let needs_commit: Symbol<unsafe extern "C" fn() -> c_int> =
            self.symbol(b"GciNeedsCommit")?;
        Ok(needs_commit())
    }

    /// Call `GciInTransaction`.
    ///
    /// # Safety
    ///
    /// The current GCI session id must refer to an active session.
    pub unsafe fn gci_in_transaction(&self) -> Result<c_int> {
        let in_transaction: Symbol<unsafe extern "C" fn() -> c_int> =
            self.symbol(b"GciInTransaction")?;
        Ok(in_transaction())
    }

    /// Call an optional export-set function when it exists in the loaded GCI library.
    ///
    /// # Safety
    ///
    /// `name` must be the exact symbol name of a GCI function with signature
    /// `extern "C" fn(RawOop)`, and `oop` must be meaningful in the current
    /// session.
    pub unsafe fn call_optional_oop_export(&self, name: &[u8], oop: RawOop) -> Result<bool> {
        let symbol = self.library.get::<unsafe extern "C" fn(RawOop)>(name);
        if let Ok(function) = symbol {
            function(oop);
            return Ok(true);
        }
        Ok(false)
    }

    fn symbol<T>(&self, name: &[u8]) -> Result<Symbol<'_, T>> {
        unsafe { self.library.get(name) }.map_err(|source| GciError::Symbol {
            path: self.path.clone(),
            symbol: String::from_utf8_lossy(name).to_string(),
            source,
        })
    }
}

pub fn is_smallint(oop: RawOop) -> bool {
    (oop & 0x7) == TAG_SMALLINT
}

pub fn is_smalldouble(oop: RawOop) -> bool {
    (oop & 0x7) == TAG_SMALLDOUBLE
}

pub fn smallint_to_i64(oop: RawOop) -> i64 {
    (oop as i64) >> SMALLINT_SHIFT
}

pub fn i64_to_smallint(value: i64) -> RawOop {
    ((value << SMALLINT_SHIFT) as RawOop) | TAG_SMALLINT
}

pub fn is_char(oop: RawOop) -> bool {
    (oop & 0xFF) == CHAR_TAG_BYTE && (oop & 0x6) == TAG_SPECIAL
}

pub fn char_from_oop(oop: RawOop) -> Result<char> {
    let codepoint = ((oop >> 8) & 0x1F_FFFF) as u32;
    char::from_u32(codepoint).ok_or(GciError::InvalidCharOop(oop))
}

pub fn char_to_oop(value: char) -> RawOop {
    ((value as u32 as RawOop) << 8) | CHAR_TAG_BYTE
}

pub fn resolve_library_path(lib_path: Option<PathBuf>) -> Result<PathBuf> {
    if let Some(path) = lib_path {
        return Ok(path);
    }
    if let Ok(path) = env::var("GS_LIB_PATH") {
        if !path.is_empty() {
            return Ok(PathBuf::from(path));
        }
    }
    if let Ok(dir) = env::var("GS_LIB") {
        if !dir.is_empty() {
            if let Some(path) = find_gcirpc_in_dir(Path::new(&dir))? {
                return Ok(path);
            }
        }
    }
    if let Ok(gemstone) = env::var("GEMSTONE") {
        if !gemstone.is_empty() {
            let lib_dir = Path::new(&gemstone).join("lib");
            if let Some(path) = find_gcirpc_in_dir(&lib_dir)? {
                return Ok(path);
            }
        }
    }
    Err(GciError::LibraryNotFound)
}

pub fn find_gcirpc_in_dir(dir: &Path) -> Result<Option<PathBuf>> {
    if !dir.is_dir() {
        return Ok(None);
    }
    let mut candidates = Vec::new();
    for entry in fs::read_dir(dir).map_err(|source| GciError::ReadDir {
        path: dir.to_path_buf(),
        source,
    })? {
        let entry = entry.map_err(|source| GciError::ReadDir {
            path: dir.to_path_buf(),
            source,
        })?;
        let path = entry.path();
        let Some(name) = path.file_name().and_then(|value| value.to_str()) else {
            continue;
        };
        if name.starts_with("libgcirpc")
            && (name.ends_with(".dylib") || name.ends_with(".so") || name.ends_with(".dll"))
        {
            candidates.push(path);
        }
    }
    candidates.sort();
    Ok(candidates.pop())
}

fn c_char_array_to_string(value: &[c_char]) -> String {
    let bytes: Vec<u8> = value
        .iter()
        .take_while(|byte| **byte != 0)
        .map(|byte| *byte as u8)
        .collect();
    String::from_utf8_lossy(&bytes).into_owned()
}

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

    #[test]
    fn smallint_helpers_round_trip_signed_values() {
        for value in [-42, -1, 0, 1, 42] {
            assert_eq!(smallint_to_i64(i64_to_smallint(value)), value);
        }
    }

    #[test]
    fn oop_helpers_identify_special_values() {
        assert!(Oop::NIL.is_nil());
        assert!(Oop::TRUE.is_boolean());
        assert!(Oop::FALSE.is_boolean());
        assert_eq!(Oop::TRUE.as_bool(), Some(true));
        assert_eq!(Oop::FALSE.as_bool(), Some(false));
        assert!(Oop(i64_to_smallint(7)).is_smallint());
        assert_eq!(Oop(i64_to_smallint(7)).as_smallint(), Some(7));
    }

    #[test]
    fn char_helpers_round_trip_unicode_values() {
        for value in ['A', '\0', 'λ'] {
            let oop = Oop::from_char(value);
            assert!(oop.is_char());
            assert_eq!(oop.as_char().unwrap(), Some(value));
            assert_eq!(char_from_oop(char_to_oop(value)).unwrap(), value);
        }
    }
}