Debian Codegraph @

third_party/rust/cubeb-pulse/src/backend/intern.rs

raw
1 // Copyright © 2017-2018 Mozilla Foundation
2 //
3 // This program is made available under an ISC-style license. See the
4 // accompanying file LICENSE for details.
5
6 use std::ffi::{CStr, CString};
7 use std::os::raw::c_char;
8
9 #[derive(Debug)]
10 pub struct Intern {
11 vec: Vec<CString>,
12 }
13
14 impl Intern {
15 pub fn new() -> Intern {
16 Intern { vec: Vec::new() }
17 }
18
19 pub fn add(&mut self, string: &CStr) -> *const c_char {
20 fn eq(s1: &CStr, s2: &CStr) -> bool {
21 s1 == s2
22 }
23 for s in &self.vec {
24 if eq(s, string) {
25 return s.as_ptr();
26 }
27 }
28
29 self.vec.push(string.to_owned());
30 self.vec.last().unwrap().as_ptr()
31 }
32 }
33
34 #[cfg(test)]
35 mod tests {
36 use super::Intern;
37 use std::ffi::CStr;
38
39 #[test]
40 fn intern() {
41 fn cstr(str: &[u8]) -> &CStr {
42 CStr::from_bytes_with_nul(str).unwrap()
43 }
44
45 let mut intern = Intern::new();
46
47 let foo_ptr = intern.add(cstr(b"foo\0"));
48 let bar_ptr = intern.add(cstr(b"bar\0"));
49 assert!(!foo_ptr.is_null());
50 assert!(!bar_ptr.is_null());
51 assert!(foo_ptr != bar_ptr);
52
53 assert!(foo_ptr == intern.add(cstr(b"foo\0")));
54 assert!(foo_ptr != intern.add(cstr(b"fo\0")));
55 assert!(foo_ptr != intern.add(cstr(b"fool\0")));
56 assert!(foo_ptr != intern.add(cstr(b"not foo\0")));
57 }
58 }