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

use crate::table::column::{ColumnType, ColumnKind, ColumnData, FromDataError};

use std::time::{SystemTime, UNIX_EPOCH};
use std::fmt;
use std::str::FromStr;
use std::borrow::Cow;

use rand::{RngCore, rngs::OsRng};
use base64::engine::{Engine, general_purpose::URL_SAFE_NO_PAD};
use base64::DecodeError;

use serde::{Serialize, Deserialize};
use serde::ser::Serializer;
use serde::de::{Deserializer, Error};

/// A UniqueId that can be used within a database. 
/// Is not cryptographically secure and could be bruteforced.
///
/// Contains 10bytes
/// - 0..5 are seconds since the UNIX_EPOCH 
/// - 5..10 are random
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct UniqueId([u8; 10]);

impl UniqueId {
	pub fn new() -> Self {
		let secs_bytes = SystemTime::now()
			.duration_since(UNIX_EPOCH)
			.expect("SystemTime before UNIX EPOCH!")
			.as_secs()
			.to_be_bytes();

		let mut bytes = [0u8; 10];
		bytes[..5].copy_from_slice(&secs_bytes[3..8]);

		OsRng.fill_bytes(&mut bytes[5..]);

		Self(bytes)
	}

	/// This creates a unique id with it's raw content
	/// making it able to be called in a const context.
	pub const fn from_raw(inner: [u8; 10]) -> Self {
		Self(inner)
	}

	pub fn from_slice_unchecked(slice: &[u8]) -> Self {
		let mut bytes = [0u8; 10];
		bytes.copy_from_slice(slice);
		Self(bytes)
	}

	pub fn to_b64(&self) -> String {
		URL_SAFE_NO_PAD.encode(self.0)
	}

	// this panics if b64 has not a length of 14
	pub fn parse_from_b64<T>(b64: T) -> Result<Self, DecodeError>
	where T: AsRef<[u8]> {
		let mut bytes = [0u8; 10];
		URL_SAFE_NO_PAD.decode_slice_unchecked(b64, &mut bytes)
			.map(|n| assert_eq!(n, bytes.len()))
			.map(|_| Self(bytes))
	}

	pub fn from_bytes(bytes: [u8; 10]) -> Self {
		Self(bytes)
	}

	pub fn into_bytes(self) -> [u8; 10] {
		self.0
	}

	pub fn since_unix_secs(&self) -> u64 {
		let mut bytes = [0u8; 8];
		bytes[3..].copy_from_slice(&self.0[..5]);
		u64::from_be_bytes(bytes)
	}

	pub fn as_slice(&self) -> &[u8] {
		&self.0
	}
}

impl fmt::Debug for UniqueId {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		f.debug_tuple("UniqueId")
			.field(&self.to_b64())
			.finish()
	}
}

impl fmt::Display for UniqueId {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		self.to_b64().fmt(f)
	}
}

impl FromStr for UniqueId {
	type Err = DecodeError;

	fn from_str(s: &str) -> Result<Self, Self::Err> {
		Self::parse_from_b64(s)
	}
}

impl From<DecodeError> for FromDataError {
	fn from(e: DecodeError) -> Self {
		Self::CustomString(format!("uniqueid decode error {:?}", e))
	}
}

impl ColumnType for UniqueId {

	fn column_kind() -> ColumnKind {
		ColumnKind::FixedText(14)
	}

	fn to_data(&self) -> ColumnData<'_> {
		ColumnData::Text(self.to_b64().into())
	}

	fn from_data(data: ColumnData) -> Result<Self, FromDataError> {
		match data {
			ColumnData::Text(s) if s.len() == 14 => Ok(Self::parse_from_b64(s.as_str())?),
			_ => Err(FromDataError::ExpectedType("char with 14 chars for unique id"))
		}
	}

}
// SERDE

impl Serialize for UniqueId {
	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
	where S: Serializer {
		serializer.serialize_str(&self.to_b64())
	}
}

impl<'de> Deserialize<'de> for UniqueId {
	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
	where D: Deserializer<'de> {
		let s: Cow<'_, str> = Deserialize::deserialize(deserializer)?;
		let s = s.as_ref();
		if s.len() == 14 {
			UniqueId::parse_from_b64(s)
				.map_err(D::Error::custom)
		} else {
			Err(D::Error::custom("expected string with exactly 14 characters"))
		}
	}
}

#[cfg(feature = "protobuf")]
mod protobuf {
	use super::*;

	use fire_protobuf::{
		WireType,
		encode::{
			EncodeMessage, MessageEncoder, FieldOpt, SizeBuilder, EncodeError
		},
		decode::{DecodeMessage, FieldKind, DecodeError},
		bytes::BytesWrite
	};

	impl EncodeMessage for UniqueId {
		const WIRE_TYPE: WireType = WireType::Len;

		fn is_default(&self) -> bool {
			false
		}

		fn encoded_size(
			&mut self,
			field: Option<FieldOpt>,
			builder: &mut SizeBuilder
		) -> Result<(), EncodeError> {
			self.0.encoded_size(field, builder)
		}

		fn encode<B>(
			&mut self,
			field: Option<FieldOpt>,
			encoder: &mut MessageEncoder<B>
		) -> Result<(), EncodeError>
		where B: BytesWrite {
			self.0.encode(field, encoder)
		}
	}

	impl<'m> DecodeMessage<'m> for UniqueId {
		const WIRE_TYPE: WireType = WireType::Len;

		fn decode_default() -> Self {
			Self::from_raw([0; 10])
		}

		fn merge(
			&mut self,
			kind: FieldKind<'m>,
			is_field: bool
		) -> Result<(), DecodeError> {
			self.0.merge(kind, is_field)
		}
	}
}

#[cfg(feature = "graphql")]
mod graphql {
	use super::*;

	use juniper::{graphql_scalar, Value};

	#[graphql_scalar]
	impl<S> GraphQlScalar for UniqueId
	where S: ScalarValue {
		fn resolve(&self) -> Value {
			Value::scalar(self.to_string())
		}

		fn from_input_value(value: &InputValue) -> Option<UniqueId> {
			value.as_string_value().and_then(|s| s.parse().ok())
		}

		fn from_str<'a>(
			value: ScalarToken<'a>
		) -> juniper::ParseScalarResult<'a, S> {
			<String as juniper::ParseScalarValue<S>>::from_str(value)
		}
	}
}

#[cfg(test)]
mod tests {

	use super::*;
	use serde_json::{Value, from_value, from_str};

	// abcdefghijklmnopqrstuvwxyz

	#[test]
	fn serde_test() {
		let s = "\"AGCGeWIDTlipbg\"";
		let d: UniqueId = from_str(s).unwrap();
		assert_eq!(d.to_string(), "AGCGeWIDTlipbg");

		let v = Value::String("AGCGeWIDTlipbg".into());
		let d: UniqueId = from_value(v).unwrap();
		assert_eq!(d.to_string(), "AGCGeWIDTlipbg");
	}

}