refprop-rs 0.2.0

Safe Rust bindings for NIST REFPROP – thermodynamic & transport properties of refrigerants, pure fluids, and mixtures
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
//! Low-level FFI bindings for NIST REFPROP.
//!
//! This module dynamically loads the REFPROP shared library (DLL/so)
//! at runtime via [`libloading`] and pre-resolves all function pointers
//! for zero-overhead calls.

#![allow(non_snake_case)]

use std::os::raw::{c_char, c_double, c_int, c_long};
use std::path::Path;

use libloading::Library;

// ── REFPROP constants ───────────────────────────────────────────────
pub const REFPROP_STRLEN: usize = 255;
pub const REFPROP_FILESTR: usize = 10000;
pub const REFPROP_NC_MAX: usize = 20;

// ── Error type ──────────────────────────────────────────────────────
#[derive(Debug)]
pub enum RefpropSysError {
    /// The DLL/so could not be found or loaded.
    LibraryLoadFailed(String),
    /// A required symbol was not found in the library.
    SymbolNotFound(String),
}

impl std::fmt::Display for RefpropSysError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::LibraryLoadFailed(msg) => write!(f, "REFPROP library load failed: {msg}"),
            Self::SymbolNotFound(sym) => {
                write!(f, "Symbol not found in REFPROP library: {sym}")
            }
        }
    }
}

impl std::error::Error for RefpropSysError {}

// ── Function pointer type aliases ───────────────────────────────────
// These match the Fortran calling convention used by REFPROP.
// Grouped by signature similarity for readability.

/// SETPATHdll(hpath, length)
type FnSetpath = unsafe extern "C" fn(*const c_char, c_long);

/// SETUPdll(nc, hfld, hfmix, hrf, ierr, herr, len...)
type FnSetup = unsafe extern "C" fn(
    *const c_int,
    *const c_char,
    *const c_char,
    *const c_char,
    *mut c_int,
    *mut c_char,
    c_long,
    c_long,
    c_long,
    c_long,
);

/// TPFLSHdll / PHFLSHdll / PSFLSHdll – all share the same signature:
/// (in1, in2, z, out1..out12, ierr, herr, herr_length)
type FnFlash = unsafe extern "C" fn(
    *const c_double,
    *const c_double,
    *const c_double,
    *mut c_double,
    *mut c_double,
    *mut c_double,
    *mut c_double,
    *mut c_double,
    *mut c_double,
    *mut c_double,
    *mut c_double,
    *mut c_double,
    *mut c_double,
    *mut c_double,
    *mut c_double,
    *mut c_int,
    *mut c_char,
    c_long,
);

/// SATTdll / SATPdll – same signature:
/// (in, z, kph, out1..out5, ierr, herr, herr_length)
type FnSat = unsafe extern "C" fn(
    *const c_double,
    *const c_double,
    *const c_int,
    *mut c_double,
    *mut c_double,
    *mut c_double,
    *mut c_double,
    *mut c_double,
    *mut c_int,
    *mut c_char,
    c_long,
);

/// CRITPdll(z, tc, pc, dc, ierr, herr, herr_length)
type FnCritp = unsafe extern "C" fn(
    *const c_double,
    *mut c_double,
    *mut c_double,
    *mut c_double,
    *mut c_int,
    *mut c_char,
    c_long,
);

/// TRNPRPdll(t, d, z, eta, tcx, ierr, herr, herr_length)
type FnTrnprp = unsafe extern "C" fn(
    *const c_double,
    *const c_double,
    *const c_double,
    *mut c_double,
    *mut c_double,
    *mut c_int,
    *mut c_char,
    c_long,
);

/// SETMIXdll(hmxnme, hfmix, hrf, nc, hfld, z, ierr, herr, len...)
type FnSetmix = unsafe extern "C" fn(
    *const c_char,
    *const c_char,
    *const c_char,
    *mut c_int,
    *mut c_char,
    *mut c_double,
    *mut c_int,
    *mut c_char,
    c_long,
    c_long,
    c_long,
    c_long,
    c_long,
);

/// THERMdll(t, d, z, p, e, h, s, cv, cp, w, hjt)
type FnTherm = unsafe extern "C" fn(
    *const c_double,
    *const c_double,
    *const c_double,
    *mut c_double,
    *mut c_double,
    *mut c_double,
    *mut c_double,
    *mut c_double,
    *mut c_double,
    *mut c_double,
    *mut c_double,
);

/// INFOdll(icomp, wmm, ttrp, tnbpt, tc, pc, dc, zc, acf, dip, rgas)
type FnInfo = unsafe extern "C" fn(
    *const c_int,
    *mut c_double,
    *mut c_double,
    *mut c_double,
    *mut c_double,
    *mut c_double,
    *mut c_double,
    *mut c_double,
    *mut c_double,
    *mut c_double,
    *mut c_double,
);

// ── Dynamic library wrapper ─────────────────────────────────────────

/// Holds a dynamically-loaded REFPROP shared library with **pre-resolved
/// function pointers** for zero-overhead calls.
///
/// All function symbols are resolved once at construction time.  If any
/// required symbol is missing the constructor returns an error instead
/// of panicking later.
///
/// All methods are `unsafe` because they forward raw pointers to Fortran
/// code that cannot be verified by the Rust compiler.
pub struct RefpropLibrary {
    /// The underlying library handle.  Must stay alive to keep the DLL
    /// loaded and the function pointers valid.
    _lib: Library,

    // ── Cached function pointers ────────────────────────────────────
    fn_setpath: FnSetpath,
    fn_setup: FnSetup,
    fn_tpflsh: FnFlash,
    fn_phflsh: FnFlash,
    fn_psflsh: FnFlash,
    fn_satt: FnSat,
    fn_satp: FnSat,
    fn_critp: FnCritp,
    fn_trnprp: FnTrnprp,
    fn_setmix: FnSetmix,
    fn_therm: FnTherm,
    fn_info: FnInfo,
}

impl RefpropLibrary {
    // ── Symbol resolution ───────────────────────────────────────────

    /// Resolve a single symbol from the library as a typed function
    /// pointer.  Returns `Err(SymbolNotFound)` if the symbol is absent.
    fn resolve<T: Copy>(lib: &Library, name: &[u8]) -> Result<T, RefpropSysError> {
        // SAFETY: We are loading a known symbol name from a REFPROP DLL.
        // The caller (resolve_all) ensures all type aliases match the
        // actual Fortran calling convention.
        let sym: libloading::Symbol<T> = unsafe { lib.get(name) }.map_err(|_| {
            // Strip trailing \0 for display.
            let display =
                String::from_utf8_lossy(&name[..name.len().saturating_sub(1)]).to_string();
            RefpropSysError::SymbolNotFound(display)
        })?;
        Ok(*sym)
    }

    /// Resolve **all** required REFPROP symbols from an already-loaded
    /// library.  Fails on the first missing symbol.
    fn resolve_all(lib: Library) -> Result<Self, RefpropSysError> {
        Ok(Self {
            fn_setpath: Self::resolve(&lib, b"SETPATHdll\0")?,
            fn_setup: Self::resolve(&lib, b"SETUPdll\0")?,
            fn_tpflsh: Self::resolve(&lib, b"TPFLSHdll\0")?,
            fn_phflsh: Self::resolve(&lib, b"PHFLSHdll\0")?,
            fn_psflsh: Self::resolve(&lib, b"PSFLSHdll\0")?,
            fn_satt: Self::resolve(&lib, b"SATTdll\0")?,
            fn_satp: Self::resolve(&lib, b"SATPdll\0")?,
            fn_critp: Self::resolve(&lib, b"CRITPdll\0")?,
            fn_trnprp: Self::resolve(&lib, b"TRNPRPdll\0")?,
            fn_setmix: Self::resolve(&lib, b"SETMIXdll\0")?,
            fn_therm: Self::resolve(&lib, b"THERMdll\0")?,
            fn_info: Self::resolve(&lib, b"INFOdll\0")?,
            _lib: lib,
        })
    }

    // ── Constructors ────────────────────────────────────────────────

    /// Try to load the REFPROP shared library from a **directory** that
    /// contains the DLL / .so.  Common file names are tried automatically.
    ///
    /// On 64-bit Windows the 64-bit DLL (`REFPRP64.DLL`) is tried first.
    /// If a candidate file exists but cannot be loaded (e.g. architecture
    /// mismatch), the next candidate is tried.
    ///
    /// All required symbols are resolved eagerly.  If any symbol is
    /// missing, an error is returned immediately.
    pub fn load_from_dir(dir: &Path) -> Result<Self, RefpropSysError> {
        // Order matters: prefer 64-bit DLL on 64-bit targets.
        let candidates: &[&str] = if cfg!(target_os = "windows") {
            if cfg!(target_pointer_width = "64") {
                &["REFPRP64.DLL", "REFPROP.DLL", "refprop.dll"]
            } else {
                &["REFPROP.DLL", "refprop.dll", "REFPRP64.DLL"]
            }
        } else if cfg!(target_os = "macos") {
            &["librefprop.dylib", "libREFPROP.dylib"]
        } else {
            &["librefprop.so", "libREFPROP.so"]
        };

        let mut errors = Vec::new();

        // 1. Try full paths inside the directory.
        //    If a file exists but fails to load, keep trying the rest.
        for name in candidates {
            let full = dir.join(name);
            if full.exists() {
                match unsafe { Library::new(&full) } {
                    Ok(lib) => return Self::resolve_all(lib),
                    Err(e) => {
                        errors.push(format!("{}: {e}", full.display()));
                    }
                }
            }
        }

        // 2. Fall back to system-wide search (PATH / LD_LIBRARY_PATH)
        for name in candidates {
            if let Ok(lib) = unsafe { Library::new(*name) } {
                return Self::resolve_all(lib);
            }
        }

        let detail = if errors.is_empty() {
            format!(
                "No REFPROP library found in {} (tried: {candidates:?})",
                dir.display()
            )
        } else {
            format!(
                "REFPROP library found but could not be loaded:\n  - {}",
                errors.join("\n  - ")
            )
        };
        Err(RefpropSysError::LibraryLoadFailed(detail))
    }

    /// Load the REFPROP shared library from an **exact file path**.
    pub fn load_from_file(path: &Path) -> Result<Self, RefpropSysError> {
        let lib = unsafe { Library::new(path) }
            .map_err(|e| RefpropSysError::LibraryLoadFailed(format!("{}: {e}", path.display())))?;
        Self::resolve_all(lib)
    }

    // ── REFPROP function wrappers ───────────────────────────────────
    //
    // Each method calls the pre-resolved function pointer directly.
    // No symbol lookup occurs at call time – this is the key
    // performance improvement over the previous design.

    /// Set the path where REFPROP will look for fluid files, mixture
    /// files, etc.
    pub unsafe fn SETPATHdll(&self, hpath: *const c_char, length: c_long) {
        unsafe { (self.fn_setpath)(hpath, length) };
    }

    /// Set up a fluid or mixture for subsequent calculations.
    pub unsafe fn SETUPdll(
        &self,
        nc: *const c_int,
        hfld: *const c_char,
        hfmix: *const c_char,
        hrf: *const c_char,
        ierr: *mut c_int,
        herr: *mut c_char,
        hfld_length: c_long,
        hfmix_length: c_long,
        hrf_length: c_long,
        herr_length: c_long,
    ) {
        unsafe {
            (self.fn_setup)(
                nc,
                hfld,
                hfmix,
                hrf,
                ierr,
                herr,
                hfld_length,
                hfmix_length,
                hrf_length,
                herr_length,
            );
        }
    }

    /// Temperature-pressure flash calculation.
    pub unsafe fn TPFLSHdll(
        &self,
        t: *const c_double,
        p: *const c_double,
        z: *const c_double,
        d: *mut c_double,
        dl: *mut c_double,
        dv: *mut c_double,
        x: *mut c_double,
        y: *mut c_double,
        q: *mut c_double,
        e: *mut c_double,
        h: *mut c_double,
        s: *mut c_double,
        cv: *mut c_double,
        cp: *mut c_double,
        w: *mut c_double,
        ierr: *mut c_int,
        herr: *mut c_char,
        herr_length: c_long,
    ) {
        unsafe {
            (self.fn_tpflsh)(
                t,
                p,
                z,
                d,
                dl,
                dv,
                x,
                y,
                q,
                e,
                h,
                s,
                cv,
                cp,
                w,
                ierr,
                herr,
                herr_length,
            );
        }
    }

    /// Pressure-enthalpy flash calculation.
    pub unsafe fn PHFLSHdll(
        &self,
        p: *const c_double,
        h: *const c_double,
        z: *const c_double,
        t: *mut c_double,
        d: *mut c_double,
        dl: *mut c_double,
        dv: *mut c_double,
        x: *mut c_double,
        y: *mut c_double,
        q: *mut c_double,
        e: *mut c_double,
        s: *mut c_double,
        cv: *mut c_double,
        cp: *mut c_double,
        w: *mut c_double,
        ierr: *mut c_int,
        herr: *mut c_char,
        herr_length: c_long,
    ) {
        unsafe {
            (self.fn_phflsh)(
                p,
                h,
                z,
                t,
                d,
                dl,
                dv,
                x,
                y,
                q,
                e,
                s,
                cv,
                cp,
                w,
                ierr,
                herr,
                herr_length,
            );
        }
    }

    /// Pressure-entropy flash calculation.
    pub unsafe fn PSFLSHdll(
        &self,
        p: *const c_double,
        s: *const c_double,
        z: *const c_double,
        t: *mut c_double,
        d: *mut c_double,
        dl: *mut c_double,
        dv: *mut c_double,
        x: *mut c_double,
        y: *mut c_double,
        q: *mut c_double,
        e: *mut c_double,
        h: *mut c_double,
        cv: *mut c_double,
        cp: *mut c_double,
        w: *mut c_double,
        ierr: *mut c_int,
        herr: *mut c_char,
        herr_length: c_long,
    ) {
        unsafe {
            (self.fn_psflsh)(
                p,
                s,
                z,
                t,
                d,
                dl,
                dv,
                x,
                y,
                q,
                e,
                h,
                cv,
                cp,
                w,
                ierr,
                herr,
                herr_length,
            );
        }
    }

    /// Saturation properties at a given temperature.
    pub unsafe fn SATTdll(
        &self,
        t: *const c_double,
        z: *const c_double,
        kph: *const c_int,
        p: *mut c_double,
        dl: *mut c_double,
        dv: *mut c_double,
        x: *mut c_double,
        y: *mut c_double,
        ierr: *mut c_int,
        herr: *mut c_char,
        herr_length: c_long,
    ) {
        unsafe { (self.fn_satt)(t, z, kph, p, dl, dv, x, y, ierr, herr, herr_length) };
    }

    /// Saturation properties at a given pressure.
    pub unsafe fn SATPdll(
        &self,
        p: *const c_double,
        z: *const c_double,
        kph: *const c_int,
        t: *mut c_double,
        dl: *mut c_double,
        dv: *mut c_double,
        x: *mut c_double,
        y: *mut c_double,
        ierr: *mut c_int,
        herr: *mut c_char,
        herr_length: c_long,
    ) {
        unsafe { (self.fn_satp)(p, z, kph, t, dl, dv, x, y, ierr, herr, herr_length) };
    }

    /// Critical-point properties.
    pub unsafe fn CRITPdll(
        &self,
        z: *const c_double,
        tcrit: *mut c_double,
        pcrit: *mut c_double,
        dcrit: *mut c_double,
        ierr: *mut c_int,
        herr: *mut c_char,
        herr_length: c_long,
    ) {
        unsafe { (self.fn_critp)(z, tcrit, pcrit, dcrit, ierr, herr, herr_length) };
    }

    /// Transport properties (viscosity, thermal conductivity).
    pub unsafe fn TRNPRPdll(
        &self,
        t: *const c_double,
        d: *const c_double,
        z: *const c_double,
        eta: *mut c_double,
        tcx: *mut c_double,
        ierr: *mut c_int,
        herr: *mut c_char,
        herr_length: c_long,
    ) {
        unsafe { (self.fn_trnprp)(t, d, z, eta, tcx, ierr, herr, herr_length) };
    }

    /// Load a predefined mixture from a `.MIX` file.
    ///
    /// Returns the number of components (`nc`), the fluid file string
    /// (`hfld`), and the molar composition array (`z`).
    pub unsafe fn SETMIXdll(
        &self,
        hmxnme: *const c_char,
        hfmix: *const c_char,
        hrf: *const c_char,
        nc: *mut c_int,
        hfld: *mut c_char,
        z: *mut c_double,
        ierr: *mut c_int,
        herr: *mut c_char,
        hmxnme_length: c_long,
        hfmix_length: c_long,
        hrf_length: c_long,
        hfld_length: c_long,
        herr_length: c_long,
    ) {
        unsafe {
            (self.fn_setmix)(
                hmxnme,
                hfmix,
                hrf,
                nc,
                hfld,
                z,
                ierr,
                herr,
                hmxnme_length,
                hfmix_length,
                hrf_length,
                hfld_length,
                herr_length,
            );
        }
    }

    /// Compute thermodynamic properties from temperature and density.
    ///
    /// No error return – REFPROP always produces a result.
    pub unsafe fn THERMdll(
        &self,
        t: *const c_double,
        d: *const c_double,
        z: *const c_double,
        p: *mut c_double,
        e: *mut c_double,
        h: *mut c_double,
        s: *mut c_double,
        cv: *mut c_double,
        cp: *mut c_double,
        w: *mut c_double,
        hjt: *mut c_double,
    ) {
        unsafe { (self.fn_therm)(t, d, z, p, e, h, s, cv, cp, w, hjt) };
    }

    /// Fluid information (molar mass, triple point, etc.).
    pub unsafe fn INFOdll(
        &self,
        icomp: *const c_int,
        wmm: *mut c_double,
        ttrp: *mut c_double,
        tnbpt: *mut c_double,
        tc: *mut c_double,
        pc: *mut c_double,
        dc: *mut c_double,
        zc: *mut c_double,
        acf: *mut c_double,
        dip: *mut c_double,
        rgas: *mut c_double,
    ) {
        unsafe { (self.fn_info)(icomp, wmm, ttrp, tnbpt, tc, pc, dc, zc, acf, dip, rgas) };
    }
}

// ── String helpers ──────────────────────────────────────────────────

/// Convert a Rust `&str` into a zero-padded `Vec<c_char>` of length
/// `max_len`, suitable for passing to a Fortran routine.
pub fn to_c_string(s: &str, max_len: usize) -> Vec<c_char> {
    let mut buffer = vec![0 as c_char; max_len];
    let bytes = s.as_bytes();
    let copy_len = bytes.len().min(max_len - 1);
    for i in 0..copy_len {
        buffer[i] = bytes[i] as c_char;
    }
    buffer
}

/// Convert a null-terminated (or fully-filled) Fortran `c_char` buffer
/// back into a trimmed Rust `String`.
pub fn from_c_string(buffer: &[c_char]) -> String {
    let bytes: Vec<u8> = buffer
        .iter()
        .take_while(|&&c| c != 0)
        .map(|&c| c as u8)
        .collect();
    String::from_utf8_lossy(&bytes).trim().to_string()
}