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
use crate::{
	vocabulary, BlankIdBuf, BlankIdVocabularyMut, Id, Namespace, Vocabulary, VocabularyMut,
};

#[cfg(feature = "meta")]
use locspan::Meta;

/// Subject identifier generator.
pub trait Generator<N: Namespace> {
	/// Generates the next fresh identifier in the given namespace.
	fn next(&mut self, namespace: &mut N) -> N::Id;

	#[cfg(feature = "meta")]
	/// Generates identifiers annotated with the given metadata.
	fn with_metadata<M>(self, metadata: M) -> WithMetadata<Self, M>
	where
		Self: Sized,
	{
		WithMetadata {
			metadata,
			generator: self,
		}
	}

	#[cfg(feature = "meta")]
	/// Generates identifiers annotated with the default value of type `M`.
	fn with_default_metadata<M: Default>(self) -> WithMetadata<Self, M>
	where
		Self: Sized,
	{
		WithMetadata {
			metadata: M::default(),
			generator: self,
		}
	}
}

impl<'a, N: Namespace, G: Generator<N>> Generator<N> for &'a mut G {
	fn next(&mut self, namespace: &mut N) -> N::Id {
		(*self).next(namespace)
	}
}

#[cfg(feature = "meta")]
/// Subject identifier generator, with metadata.
pub trait MetaGenerator<N: Namespace, M> {
	fn next(&mut self, namespace: &mut N) -> Meta<N::Id, M>;
}

#[cfg(feature = "meta")]
impl<'a, N: Namespace, M, G: MetaGenerator<N, M>> MetaGenerator<N, M> for &'a mut G {
	fn next(&mut self, namespace: &mut N) -> Meta<N::Id, M> {
		(*self).next(namespace)
	}
}

#[cfg(feature = "meta")]
pub struct WithMetadata<G, M> {
	metadata: M,
	generator: G,
}

#[cfg(feature = "meta")]
impl<G, M> WithMetadata<G, M> {
	pub fn metadata(&self) -> &M {
		&self.metadata
	}

	pub fn generator(&self) -> &G {
		&self.generator
	}
}

#[cfg(feature = "meta")]
impl<N: Namespace, G: Generator<N>, M> Generator<N> for WithMetadata<G, M> {
	fn next(&mut self, namespace: &mut N) -> N::Id {
		self.generator.next(namespace)
	}
}

#[cfg(feature = "meta")]
impl<N: Namespace, G: Generator<N>, M: Clone> MetaGenerator<N, M> for WithMetadata<G, M> {
	fn next(&mut self, namespace: &mut N) -> Meta<N::Id, M> {
		Meta(self.generator.next(namespace), self.metadata.clone())
	}
}

/// Generates numbered blank node identifiers,
/// with an optional prefix.
///
/// This generator can create `usize::MAX` unique blank node identifiers.
/// If [`Generator::next`] is called `usize::MAX + 1` times, it will panic.
#[derive(Default)]
pub struct Blank {
	/// Prefix string.
	prefix: String,

	/// Number of already generated identifiers.
	count: usize,
}

impl Blank {
	/// Creates a new numbered generator with no prefix.
	pub fn new() -> Self {
		Self::new_full(String::new(), 0)
	}

	/// Creates a new numbered generator with no prefix,
	/// starting with the given `offset` number.
	///
	/// The returned generator can create `usize::MAX - offset` unique blank node identifiers
	/// before panicking.
	pub fn new_with_offset(offset: usize) -> Self {
		Self::new_full(String::new(), offset)
	}

	/// Creates a new numbered generator with the given prefix.
	pub fn new_with_prefix(prefix: String) -> Self {
		Self::new_full(prefix, 0)
	}

	/// Creates a new numbered generator with the given prefix,
	/// starting with the given `offset` number.
	///
	/// The returned generator can create `usize::MAX - offset` unique blank node identifiers
	/// before panicking.
	pub fn new_full(prefix: String, offset: usize) -> Self {
		Self {
			prefix,
			count: offset,
		}
	}

	#[cfg(feature = "meta")]
	/// Generates identifiers annotated with the given metadata.
	pub fn with_metadata<M>(self, metadata: M) -> WithMetadata<Self, M>
	where
		Self: Sized,
	{
		WithMetadata {
			metadata,
			generator: self,
		}
	}

	#[cfg(feature = "meta")]
	/// Generates identifiers annotated with the default value of type `M`.
	pub fn with_default_metadata<M: Default>(self) -> WithMetadata<Self, M>
	where
		Self: Sized,
	{
		WithMetadata {
			metadata: M::default(),
			generator: self,
		}
	}

	/// Returns the prefix of this generator.
	pub fn prefix(&self) -> &str {
		&self.prefix
	}

	/// Returns the number of already generated identifiers.
	pub fn count(&self) -> usize {
		self.count
	}

	pub fn next_blank_id(&mut self) -> BlankIdBuf {
		let id = unsafe { BlankIdBuf::new_unchecked(format!("_:{}{}", self.prefix, self.count)) };
		self.count += 1;
		id
	}
}

impl<V: Vocabulary + BlankIdVocabularyMut> Generator<V> for Blank {
	fn next(&mut self, vocabulary: &mut V) -> Id<V::Iri, V::BlankId> {
		Id::Blank(vocabulary.insert_blank_id(&self.next_blank_id()))
	}
}

/// Generates UUID blank node identifiers based on the [`uuid`](https://crates.io/crates/uuid) crate.
///
/// This is an enum type with different UUID versions supported
/// by the `uuid` library, so you can choose which kind of UUID
/// better fits your application.
/// Version 1 is not supported.
///
/// You need to enable the `uuid-generator` feature to
/// use this type.
/// You also need to enable the features of each version you need
/// in the `uuid` crate.
pub enum Uuid {
	/// UUIDv3.
	///
	/// You must provide a vocabulary UUID and a name.
	/// See [uuid::Uuid::new_v3] for more information.
	#[cfg(feature = "uuid-generator-v3")]
	V3(uuid::Uuid, String),

	/// UUIDv4.
	///
	/// See [uuid::Uuid::new_v4] for more information.
	#[cfg(feature = "uuid-generator-v4")]
	V4,

	/// UUIDv5.
	///
	/// You must provide a vocabulary UUID and a name.
	/// See [uuid::Uuid::new_v5] for more information.
	#[cfg(feature = "uuid-generator-v5")]
	V5(uuid::Uuid, String),
}

#[cfg(any(
	feature = "uuid-generator-v3",
	feature = "uuid-generator-v4",
	feature = "uuid-generator-v5"
))]
impl Uuid {
	pub fn next_uuid(&self) -> uuid::Uuid {
		match self {
			#[cfg(feature = "uuid-generator-v3")]
			Self::V3(vocabulary, name) => uuid::Uuid::new_v3(vocabulary, name.as_bytes()),
			#[cfg(feature = "uuid-generator-v4")]
			Self::V4 => uuid::Uuid::new_v4(),
			#[cfg(feature = "uuid-generator-v5")]
			Self::V5(vocabulary, name) => uuid::Uuid::new_v5(vocabulary, name.as_bytes()),
		}
	}

	#[cfg(feature = "meta")]
	/// Generates identifiers annotated with the given metadata.
	pub fn with_metadata<M>(self, metadata: M) -> WithMetadata<Self, M>
	where
		Self: Sized,
	{
		WithMetadata {
			metadata,
			generator: self,
		}
	}

	#[cfg(feature = "meta")]
	/// Generates identifiers annotated with the default value of type `M`.
	pub fn with_default_metadata<M: Default>(self) -> WithMetadata<Self, M>
	where
		Self: Sized,
	{
		WithMetadata {
			metadata: M::default(),
			generator: self,
		}
	}
}

#[cfg(any(
	feature = "uuid-generator-v3",
	feature = "uuid-generator-v4",
	feature = "uuid-generator-v5"
))]
impl<V: crate::Vocabulary + crate::IriVocabularyMut> Generator<V> for Uuid {
	fn next(&mut self, vocabulary: &mut V) -> Id<V::Iri, V::BlankId> {
		unsafe {
			let mut buffer = Vec::with_capacity(uuid::adapter::Urn::LENGTH);
			let ptr = buffer.as_mut_ptr();
			let capacity = buffer.capacity();
			std::mem::forget(buffer);
			let uuid = self.next_uuid();
			let len = uuid
				.to_urn()
				.encode_lower(std::slice::from_raw_parts_mut(
					ptr,
					uuid::adapter::Urn::LENGTH,
				))
				.len();
			let buffer = Vec::from_raw_parts(ptr, len, capacity);
			let p = iref::parsing::ParsedIriRef::new(&buffer).unwrap();
			let iri = iref::IriBuf::from_raw_parts(buffer, p);
			Id::Iri(vocabulary.insert(iri.as_iri()))
		}
	}
}

#[cfg(any(
	feature = "uuid-generator-v3",
	feature = "uuid-generator-v4",
	feature = "uuid-generator-v5"
))]
#[cfg(test)]
mod tests {
	use super::*;

	#[cfg(feature = "uuid-generator-v3")]
	#[test]
	fn uuidv3_iri() {
		let mut uuid_gen = Uuid::V3(
			uuid::Uuid::parse_str("936DA01F9ABD4d9d80C702AF85C822A8").unwrap(),
			"test".to_string(),
		);
		for _ in 0..100 {
			let reference: Id = uuid_gen.next(&mut ());
			assert!(iref::IriBuf::new(reference.as_str()).is_ok())
		}
	}

	#[cfg(feature = "uuid-generator-v4")]
	#[test]
	fn uuidv4_iri() {
		let mut uuid_gen = Uuid::V4;
		for _ in 0..100 {
			let reference: Id = uuid_gen.next(&mut ());
			assert!(iref::IriBuf::new(reference.as_str()).is_ok())
		}
	}

	#[cfg(feature = "uuid-generator-v5")]
	#[test]
	fn uuidv5_iri() {
		let mut uuid_gen = Uuid::V5(
			uuid::Uuid::parse_str("936DA01F9ABD4d9d80C702AF85C822A8").unwrap(),
			"test".to_string(),
		);
		for _ in 0..100 {
			let reference: Id = uuid_gen.next(&mut ());
			assert!(iref::IriBuf::new(reference.as_str()).is_ok())
		}
	}
}

/// Wrapper around a generator to work with [`vocabulary::Scoped`].
///
/// Any generator for some vocabulary `V` can be wrapped around `Unscoped` to
/// work with `vocabulary::Scoped<V>`.
/// As the name implies, the identifier generated by such generator will
/// escape the scope of `vocabulary::Scoped`. This means that a collision can
/// still occur if multiple generators are used on the same vocabulary, even
/// wrapped inside different `vocabulary::Scoped`.
pub struct Unscoped<'a, G>(pub &'a mut G);

impl<'a, 'v, G: Generator<V>, V: VocabularyMut, S> Generator<vocabulary::Scoped<'v, V, S>>
	for Unscoped<'a, G>
where
	V::BlankId: Clone,
{
	fn next(&mut self, vocabulary: &mut vocabulary::Scoped<'v, V, S>) -> Id<V::Iri, V::BlankId> {
		self.0.next(vocabulary.inner)
	}
}