]> git.proxmox.com Git - cargo.git/blob - vendor/curl/src/easy/list.rs
New upstream version 0.47.0
[cargo.git] / vendor / curl / src / easy / list.rs
1 use std::ffi::{CStr, CString};
2 use std::fmt;
3
4 use curl_sys;
5 use Error;
6
7 /// A linked list of a strings
8 pub struct List {
9 raw: *mut curl_sys::curl_slist,
10 }
11
12 /// An iterator over `List`
13 #[derive(Clone)]
14 pub struct Iter<'a> {
15 _me: &'a List,
16 cur: *mut curl_sys::curl_slist,
17 }
18
19 pub fn raw(list: &List) -> *mut curl_sys::curl_slist {
20 list.raw
21 }
22
23 pub unsafe fn from_raw(raw: *mut curl_sys::curl_slist) -> List {
24 List { raw: raw }
25 }
26
27 unsafe impl Send for List {}
28
29 impl List {
30 /// Creates a new empty list of strings.
31 pub fn new() -> List {
32 List { raw: 0 as *mut _ }
33 }
34
35 /// Appends some data into this list.
36 pub fn append(&mut self, data: &str) -> Result<(), Error> {
37 let data = CString::new(data)?;
38 unsafe {
39 let raw = curl_sys::curl_slist_append(self.raw, data.as_ptr());
40 assert!(!raw.is_null());
41 self.raw = raw;
42 Ok(())
43 }
44 }
45
46 /// Returns an iterator over the nodes in this list.
47 pub fn iter(&self) -> Iter {
48 Iter {
49 _me: self,
50 cur: self.raw,
51 }
52 }
53 }
54
55 impl fmt::Debug for List {
56 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
57 f.debug_list()
58 .entries(self.iter().map(String::from_utf8_lossy))
59 .finish()
60 }
61 }
62
63 impl<'a> IntoIterator for &'a List {
64 type IntoIter = Iter<'a>;
65 type Item = &'a [u8];
66
67 fn into_iter(self) -> Iter<'a> {
68 self.iter()
69 }
70 }
71
72 impl Drop for List {
73 fn drop(&mut self) {
74 unsafe { curl_sys::curl_slist_free_all(self.raw) }
75 }
76 }
77
78 impl<'a> Iterator for Iter<'a> {
79 type Item = &'a [u8];
80
81 fn next(&mut self) -> Option<&'a [u8]> {
82 if self.cur.is_null() {
83 return None;
84 }
85
86 unsafe {
87 let ret = Some(CStr::from_ptr((*self.cur).data).to_bytes());
88 self.cur = (*self.cur).next;
89 return ret;
90 }
91 }
92 }
93
94 impl<'a> fmt::Debug for Iter<'a> {
95 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
96 f.debug_list()
97 .entries(self.clone().map(String::from_utf8_lossy))
98 .finish()
99 }
100 }