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
use crate::cassandra::error::*;
use crate::cassandra::user_type::UserType;
use crate::cassandra::util::{Protected, ProtectedInner};
use crate::cassandra::value::ValueType;

use crate::cassandra_sys::cass_data_sub_type_count;
use crate::cassandra_sys::cass_data_type_add_sub_type;
use crate::cassandra_sys::cass_data_type_add_sub_type_by_name_n;
use crate::cassandra_sys::cass_data_type_add_sub_value_type;
use crate::cassandra_sys::cass_data_type_add_sub_value_type_by_name_n;
use crate::cassandra_sys::cass_data_type_class_name;
use crate::cassandra_sys::cass_data_type_free;
use crate::cassandra_sys::cass_data_type_keyspace;
use crate::cassandra_sys::cass_data_type_new;
use crate::cassandra_sys::cass_data_type_new_from_existing;
use crate::cassandra_sys::cass_data_type_new_tuple;
use crate::cassandra_sys::cass_data_type_new_udt;
use crate::cassandra_sys::cass_data_type_set_class_name_n;
use crate::cassandra_sys::cass_data_type_set_keyspace_n;
use crate::cassandra_sys::cass_data_type_set_type_name_n;
use crate::cassandra_sys::cass_data_type_sub_data_type;
use crate::cassandra_sys::cass_data_type_sub_data_type_by_name_n;
use crate::cassandra_sys::cass_data_type_sub_type_name;
use crate::cassandra_sys::cass_data_type_type;
use crate::cassandra_sys::cass_data_type_type_name;
use crate::cassandra_sys::cass_user_type_new_from_data_type;
use crate::cassandra_sys::CassDataType as _CassDataType;

use std::ffi::CString;
use std::marker::PhantomData;
use std::os::raw::c_char;

/// Any Cassandra datatype. This is an owned type.
#[derive(Debug)]
pub struct DataType(*mut _CassDataType);

/// Any Cassandra datatype. This is a reference type.
//
// Borrowed from whatever descriptor contains the type, e.g., a `SchemaMeta`.
#[derive(Debug)]
pub struct ConstDataType<'a>(*const _CassDataType, PhantomData<&'a _CassDataType>);

// The underlying C types have no thread-local state, and forbids only concurrent
// mutation/free: https://datastax.github.io/cpp-driver/topics/#thread-safety
unsafe impl Send for DataType {}
unsafe impl Sync for DataType {}
unsafe impl Send for ConstDataType<'_> {}
unsafe impl Sync for ConstDataType<'_> {}

impl ProtectedInner<*mut _CassDataType> for DataType {
    fn inner(&self) -> *mut _CassDataType {
        self.0
    }
}

impl Protected<*mut _CassDataType> for DataType {
    fn build(inner: *mut _CassDataType) -> Self {
        if inner.is_null() {
            panic!("Unexpected null pointer")
        };
        DataType(inner)
    }
}

impl ProtectedInner<*const _CassDataType> for ConstDataType<'_> {
    fn inner(&self) -> *const _CassDataType {
        self.0
    }
}

impl Protected<*const _CassDataType> for ConstDataType<'_> {
    fn build(inner: *const _CassDataType) -> Self {
        if inner.is_null() {
            panic!("Unexpected null pointer")
        };
        ConstDataType(inner, PhantomData)
    }
}

impl Drop for DataType {
    /// Frees a data type instance.
    fn drop(&mut self) {
        unsafe { cass_data_type_free(self.0) }
    }
}

impl ConstDataType<'_> {
    /// Creates a new user defined type from existing data type.
    pub fn new_user_type(&self) -> UserType {
        unsafe { UserType::build(cass_user_type_new_from_data_type(self.0)) }
    }
}

impl DataType {
    /// Creates a new data type with value type.
    pub fn new(value_type: ValueType) -> Self {
        unsafe { DataType(cass_data_type_new(value_type.inner())) }
    }

    /// Creates a new data type from an existing data type.
    // TODO: can return NULL
    pub fn new_user_type(&self) -> UserType {
        unsafe { UserType::build(cass_user_type_new_from_data_type(self.0)) }
    }

    /// Creates a new data type from an existing data type.
    pub fn new_from_existing(&self) -> Self {
        unsafe { DataType(cass_data_type_new_from_existing(self.0)) }
    }

    /// Creates a new tuple data type.
    pub fn new_tuple(item_count: usize) -> Self {
        unsafe { DataType(cass_data_type_new_tuple(item_count)) }
    }

    /// Creates a new UDT (user defined type) data type.
    pub fn new_udt(field_count: usize) -> DataType {
        unsafe { DataType(cass_data_type_new_udt(field_count)) }
    }

    /// Gets the value type of the specified data type.
    pub fn get_type(data_type: DataType) -> ValueType {
        unsafe { ValueType::build(cass_data_type_type(data_type.0)) }
    }

    /// Gets the type name of a UDT data type.
    pub fn type_name<S>(data_type: DataType, type_name: S) -> Result<()>
    where
        S: Into<String>,
    {
        unsafe {
            let type_name2 = CString::new(type_name.into())?;
            let err = cass_data_type_type_name(
                data_type.0,
                &mut type_name2.as_ptr(),
                &mut (type_name2.as_bytes().len()),
            );
            err.to_result(())
        }
    }

    /// Sets the type name of a UDT data type.
    ///
    /// <b>Note:</b> Only valid for UDT data types.
    pub fn set_type_name<S>(data_type: DataType, type_name: S) -> Result<()>
    where
        S: Into<String>,
    {
        unsafe {
            let type_name_str = type_name.into();
            let type_name_ptr = type_name_str.as_ptr() as *const c_char;
            cass_data_type_set_type_name_n(data_type.0, type_name_ptr, type_name_str.len())
                .to_result(())
        }
    }

    /// Gets the type name of a UDT data type.
    ///
    /// <b>Note:</b> Only valid for UDT data types.
    pub fn keyspace<S>(data_type: DataType, keyspace: S) -> Result<()>
    where
        S: Into<String>,
    {
        unsafe {
            let keyspace2 = CString::new(keyspace.into())?;
            cass_data_type_keyspace(
                data_type.0,
                &mut (keyspace2.as_ptr()),
                &mut (keyspace2.as_bytes().len()),
            )
            .to_result(())
        }
    }

    /// Sets the keyspace of a UDT data type.
    ///
    /// <b>Note:</b> Only valid for UDT data types.
    pub fn set_keyspace<S>(data_type: DataType, keyspace: S) -> Result<()>
    where
        S: Into<String>,
    {
        unsafe {
            let keyspace_str = keyspace.into();
            let keyspace_ptr = keyspace_str.as_ptr() as *const c_char;
            cass_data_type_set_keyspace_n(data_type.0, keyspace_ptr, keyspace_str.len())
                .to_result(())
        }
    }

    /// Gets the class name of a custom data type.
    ///
    /// <b>Note:</b> Only valid for custom data types.
    pub fn class_name<S>(data_type: DataType, class_name: S) -> Result<()>
    where
        S: Into<String>,
    {
        unsafe {
            let class_name2 = CString::new(class_name.into())?;
            cass_data_type_class_name(
                data_type.0,
                &mut class_name2.as_ptr(),
                &mut (class_name2.as_bytes().len()),
            )
            .to_result(())
        }
    }

    /// Sets the class name of a custom data type.
    ///
    /// <b>Note:</b> Only valid for custom data types.
    pub fn set_class_name<S>(&self, class_name: S) -> Result<()>
    where
        S: Into<String>,
    {
        unsafe {
            let class_name_str = class_name.into();
            let class_name_ptr = class_name_str.as_ptr() as *const c_char;
            cass_data_type_set_class_name_n(self.0, class_name_ptr, class_name_str.len())
                .to_result(())
        }
    }

    /// Gets the sub-data type count of a UDT (user defined type), tuple
    /// or collection.
    ///
    /// <b>Note:</b> Only valid for UDT, tuple and collection data types.
    pub fn sub_type_count<S>(&self) -> usize {
        unsafe { cass_data_sub_type_count(self.0) }
    }

    /// Gets the sub-data type of a UDT (user defined type), tuple or collection at
    /// the specified index.
    ///
    /// <b>Note:</b> Only valid for UDT, tuple and collection data types.
    pub fn sub_data_type(&self, index: usize) -> ConstDataType {
        // TODO: can return NULL
        unsafe { ConstDataType::build(cass_data_type_sub_data_type(self.0, index)) }
    }

    /// Gets the sub-data type of a UDT (user defined type) at the specified index.
    ///
    /// <b>Note:</b> Only valid for UDT data types.
    pub fn sub_data_type_by_name<S>(&self, name: S) -> ConstDataType
    where
        S: Into<String>,
    {
        unsafe {
            let name_str = name.into();
            let name_ptr = name_str.as_ptr() as *const c_char;
            // TODO: can return NULL
            ConstDataType::build(cass_data_type_sub_data_type_by_name_n(
                self.0,
                name_ptr,
                name_str.len(),
            ))
        }
    }

    /// Gets the sub-type name of a UDT (user defined type) at the specified index.
    ///
    /// <b>Note:</b> Only valid for UDT data types.
    pub fn sub_type_name<S>(&self, index: usize, name: S) -> Result<()>
    where
        S: Into<String>,
    {
        unsafe {
            let name2 = CString::new(name.into())?;
            cass_data_type_sub_type_name(
                self.0,
                index,
                &mut name2.as_ptr(),
                &mut (name2.as_bytes().len()),
            )
            .to_result(())
        }
    }

    /// Adds a sub-data type to a tuple or collection.
    ///
    /// <b>Note:</b> Only valid for tuple and collection data types.
    pub fn add_sub_type(&self, sub_data_type: DataType) -> Result<()> {
        unsafe { cass_data_type_add_sub_type(self.0, sub_data_type.0).to_result(()) }
    }

    /// Gets the sub-data type of a UDT (user defined type) at the specified index.
    ///
    /// <b>Note:</b> Only valid for UDT data types.
    pub fn add_sub_type_by_name<S>(&mut self, name: S, sub_data_type: DataType) -> Result<()>
    where
        S: Into<String>,
    {
        unsafe {
            let name_str = name.into();
            let name_ptr = name_str.as_ptr() as *const c_char;
            cass_data_type_add_sub_type_by_name_n(self.0, name_ptr, name_str.len(), sub_data_type.0)
                .to_result(())
        }
    }

    /// Adds a sub-data type to a tuple or collection using a value type.
    ///
    /// <b>Note:</b> Only valid for tuple and collection data types.
    pub fn add_sub_value_type<S>(&self, sub_value_type: ValueType) -> Result<()>
    where
        S: Into<String>,
    {
        unsafe { cass_data_type_add_sub_value_type(self.0, sub_value_type.inner()).to_result(()) }
    }

    /// Adds a sub-data type to a tuple or collection using a value type.
    ///
    /// <b>Note:</b> Only valid for tuple and collection data types.
    pub fn add_sub_value_type_by_name<S>(&self, name: S, typ: ValueType) -> Result<()>
    where
        S: Into<String>,
    {
        unsafe {
            let name_str = name.into();
            let name_ptr = name_str.as_ptr() as *const c_char;
            cass_data_type_add_sub_value_type_by_name_n(
                self.0,
                name_ptr,
                name_str.len(),
                typ.inner(),
            )
            .to_result(())
        }
    }

    //    pub fn set_type_name_n<S>(data_type: DataType, type_name: S) -> Result<(), CassError>
    //        where S: Into<String>
    //    {
    //        unsafe {
    //            let type_name = CString::new(type_name.into()).unwrap();
    //            CassError::build(cass_data_type_set_type_name_n(data_type.0,
    //                                                            type_name.as_ptr(),
    //                                                            type_name.as_bytes().len() as u64))
    //                .wrap(())
    //        }
    //    }

    //    pub fn set_class_name_n<S>(data_type: DataType, class_name: S) -> Result<(), CassError>
    //        where S: Into<String>
    //    {
    //        unsafe {
    //            let class_name = CString::new(class_name.into()).unwrap();
    //            CassError::build(cass_data_type_set_class_name_n(data_type.0,
    //                                                             class_name.as_ptr(),
    //                                                             class_name.as_bytes().len() as u64))
    //                .wrap(())
    //        }
    //    }

    //    pub fn sub_data_type_by_name_n<S>(data_type: DataType, name: S) -> ConstDataType
    //        where S: Into<String>
    //    {
    //        unsafe {
    //            let name = CString::new(name.into()).unwrap();
    //            // TODO: can return NULL
    //            ConstDataType::build(cass_data_type_sub_data_type_by_name_n(data_type.0,
    //                                                                 name.as_ptr(),
    //                                                                 name.as_bytes().len() as u64))
    //        }
    //    }
}