hdf5-pure-rust 0.3.1

Pure Rust implementation of the HDF5 file format
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
use std::sync::atomic::{
    AtomicBool, AtomicI32, AtomicPtr, AtomicU32, AtomicU64, AtomicUsize, Ordering,
};
use std::sync::{Arc, Barrier, Condvar, Mutex, Once, RwLock};
use std::thread::{self, JoinHandle, ThreadId};

use crate::error::ErrorStack;
use crate::hl::context::ApiContext;

#[derive(Debug, Default)]
pub struct ThreadPackage {
    initialized: AtomicBool,
}

impl ThreadPackage {
    pub fn init_package(&self) {
        self.initialized.store(true, Ordering::SeqCst);
    }

    pub fn term_package(&self) {
        self.initialized.store(false, Ordering::SeqCst);
    }

    pub fn pthread_first_thread_init(&self) {
        self.init_package();
    }

    pub fn c11_first_thread_init(&self) {
        self.init_package();
    }

    pub fn win32_process_enter(&self) {
        self.init_package();
    }

    pub fn top_term_package(&self) {
        self.term_package();
    }

    pub fn tinfo_term(&self) {
        self.term_package();
    }
}

#[derive(Debug, Default)]
pub struct TsMutex {
    locked: AtomicBool,
}

impl TsMutex {
    pub fn mutex_init() -> Self {
        Self::default()
    }

    pub fn mutex_trylock(&self) -> bool {
        self.locked
            .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
            .is_ok()
    }

    pub fn mutex_lock(&self) {
        while !self.mutex_trylock() {
            thread::yield_now();
        }
    }

    pub fn mutex_unlock(&self) {
        self.locked.store(false, Ordering::SeqCst);
    }

    pub fn mutex_destroy(self) {}

    pub fn mutex_acquire(&self) {
        self.mutex_lock();
    }

    pub fn mutex_release(&self) {
        self.mutex_unlock();
    }

    pub fn api_lock(&self) {
        self.mutex_lock();
    }

    pub fn api_mutex_release(&self) {
        self.mutex_unlock();
    }

    pub fn api_unlock(&self) {
        self.mutex_unlock();
    }
}

#[derive(Debug)]
pub struct TsSemaphore {
    count: Mutex<usize>,
    cv: Condvar,
}

impl TsSemaphore {
    pub fn semaphore_init(count: usize) -> Self {
        Self {
            count: Mutex::new(count),
            cv: Condvar::new(),
        }
    }

    pub fn semaphore_wait(&self) {
        let mut count = self.count.lock().expect("semaphore poisoned");
        while *count == 0 {
            count = self.cv.wait(count).expect("semaphore poisoned");
        }
        *count -= 1;
    }

    pub fn semaphore_signal(&self) {
        let mut count = self.count.lock().expect("semaphore poisoned");
        *count += 1;
        self.cv.notify_one();
    }

    pub fn semaphore_destroy(self) {}
}

pub struct TsThread {
    handle: Option<JoinHandle<()>>,
}

impl TsThread {
    pub fn thread_create<F>(task: F) -> Self
    where
        F: FnOnce() + Send + 'static,
    {
        Self {
            handle: Some(thread::spawn(task)),
        }
    }

    pub fn thread_join(mut self) {
        if let Some(handle) = self.handle.take() {
            let _ = handle.join();
        }
    }

    pub fn thread_detach(mut self) {
        self.handle.take();
    }

    pub fn thread_yield() {
        thread::yield_now();
    }
}

#[derive(Debug)]
pub struct TsCondvar {
    cv: Condvar,
}

impl TsCondvar {
    pub fn cond_init() -> Self {
        Self { cv: Condvar::new() }
    }

    pub fn cond_signal(&self) {
        self.cv.notify_one();
    }

    pub fn cond_broadcast(&self) {
        self.cv.notify_all();
    }

    pub fn cond_destroy(self) {}
}

#[derive(Debug, Clone)]
pub struct TsBarrier {
    inner: Arc<Barrier>,
}

impl TsBarrier {
    pub fn barrier_init(participants: usize) -> Self {
        Self {
            inner: Arc::new(Barrier::new(participants)),
        }
    }

    pub fn barrier_wait(&self) -> bool {
        self.inner.wait().is_leader()
    }

    pub fn barrier_destroy(self) {}
}

#[derive(Debug, Default)]
pub struct TsRwLock {
    lock: RwLock<()>,
    stats: RwLockStats,
}

#[derive(Debug, Default, Clone)]
pub struct RwLockStats {
    pub rdlocks: Arc<AtomicU64>,
    pub wrlocks: Arc<AtomicU64>,
    pub rdunlocks: Arc<AtomicU64>,
    pub wrunlocks: Arc<AtomicU64>,
}

impl TsRwLock {
    pub fn rwlock_init() -> Self {
        Self::default()
    }

    pub fn rwlock_rdlock(&self) {
        drop(self.lock.read().expect("rwlock poisoned"));
        self.update_stats_rdlock();
    }

    pub fn rwlock_rdunlock(&self) {
        self.update_stats_rd_unlock();
    }

    pub fn rwlock_wrlock(&self) {
        drop(self.lock.write().expect("rwlock poisoned"));
        self.update_stats_wr_lock();
    }

    pub fn rwlock_trywrlock(&self) -> bool {
        self.lock.try_write().is_ok()
    }

    pub fn rwlock_wrunlock(&self) {
        self.update_stats_wr_unlock();
    }

    pub fn rwlock_destroy(self) {}

    pub fn rec_rwlock_init() -> Self {
        Self::rwlock_init()
    }

    pub fn rec_rwlock_destroy(self) {}

    pub fn rec_rwlock_rdlock(&self) {
        self.rwlock_rdlock();
    }

    pub fn rec_rwlock_wrlock(&self) {
        self.rwlock_wrlock();
    }

    pub fn rec_rwlock_rdunlock(&self) {
        self.rwlock_rdunlock();
    }

    pub fn rec_rwlock_wrunlock(&self) {
        self.rwlock_wrunlock();
    }

    pub fn update_stats_rdlock(&self) {
        self.stats.rdlocks.fetch_add(1, Ordering::Relaxed);
    }

    pub fn update_stats_rd_lock_delay(&self) {
        self.update_stats_rdlock();
    }

    pub fn update_stats_rd_unlock(&self) {
        self.stats.rdunlocks.fetch_add(1, Ordering::Relaxed);
    }

    pub fn update_stats_wr_lock(&self) {
        self.stats.wrlocks.fetch_add(1, Ordering::Relaxed);
    }

    pub fn update_stats_wr_lock_delay(&self) {
        self.update_stats_wr_lock();
    }

    pub fn update_stats_wr_unlock(&self) {
        self.stats.wrunlocks.fetch_add(1, Ordering::Relaxed);
    }

    pub fn rec_rwlock_get_stats(&self) -> (u64, u64, u64, u64) {
        (
            self.stats.rdlocks.load(Ordering::Relaxed),
            self.stats.wrlocks.load(Ordering::Relaxed),
            self.stats.rdunlocks.load(Ordering::Relaxed),
            self.stats.wrunlocks.load(Ordering::Relaxed),
        )
    }

    pub fn rec_rwlock_reset_stats(&self) {
        self.stats.rdlocks.store(0, Ordering::Relaxed);
        self.stats.wrlocks.store(0, Ordering::Relaxed);
        self.stats.rdunlocks.store(0, Ordering::Relaxed);
        self.stats.wrunlocks.store(0, Ordering::Relaxed);
    }

    pub fn rec_rwlock_print_stats(&self) -> String {
        let (rd, wr, rdu, wru) = self.rec_rwlock_get_stats();
        format!("rdlock={rd}, wrlock={wr}, rdunlock={rdu}, wrunlock={wru}")
    }
}

pub struct TsThreadPool {
    tasks: Mutex<Vec<JoinHandle<()>>>,
}

impl Default for TsThreadPool {
    fn default() -> Self {
        Self {
            tasks: Mutex::new(Vec::new()),
        }
    }
}

impl TsThreadPool {
    pub fn pool_add_task<F>(&self, task: F)
    where
        F: FnOnce() + Send + 'static,
    {
        self.tasks
            .lock()
            .expect("pool poisoned")
            .push(thread::spawn(task));
    }

    pub fn pool_do(&self) {
        let mut tasks = self.tasks.lock().expect("pool poisoned");
        for task in tasks.drain(..) {
            let _ = task.join();
        }
    }

    pub fn pool_free(self) {
        self.pool_do();
    }

    pub fn pool_destroy(self) {
        self.pool_do();
    }
}

#[derive(Debug, Default)]
pub struct ThreadInfo {
    api_ctx: ApiContext,
    err_stack: ErrorStack,
    dlftt: usize,
}

impl ThreadInfo {
    pub fn tinfo_init() -> Self {
        Self::default()
    }

    pub fn tinfo_create() -> Self {
        Self::default()
    }

    pub fn thread_id() -> ThreadId {
        thread::current().id()
    }

    pub fn get_api_ctx_ptr(&mut self) -> &mut ApiContext {
        &mut self.api_ctx
    }

    pub fn get_err_stack(&mut self) -> &mut ErrorStack {
        &mut self.err_stack
    }

    pub fn get_dlftt(&self) -> usize {
        self.dlftt
    }

    pub fn set_dlftt(&mut self, value: usize) {
        self.dlftt = value;
    }

    pub fn inc_dlftt(&mut self) -> usize {
        self.dlftt += 1;
        self.dlftt
    }

    pub fn dec_dlftt(&mut self) -> usize {
        self.dlftt = self.dlftt.saturating_sub(1);
        self.dlftt
    }

    pub fn tinfo_destroy(self) {}
}

#[derive(Debug)]
pub struct TsKey<T: Clone> {
    value: Mutex<Option<T>>,
}

impl<T: Clone> TsKey<T> {
    pub fn key_create() -> Self {
        Self {
            value: Mutex::new(None),
        }
    }

    pub fn key_set_value(&self, value: T) {
        *self.value.lock().expect("key poisoned") = Some(value);
    }

    pub fn key_get_value(&self) -> Option<T> {
        self.value.lock().expect("key poisoned").clone()
    }

    pub fn key_delete(self) {}
}

pub fn once(once: &Once, f: impl FnOnce()) {
    once.call_once(f);
}

pub fn atomic_init_int(value: i32) -> AtomicI32 {
    AtomicI32::new(value)
}

pub fn atomic_load_int(value: &AtomicI32) -> i32 {
    value.load(Ordering::SeqCst)
}

pub fn atomic_store_int(value: &AtomicI32, new_value: i32) {
    value.store(new_value, Ordering::SeqCst);
}

pub fn atomic_fetch_add_int(value: &AtomicI32, addend: i32) -> i32 {
    value.fetch_add(addend, Ordering::SeqCst)
}

pub fn atomic_fetch_sub_int(value: &AtomicI32, subtrahend: i32) -> i32 {
    value.fetch_sub(subtrahend, Ordering::SeqCst)
}

pub fn atomic_destroy_int(_value: AtomicI32) {}

pub fn atomic_init_uint(value: u32) -> AtomicU32 {
    AtomicU32::new(value)
}

pub fn atomic_load_uint(value: &AtomicU32) -> u32 {
    value.load(Ordering::SeqCst)
}

pub fn atomic_store_uint(value: &AtomicU32, new_value: u32) {
    value.store(new_value, Ordering::SeqCst);
}

pub fn atomic_fetch_add_uint(value: &AtomicU32, addend: u32) -> u32 {
    value.fetch_add(addend, Ordering::SeqCst)
}

pub fn atomic_fetch_sub_uint(value: &AtomicU32, subtrahend: u32) -> u32 {
    value.fetch_sub(subtrahend, Ordering::SeqCst)
}

pub fn atomic_destroy_uint(_value: AtomicU32) {}

pub fn atomic_init_voidp<T>(value: *mut T) -> AtomicPtr<T> {
    AtomicPtr::new(value)
}

pub fn atomic_exchange_voidp<T>(value: &AtomicPtr<T>, new_value: *mut T) -> *mut T {
    value.swap(new_value, Ordering::SeqCst)
}

pub fn atomic_destroy_voidp<T>(_value: AtomicPtr<T>) {}

pub fn atomic_init_usize(value: usize) -> AtomicUsize {
    AtomicUsize::new(value)
}

#[cfg(test)]
mod tests {
    use super::{atomic_fetch_add_int, atomic_init_int, atomic_load_int, TsMutex, TsThreadPool};

    #[test]
    fn threading_mutex_and_pool_do_real_work() {
        let mutex = TsMutex::mutex_init();
        assert!(mutex.mutex_trylock());
        mutex.mutex_unlock();

        let value = std::sync::Arc::new(atomic_init_int(0));
        let pool = TsThreadPool::default();
        for _ in 0..4 {
            let value = value.clone();
            pool.pool_add_task(move || {
                atomic_fetch_add_int(&value, 1);
            });
        }
        pool.pool_do();
        assert_eq!(atomic_load_int(&value), 4);
    }
}