forked from georust/gdal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cpl.rs
227 lines (191 loc) · 5.81 KB
/
cpl.rs
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
//! GDAL Common Portability Library Functions
//!
//! This module provides safe access to a subset of the [GDAL CPL functions](https://gdal.org/api/cpl.html).
//!
use std::ffi::CString;
use std::fmt::{Debug, Formatter};
use std::ptr;
use gdal_sys::{CSLCount, CSLDestroy, CSLFetchNameValue, CSLGetField, CSLSetNameValue};
use libc::c_char;
use crate::errors::{GdalError, Result};
use crate::utils::{_string, _string_tuple};
/// Wraps a [`gdal_sys::CSLConstList`] (a.k.a. `char **papszStrList`)
///
/// See the [`CSL*` GDAL functions](https://gdal.org/api/cpl.html#cpl-string-h) for more details.
pub struct CslStringList {
list_ptr: *mut *mut c_char,
}
impl CslStringList {
pub fn new() -> Self {
Self {
list_ptr: ptr::null_mut(),
}
}
/// Assigns `value` to `name`.
///
/// Overwrites duplicate `name`s.
///
/// Returns `Ok<()>` on success, `Err<GdalError>` if `name` has non alphanumeric
/// characters, or `value` has newline characters.
pub fn set_name_value(&mut self, name: &str, value: &str) -> Result<()> {
if !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
return Err(GdalError::BadArgument(format!(
"Invalid characters in name: '{}'",
name
)));
}
if value.contains(|c| c == '\n' || c == '\r') {
return Err(GdalError::BadArgument(format!(
"Invalid characters in value: '{}'",
value
)));
}
let psz_name = CString::new(name)?;
let psz_value = CString::new(value)?;
unsafe {
self.list_ptr = CSLSetNameValue(self.list_ptr, psz_name.as_ptr(), psz_value.as_ptr());
}
Ok(())
}
/// Looks up the value corresponding to `key`.
///
/// See [`CSLFetchNameValue`](https://gdal.org/doxygen/cpl__string_8h.html#a4f23675f8b6f015ed23d9928048361a1)
/// for details.
pub fn fetch_name_value(&self, key: &str) -> Result<Option<String>> {
let key = CString::new(key)?;
let c_value = unsafe { CSLFetchNameValue(self.as_ptr(), key.as_ptr()) };
let value = if c_value.is_null() {
None
} else {
Some(_string(c_value))
};
Ok(value)
}
/// Determine the number of entries in the list.
pub fn len(&self) -> isize {
unsafe { CSLCount(self.as_ptr()) as isize }
}
/// Determine if the list has any values
pub fn is_empty(&self) -> bool {
self.len() <= 0
}
/// Get an iterator over the name/value elements of the list.
pub fn iter(&self) -> CslStringListIterator {
CslStringListIterator::new(self)
}
/// Get the raw pointer behind list's data.
pub fn as_ptr(&self) -> gdal_sys::CSLConstList {
self.list_ptr
}
}
impl Drop for CslStringList {
fn drop(&mut self) {
unsafe { CSLDestroy(self.list_ptr) }
}
}
impl Default for CslStringList {
fn default() -> Self {
Self::new()
}
}
pub struct CslStringListIterator<'a> {
list: &'a CslStringList,
idx: isize,
count: isize,
}
impl<'a> CslStringListIterator<'a> {
fn new(list: &'a CslStringList) -> Self {
Self {
list,
idx: 0,
count: list.len(),
}
}
fn is_done(&self) -> bool {
self.idx >= self.count
}
}
impl<'a> Iterator for CslStringListIterator<'a> {
type Item = (String, String);
fn next(&mut self) -> Option<Self::Item> {
if self.is_done() {
return None;
}
let field = unsafe { CSLGetField(self.list.as_ptr(), self.idx as libc::c_int) };
if field.is_null() {
None
} else {
self.idx += 1;
_string_tuple(field, '=')
}
}
}
impl Debug for CslStringList {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
for (k, v) in self.iter() {
f.write_fmt(format_args!("{k}={v}\n"))?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use crate::cpl::CslStringList;
use crate::errors::Result;
fn fixture() -> Result<CslStringList> {
let mut l = CslStringList::new();
l.set_name_value("ONE", "1")?;
l.set_name_value("TWO", "2")?;
l.set_name_value("THREE", "3")?;
Ok(l)
}
#[test]
fn basic_list() -> Result<()> {
let l = fixture()?;
assert!(matches!(l.fetch_name_value("ONE"), Ok(Some(s)) if s == *"1"));
assert!(matches!(l.fetch_name_value("THREE"), Ok(Some(s)) if s == *"3"));
assert!(matches!(l.fetch_name_value("FOO"), Ok(None)));
Ok(())
}
#[test]
fn has_length() -> Result<()> {
let l = fixture()?;
assert_eq!(l.len(), 3);
Ok(())
}
#[test]
fn can_be_empty() -> Result<()> {
let l = CslStringList::new();
assert!(l.is_empty());
let l = fixture()?;
assert!(!l.is_empty());
Ok(())
}
#[test]
fn has_iterator() -> Result<()> {
let f = fixture()?;
let mut it = f.iter();
assert_eq!(it.next(), Some(("ONE".to_string(), "1".to_string())));
assert_eq!(it.next(), Some(("TWO".to_string(), "2".to_string())));
assert_eq!(it.next(), Some(("THREE".to_string(), "3".to_string())));
assert_eq!(it.next(), None);
assert_eq!(it.next(), None);
Ok(())
}
#[test]
fn invalid_keys() -> Result<()> {
let mut l = fixture()?;
assert!(l.set_name_value("l==t", "2").is_err());
assert!(l.set_name_value("foo", "2\n4\r5").is_err());
Ok(())
}
#[test]
fn debug_fmt() -> Result<()> {
let l = fixture()?;
let s = format!("{l:?}");
assert!(s.contains("ONE=1"));
assert!(s.contains("TWO=2"));
assert!(s.contains("THREE=3"));
Ok(())
}
}