forked from transact-rs/sqlx
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencode.rs
More file actions
82 lines (68 loc) 路 1.7 KB
/
Copy pathencode.rs
File metadata and controls
82 lines (68 loc) 路 1.7 KB
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
//! Types and traits for encoding values to the database.
use crate::database::Database;
use crate::types::HasSqlType;
use std::mem;
/// The return type of [Encode::encode].
pub enum IsNull {
/// The value is null; no data was written.
Yes,
/// The value is not null.
///
/// This does not mean that data was written.
No,
}
/// Encode a single value to be sent to the database.
pub trait Encode<DB>
where
DB: Database + ?Sized,
{
/// Writes the value of `self` into `buf` in the expected format for the database.
fn encode(&self, buf: &mut Vec<u8>);
fn encode_nullable(&self, buf: &mut Vec<u8>) -> IsNull {
self.encode(buf);
IsNull::No
}
fn size_hint(&self) -> usize {
mem::size_of_val(self)
}
}
impl<T: ?Sized, DB> Encode<DB> for &'_ T
where
DB: Database + HasSqlType<T>,
T: Encode<DB>,
{
fn encode(&self, buf: &mut Vec<u8>) {
(*self).encode(buf)
}
fn encode_nullable(&self, buf: &mut Vec<u8>) -> IsNull {
(*self).encode_nullable(buf)
}
fn size_hint(&self) -> usize {
(*self).size_hint()
}
}
impl<T, DB> Encode<DB> for Option<T>
where
DB: Database + HasSqlType<T>,
T: Encode<DB>,
{
fn encode(&self, buf: &mut Vec<u8>) {
// Forward to [encode_nullable] and ignore the result
let _ = self.encode_nullable(buf);
}
fn encode_nullable(&self, buf: &mut Vec<u8>) -> IsNull {
if let Some(self_) = self {
self_.encode(buf);
IsNull::No
} else {
IsNull::Yes
}
}
fn size_hint(&self) -> usize {
if self.is_some() {
(*self).size_hint()
} else {
0
}
}
}