Skip to content

Commit 1f546b2

Browse files
Add functions to check for numerical and/or sequential keys (#115)
1 parent 3598d9c commit 1f546b2

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

src/types/array.rs

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,60 @@ impl ZendHashTable {
394394
Ok(())
395395
}
396396

397+
/// Checks if the hashtable only contains numerical keys.
398+
///
399+
/// # Returns
400+
///
401+
/// True if all keys on the hashtable are numerical.
402+
///
403+
/// # Example
404+
///
405+
/// ```no_run
406+
/// use ext_php_rs::types::ZendHashTable;
407+
///
408+
/// let mut ht = ZendHashTable::new();
409+
///
410+
/// ht.push(0);
411+
/// ht.push(3);
412+
/// ht.push(9);
413+
/// assert!(ht.has_numerical_keys());
414+
///
415+
/// ht.insert("obviously not numerical", 10);
416+
/// assert!(!ht.has_numerical_keys());
417+
/// ```
418+
pub fn has_numerical_keys(&self) -> bool {
419+
!self.iter().any(|(_, k, _)| k.is_some())
420+
}
421+
422+
/// Checks if the hashtable has numerical, sequential keys.
423+
///
424+
/// # Returns
425+
///
426+
/// True if all keys on the hashtable are numerical and are in sequential
427+
/// order (i.e. starting at 0 and not skipping any keys).
428+
///
429+
/// # Example
430+
///
431+
/// ```no_run
432+
/// use ext_php_rs::types::ZendHashTable;
433+
///
434+
/// let mut ht = ZendHashTable::new();
435+
///
436+
/// ht.push(0);
437+
/// ht.push(3);
438+
/// ht.push(9);
439+
/// assert!(ht.has_sequential_keys());
440+
///
441+
/// ht.insert_at_index(90, 10);
442+
/// assert!(!ht.has_sequential_keys());
443+
/// ```
444+
pub fn has_sequential_keys(&self) -> bool {
445+
!self
446+
.iter()
447+
.enumerate()
448+
.any(|(i, (k, strk, _))| i as u64 != k || strk.is_some())
449+
}
450+
397451
/// Returns an iterator over the key(s) and value contained inside the
398452
/// hashtable.
399453
///

0 commit comments

Comments
 (0)