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
//! Types and functions for working with Ruby’s Hash class.

use std::{
    collections::HashMap,
    fmt,
    hash::Hash,
    os::raw::{c_int, c_long},
    panic::AssertUnwindSafe,
};

#[cfg(ruby_gte_2_7)]
use rb_sys::rb_hash_bulk_insert;
#[cfg(ruby_gte_3_2)]
use rb_sys::rb_hash_new_capa;
use rb_sys::{
    rb_check_hash_type, rb_hash_aref, rb_hash_aset, rb_hash_clear, rb_hash_delete, rb_hash_fetch,
    rb_hash_foreach, rb_hash_lookup, rb_hash_lookup2, rb_hash_new, rb_hash_size, rb_hash_size_num,
    rb_hash_update_by, ruby_value_type, VALUE,
};

use crate::{
    error::{protect, raise, Error},
    into_value::{IntoValue, IntoValueFromNative},
    object::Object,
    try_convert::{TryConvert, TryConvertOwned},
    value::{
        private::{self, ReprValue as _},
        Fixnum, NonZeroValue, ReprValue, Value, QUNDEF,
    },
    Ruby,
};

/// Iteration state for [`RHash::foreach`].
#[repr(u32)]
pub enum ForEach {
    /// Continue iterating.
    Continue,
    /// Stop iterating.
    Stop,
    /// Delete the last entry and continue iterating.
    Delete,
}

// Helper trait for wrapping a function with type conversions and error
// handling for `RHash::foreach`.
trait ForEachCallback<Func, K, V>
where
    Self: Sized + FnMut(K, V) -> Result<ForEach, Error>,
    K: TryConvert,
    V: TryConvert,
{
    #[inline]
    unsafe fn call_convert_value(mut self, key: Value, value: Value) -> Result<ForEach, Error> {
        (self)(
            TryConvert::try_convert(key)?,
            TryConvert::try_convert(value)?,
        )
    }

    #[inline]
    unsafe fn call_handle_error(self, key: Value, value: Value) -> ForEach {
        let res = match std::panic::catch_unwind(AssertUnwindSafe(|| {
            self.call_convert_value(key, value)
        })) {
            Ok(v) => v,
            Err(e) => Err(Error::from_panic(e)),
        };
        match res {
            Ok(v) => v,
            Err(e) => raise(e),
        }
    }
}

impl<Func, K, V> ForEachCallback<Func, K, V> for Func
where
    Func: FnMut(K, V) -> Result<ForEach, Error>,
    K: TryConvert,
    V: TryConvert,
{
}

/// # `RHash`
///
/// Functions that can be used to create Ruby `Hash`es.
///
/// See also the [`RHash`] type.
impl Ruby {
    /// Create a new empty `RHash`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{Error, Ruby};
    ///
    /// fn example(ruby: &Ruby) -> Result<(), Error> {
    ///     let hash = ruby.hash_new();
    ///     assert!(hash.is_empty());
    ///
    ///     Ok(())
    /// }
    /// # Ruby::init(example).unwrap()
    /// ```
    pub fn hash_new(&self) -> RHash {
        unsafe { RHash::from_rb_value_unchecked(rb_hash_new()) }
    }

    /// Create a new empty `RHash` with capacity for `n` elements pre-allocated.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{Error, Ruby};
    ///
    /// fn example(ruby: &Ruby) -> Result<(), Error> {
    ///     let ary = ruby.hash_new_capa(16);
    ///     assert!(ary.is_empty());
    ///
    ///     Ok(())
    /// }
    /// # Ruby::init(example).unwrap()
    /// ```
    #[cfg(any(ruby_gte_3_2, docsrs))]
    #[cfg_attr(docsrs, doc(cfg(ruby_gte_3_2)))]
    pub fn hash_new_capa(&self, n: usize) -> RHash {
        unsafe { RHash::from_rb_value_unchecked(rb_hash_new_capa(n as c_long)) }
    }
}

/// A Value pointer to a RHash struct, Ruby's internal representation of Hash
/// objects.
///
/// See the [`ReprValue`] and [`Object`] traits for additional methods
/// available on this type. See [`Ruby`](Ruby#rhash) for methods to create an
/// `RHash`.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct RHash(NonZeroValue);

impl RHash {
    /// Return `Some(RHash)` if `val` is a `RHash`, `None` otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, RHash};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// assert!(RHash::from_value(eval(r#"{"answer" => 42}"#).unwrap()).is_some());
    /// assert!(RHash::from_value(eval("[]").unwrap()).is_none());
    /// assert!(RHash::from_value(eval("nil").unwrap()).is_none());
    /// ```
    #[inline]
    pub fn from_value(val: Value) -> Option<Self> {
        unsafe {
            (val.rb_type() == ruby_value_type::RUBY_T_HASH)
                .then(|| Self(NonZeroValue::new_unchecked(val)))
        }
    }

    #[inline]
    pub(crate) unsafe fn from_rb_value_unchecked(val: VALUE) -> Self {
        Self(NonZeroValue::new_unchecked(Value::new(val)))
    }

    /// Create a new empty `RHash`.
    ///
    /// # Panics
    ///
    /// Panics if called from a non-Ruby thread. See [`Ruby::hash_new`] for the
    /// non-panicking version.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::RHash;
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let hash = RHash::new();
    /// assert!(hash.is_empty());
    /// ```
    #[cfg_attr(
        not(feature = "friendly-api"),
        deprecated(note = "please use `Ruby::hash_new` instead")
    )]
    #[inline]
    pub fn new() -> RHash {
        get_ruby!().hash_new()
    }

    /// Create a new empty `RHash` with capacity for `n` elements
    /// pre-allocated.
    ///
    /// # Panics
    ///
    /// Panics if called from a non-Ruby thread. See [`Ruby::hash_new_capa`]
    /// for the non-panicking version.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::RHash;
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let ary = RHash::with_capacity(16);
    /// assert!(ary.is_empty());
    /// ```
    #[cfg_attr(
        not(feature = "friendly-api"),
        deprecated(note = "please use `Ruby::hash_new_capa` instead")
    )]
    #[cfg(any(ruby_gte_3_2, docsrs))]
    #[cfg_attr(docsrs, doc(cfg(ruby_gte_3_2)))]
    #[inline]
    pub fn with_capacity(n: usize) -> Self {
        get_ruby!().hash_new_capa(n)
    }

    /// Set the value `val` for the key `key`.
    ///
    /// Errors if `self` is frozen or `key` does not respond to `hash`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{rb_assert, RHash};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let hash = RHash::new();
    /// hash.aset("answer", 42).unwrap();
    /// rb_assert!(r#"hash == {"answer" => 42}"#, hash);
    /// ```
    pub fn aset<K, V>(self, key: K, val: V) -> Result<(), Error>
    where
        K: IntoValue,
        V: IntoValue,
    {
        let handle = Ruby::get_with(self);
        let key = handle.into_value(key);
        let val = handle.into_value(val);
        unsafe {
            protect(|| {
                Value::new(rb_hash_aset(
                    self.as_rb_value(),
                    key.as_rb_value(),
                    val.as_rb_value(),
                ))
            })?;
        }
        Ok(())
    }

    /// Insert a list of key-value pairs into a hash at once.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{prelude::*, rb_assert, RHash, RString, Symbol};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let hash = RHash::new();
    /// hash.bulk_insert(&[
    ///     Symbol::new("given_name").as_value(),
    ///     RString::new("Arthur").as_value(),
    ///     Symbol::new("family_name").as_value(),
    ///     RString::new("Dent").as_value(),
    /// ])
    /// .unwrap();
    /// rb_assert!(
    ///     r#"hash == {given_name: "Arthur", family_name: "Dent"}"#,
    ///     hash,
    /// );
    /// ```
    #[cfg(any(ruby_gte_2_7, docsrs))]
    #[cfg_attr(docsrs, doc(cfg(ruby_gte_2_7)))]
    pub fn bulk_insert<T>(self, slice: &[T]) -> Result<(), Error>
    where
        T: ReprValue,
    {
        let ptr = slice.as_ptr() as *const VALUE;
        protect(|| {
            unsafe { rb_hash_bulk_insert(slice.len() as c_long, ptr, self.as_rb_value()) };
            Ruby::get_with(self).qnil()
        })?;
        Ok(())
    }

    /// Merges two hashes into one.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, rb_assert, RHash};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let a: RHash = eval("{a: 1, b: 2}").unwrap();
    /// let b: RHash = eval("{b: 3, c: 4}").unwrap();
    /// a.update(b).unwrap();
    ///
    /// // a is mutated, in case of conflicts b wins
    /// rb_assert!("a == {a: 1, b: 3, c: 4}", a);
    ///
    /// // b is unmodified
    /// rb_assert!("b == {b: 3, c: 4}", b);
    /// ```
    //
    // Implementation note: `rb_hash_update_by` takes a third optional argument,
    // a function pointer, the function being called to resolve conflicts.
    // Unfortunately there's no way to wrap this in a easy to use and safe Rust
    // api, so it has been omitted.
    pub fn update(self, other: RHash) -> Result<(), Error> {
        protect(|| {
            unsafe { rb_hash_update_by(self.as_rb_value(), other.as_rb_value(), None) };
            Ruby::get_with(self).qnil()
        })?;
        Ok(())
    }

    /// Return the value for `key`, converting it to `U`.
    ///
    /// Returns hash's default if `key` is missing. See also
    /// [`lookup`](RHash::lookup), [`get`](RHash::get), and
    /// [`fetch`](RHash::fetch).
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{value::Qnil, RHash};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let hash = RHash::new();
    /// hash.aset("answer", 42).unwrap();
    /// assert_eq!(hash.aref::<_, i64>("answer").unwrap(), 42);
    /// assert!(hash.aref::<_, Qnil>("missing").is_ok());
    /// assert_eq!(hash.aref::<_, Option<i64>>("answer").unwrap(), Some(42));
    /// assert_eq!(hash.aref::<_, Option<i64>>("missing").unwrap(), None);
    /// ```
    ///
    /// ```
    /// use magnus::{eval, RHash};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let hash: RHash = eval(
    ///     r#"
    ///       hash = {"answer" => 42}
    ///       hash.default = 0
    ///       hash
    ///     "#,
    /// )
    /// .unwrap();
    /// assert_eq!(hash.aref::<_, i64>("answer").unwrap(), 42);
    /// assert_eq!(hash.aref::<_, i64>("missing").unwrap(), 0);
    /// assert_eq!(hash.aref::<_, i64>(()).unwrap(), 0);
    /// ```
    pub fn aref<T, U>(self, key: T) -> Result<U, Error>
    where
        T: IntoValue,
        U: TryConvert,
    {
        let key = Ruby::get_with(self).into_value(key);
        protect(|| unsafe { Value::new(rb_hash_aref(self.as_rb_value(), key.as_rb_value())) })
            .and_then(TryConvert::try_convert)
    }

    /// Return the value for `key`, converting it to `U`.
    ///
    /// Returns `nil` if `key` is missing. See also [`aref`](RHash::aref),
    /// [`get`](RHash::get), and [`fetch`](RHash::fetch).
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, value::Qnil, RHash};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let hash: RHash = eval(
    ///     r#"
    ///       hash = {"answer" => 42}
    ///       hash.default = 0
    ///       hash
    ///     "#,
    /// )
    /// .unwrap();
    /// assert_eq!(hash.lookup::<_, i64>("answer").unwrap(), 42);
    /// assert!(hash.lookup::<_, Qnil>("missing").is_ok());
    /// assert_eq!(hash.lookup::<_, Option<i64>>("answer").unwrap(), Some(42));
    /// assert_eq!(hash.lookup::<_, Option<i64>>("missing").unwrap(), None);
    /// ```
    pub fn lookup<T, U>(self, key: T) -> Result<U, Error>
    where
        T: IntoValue,
        U: TryConvert,
    {
        let key = Ruby::get_with(self).into_value(key);
        protect(|| unsafe { Value::new(rb_hash_lookup(self.as_rb_value(), key.as_rb_value())) })
            .and_then(TryConvert::try_convert)
    }

    /// Return the value for `key` as a [`Value`].
    ///
    /// Returns `None` if `key` is missing. See also [`aref`](RHash::aref),
    /// [`lookup`](RHash::lookup), and [`fetch`](RHash::fetch).
    ///
    /// Note: It is possible for very badly behaved key objects to raise an
    /// error during hash lookup. This is unlikely, and for the simplicity of
    /// this api any errors will result in `None`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::RHash;
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let hash = RHash::new();
    /// hash.aset("answer", 42).unwrap();
    /// assert!(hash.get("answer").is_some());
    /// assert!(hash.get("missing").is_none());
    /// ```
    pub fn get<T>(self, key: T) -> Option<Value>
    where
        T: IntoValue,
    {
        let key = Ruby::get_with(self).into_value(key);
        protect(|| unsafe {
            Value::new(rb_hash_lookup2(
                self.as_rb_value(),
                key.as_rb_value(),
                QUNDEF.as_value().as_rb_value(),
            ))
        })
        .ok()
        .and_then(|v| (!v.is_undef()).then(|| v))
    }

    /// Return the value for `key`, converting it to `U`.
    ///
    /// Returns `Err` if `key` is missing. See also [`aref`](RHash::aref),
    /// [`lookup`](RHash::lookup), and [`get`](RHash::get).
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, RHash};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let hash: RHash = eval(
    ///     r#"
    ///       hash = {"answer" => 42}
    ///       hash.default = 0
    ///       hash
    ///     "#,
    /// )
    /// .unwrap();
    /// assert_eq!(hash.fetch::<_, i64>("answer").unwrap(), 42);
    /// assert!(hash.fetch::<_, i64>("missing").is_err());
    /// assert_eq!(hash.fetch::<_, Option<i64>>("answer").unwrap(), Some(42));
    /// assert!(hash.fetch::<_, Option<i64>>("missing").is_err());
    /// ```
    pub fn fetch<T, U>(self, key: T) -> Result<U, Error>
    where
        T: IntoValue,
        U: TryConvert,
    {
        let key = Ruby::get_with(self).into_value(key);
        protect(|| unsafe { Value::new(rb_hash_fetch(self.as_rb_value(), key.as_rb_value())) })
            .and_then(TryConvert::try_convert)
    }

    /// Removes the key `key` from self and returns the associated value,
    /// converting it to `U`.
    ///
    /// Returns `nil` if `key` is missing.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, value::Qnil, RHash};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let hash: RHash = eval(r#"hash = {"answer" => 42}"#).unwrap();
    /// assert_eq!(hash.delete::<_, i64>("answer").unwrap(), 42);
    /// assert!(hash.delete::<_, Qnil>("answer").is_ok());
    /// ```
    pub fn delete<T, U>(self, key: T) -> Result<U, Error>
    where
        T: IntoValue,
        U: TryConvert,
    {
        let key = Ruby::get_with(self).into_value(key);
        protect(|| unsafe { Value::new(rb_hash_delete(self.as_rb_value(), key.as_rb_value())) })
            .and_then(TryConvert::try_convert)
    }

    /// Removes all entries from `self`.
    ///
    /// Errors if `self` is frozen.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, RHash};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let hash: RHash = eval(r#"{"answer" => 42}"#).unwrap();
    /// assert!(!hash.is_empty());
    /// hash.clear().unwrap();
    /// assert!(hash.is_empty());
    /// ```
    pub fn clear(self) -> Result<(), Error> {
        protect(|| unsafe { Value::new(rb_hash_clear(self.as_rb_value())) })?;
        Ok(())
    }

    /// Run `func` for each key/value pair in `self`.
    ///
    /// The result of `func` is checked on each call, when it is
    /// [`ForEach::Continue`] the iteration will continue, [`ForEach::Stop`]
    /// will cause the iteration to stop, and [`ForEach::Delete`] will remove
    /// the key/value pair from `self` and then continue iteration.
    ///
    /// Returing an error from `func` behaves like [`ForEach::Stop`].
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, r_hash::ForEach, RHash};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let hash: RHash = eval(r#"{"foo" => 1, "bar" => 2, "baz" => 4, "qux" => 8}"#).unwrap();
    /// let mut found = None;
    /// hash.foreach(|key: String, value: i64| {
    ///     if value > 3 {
    ///         found = Some(key);
    ///         Ok(ForEach::Stop)
    ///     } else {
    ///         Ok(ForEach::Continue)
    ///     }
    /// })
    /// .unwrap();
    /// assert_eq!(found, Some(String::from("baz")));
    /// ```
    pub fn foreach<F, K, V>(self, mut func: F) -> Result<(), Error>
    where
        F: FnMut(K, V) -> Result<ForEach, Error>,
        K: TryConvert,
        V: TryConvert,
    {
        unsafe extern "C" fn iter<F, K, V>(key: VALUE, value: VALUE, arg: VALUE) -> c_int
        where
            F: FnMut(K, V) -> Result<ForEach, Error>,
            K: TryConvert,
            V: TryConvert,
        {
            let closure = &mut *(arg as *mut F);
            closure.call_handle_error(Value::new(key), Value::new(value)) as c_int
        }

        unsafe {
            let arg = &mut func as *mut F as VALUE;
            protect(|| {
                let fptr = iter::<F, K, V> as unsafe extern "C" fn(VALUE, VALUE, VALUE) -> c_int;
                #[cfg(ruby_lt_2_7)]
                let fptr: unsafe extern "C" fn() -> c_int = std::mem::transmute(fptr);
                rb_hash_foreach(self.as_rb_value(), Some(fptr), arg);
                Ruby::get_with(self).qnil()
            })?;
        }
        Ok(())
    }

    /// Return `self` converted to a Rust [`HashMap`].
    ///
    /// This will only convert to a map of 'owned' Rust native types. The types
    /// representing Ruby objects can not be stored in a heap-allocated
    /// datastructure like a [`HashMap`] as they are hidden from the mark phase
    /// of Ruby's garbage collector, and thus may be prematurely garbage
    /// collected in the following sweep phase.
    ///
    /// Errors if the conversion of any key or value fails.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::collections::HashMap;
    ///
    /// use magnus::{eval, RHash};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let r_hash: RHash = eval(r#"{"answer" => 42}"#).unwrap();
    /// let mut hash_map = HashMap::new();
    /// hash_map.insert(String::from("answer"), 42);
    /// assert_eq!(r_hash.to_hash_map().unwrap(), hash_map);
    /// ```
    pub fn to_hash_map<K, V>(self) -> Result<HashMap<K, V>, Error>
    where
        K: TryConvertOwned + Eq + Hash,
        V: TryConvertOwned,
    {
        let mut map = HashMap::new();
        self.foreach(|key, value| {
            map.insert(key, value);
            Ok(ForEach::Continue)
        })?;
        Ok(map)
    }

    /// Convert `self` to a Rust vector of key/value pairs.
    ///
    /// This will only convert to a map of 'owned' Rust native types. The types
    /// representing Ruby objects can not be stored in a heap-allocated
    /// datastructure like a [`Vec`] as they are hidden from the mark phase
    /// of Ruby's garbage collector, and thus may be prematurely garbage
    /// collected in the following sweep phase.
    ///
    /// Errors if the conversion of any key or value fails.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, RHash};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let r_hash: RHash = eval(r#"{"answer" => 42}"#).unwrap();
    /// assert_eq!(r_hash.to_vec().unwrap(), vec![(String::from("answer"), 42)]);
    /// ```
    pub fn to_vec<K, V>(self) -> Result<Vec<(K, V)>, Error>
    where
        K: TryConvertOwned,
        V: TryConvertOwned,
    {
        let mut vec = Vec::with_capacity(self.len());
        self.foreach(|key, value| {
            vec.push((key, value));
            Ok(ForEach::Continue)
        })?;
        Ok(vec)
    }

    /// Return the number of entries in `self` as a Ruby [`Fixnum`].
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, RHash};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let hash: RHash = eval(r#"{"foo" => 1, "bar" => 2, "baz" => 4}"#).unwrap();
    /// assert_eq!(hash.size().to_i64(), 3);
    /// ```
    pub fn size(self) -> Fixnum {
        unsafe { Fixnum::from_rb_value_unchecked(rb_hash_size(self.as_rb_value())) }
    }

    /// Return the number of entries in `self` as a Rust [`usize`].
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, RHash};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let hash: RHash = eval(r#"{"foo" => 1, "bar" => 2, "baz" => 4}"#).unwrap();
    /// assert_eq!(hash.len(), 3);
    /// ```
    pub fn len(self) -> usize {
        unsafe { rb_hash_size_num(self.as_rb_value()) as usize }
    }

    /// Return whether self contains any entries or not.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::RHash;
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let hash = RHash::new();
    /// assert!(hash.is_empty());
    /// hash.aset("answer", 42).unwrap();
    /// assert!(!hash.is_empty());
    /// ```
    pub fn is_empty(self) -> bool {
        self.len() == 0
    }
}

impl fmt::Display for RHash {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", unsafe { self.to_s_infallible() })
    }
}

impl fmt::Debug for RHash {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.inspect())
    }
}

impl IntoValue for RHash {
    #[inline]
    fn into_value_with(self, _: &Ruby) -> Value {
        self.0.get()
    }
}

impl<K, V> IntoValue for HashMap<K, V>
where
    K: IntoValueFromNative,
    V: IntoValueFromNative,
{
    fn into_value_with(self, handle: &Ruby) -> Value {
        let hash = handle.hash_new();
        for (k, v) in self {
            let _ = hash.aset(k, v);
        }
        hash.into_value_with(handle)
    }
}

unsafe impl<K, V> IntoValueFromNative for HashMap<K, V>
where
    K: IntoValueFromNative,
    V: IntoValueFromNative,
{
}

#[cfg(feature = "friendly-api")]
impl<K, V> FromIterator<(K, V)> for RHash
where
    K: IntoValue,
    V: IntoValue,
{
    fn from_iter<I>(iter: I) -> Self
    where
        I: IntoIterator<Item = (K, V)>,
    {
        let hash = RHash::new();
        for (k, v) in iter {
            let _ = hash.aset(k, v);
        }
        hash
    }
}

impl Object for RHash {}

unsafe impl private::ReprValue for RHash {}

impl ReprValue for RHash {}

impl TryConvert for RHash {
    fn try_convert(val: Value) -> Result<Self, Error> {
        debug_assert_value!(val);
        if let Some(v) = Self::from_value(val) {
            return Ok(v);
        }
        unsafe {
            protect(|| Value::new(rb_check_hash_type(val.as_rb_value()))).and_then(|res| {
                Self::from_value(res).ok_or_else(|| {
                    Error::new(
                        Ruby::get_with(val).exception_type_error(),
                        format!("no implicit conversion of {} into Hash", val.class()),
                    )
                })
            })
        }
    }
}