protify 0.1.4

A Rust-first protobuf framework to generate packages from rust code, with validation included
Documentation
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
mod builder;
pub use builder::FloatValidatorBuilder;

use float_eq::FloatEq;
use float_eq::float_eq;

use super::*;

/// Validator for [`f32`](core::f32) and [`f64`](core::f64).
///
/// Unlike other validators, this contains two special parameters, namely [`abs_tolerance`](FloatValidator::abs_tolerance) and [`rel_tolerance`](FloatValidator::rel_tolerance), which are used in all operations involving the target floats.
///
/// These two represent the `abs` and `2nd` parameters in the [`float_eq!`] macro. For more information, see the [float_eq guide](https://jtempest.github.io/float_eq-rs/book/how_to/compare_floating_point_numbers.html)
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct FloatValidator<Num>
where
	Num: FloatWrapper,
{
	/// Adds custom validation using one or more [`CelRule`]s to this field.
	pub cel: Vec<CelProgram>,

	/// The conditions upon which this validator should be skipped.
	pub ignore: Ignore,

	#[cfg_attr(feature = "serde", serde(skip))]
	_wrapper: PhantomData<Num>,

	/// Specifies that the field must be set (if optional) or not equal to its zero value (if not optional) in order to be valid.
	pub required: bool,

	/// Represents the `abs` parameter in the [`float_eq!`] macro, and is used in all arithmetic operations for the validated floats. For more information, see the [float_eq guide](https://jtempest.github.io/float_eq-rs/book/how_to/compare_floating_point_numbers.html).
	pub abs_tolerance: Num,

	/// Represents the `r2nd` parameter in the [`float_eq!`] macro, and is used in all arithmetic operations for the validated floats. For more information, see the [float_eq guide](https://jtempest.github.io/float_eq-rs/book/how_to/compare_floating_point_numbers.html).
	pub rel_tolerance: Num,

	/// Specifies that this field must be finite (i.e. it can't represent Infinity or NaN).
	pub finite: bool,

	/// Specifies that only this specific value will be considered valid for this field.
	pub const_: Option<Num>,

	/// Specifies that this field's value will be valid only if it is smaller than the specified amount
	pub lt: Option<Num>,

	/// Specifies that this field's value will be valid only if it is smaller than, or equal to, the specified amount
	pub lte: Option<Num>,

	/// Specifies that this field's value will be valid only if it is greater than the specified amount
	pub gt: Option<Num>,

	/// Specifies that this field's value will be valid only if it is smaller than, or equal to, the specified amount
	pub gte: Option<Num>,

	/// Specifies that only the values in this list will be considered valid for this field.
	pub in_: Option<SortedList<OrderedFloat<Num>>>,

	/// Specifies that the values in this list will be considered NOT valid for this field.
	pub not_in: Option<SortedList<OrderedFloat<Num>>>,

	/// A map of custom error messages.
	pub error_messages: Option<ErrorMessages<Num::ViolationEnum>>,
}

impl<Num> FloatValidator<Num>
where
	Num: FloatWrapper,
{
	#[inline(never)]
	#[cold]
	fn custom_error_or_else(
		&self,
		violation: Num::ViolationEnum,
		default: impl Fn() -> String,
	) -> String {
		self.error_messages
			.as_deref()
			.and_then(|map| map.get(&violation))
			.map(|m| m.to_string())
			.unwrap_or_else(default)
	}
}

impl<Num> Default for FloatValidator<Num>
where
	Num: FloatWrapper + Default,
{
	#[inline]
	fn default() -> Self {
		Self {
			cel: Default::default(),
			ignore: Default::default(),
			_wrapper: Default::default(),
			required: Default::default(),
			abs_tolerance: Default::default(),
			rel_tolerance: Default::default(),
			finite: Default::default(),
			const_: Default::default(),
			lt: Default::default(),
			lte: Default::default(),
			gt: Default::default(),
			gte: Default::default(),
			in_: Default::default(),
			not_in: Default::default(),
			error_messages: Default::default(),
		}
	}
}

pub(crate) fn float_in_list<T>(target: T, list: &[OrderedFloat<T>], abs_tol: T, r2nd_tol: T) -> bool
where
	T: FloatCore + FloatEq<Tol = T>,
{
	let wrapped_target: OrderedFloat<T> = target.into();

	// 1. Perform Binary Search
	match list.binary_search(&wrapped_target) {
		// Exact bit-for-bit match found
		Ok(_) => true,

		// No exact match. 'idx' is the insertion point.
		Err(idx) => {
			// 2. Check the neighbor immediately AFTER the insertion point
			if let Some(above) = list.get(idx)
				&& float_eq!(above.0, target, abs <= abs_tol, r2nd <= r2nd_tol)
			{
				return true;
			}

			// 3. Check the neighbor immediately BEFORE the insertion point
			if idx > 0
				&& let Some(below) = list.get(idx - 1)
				&& float_eq!(below.0, target, abs <= abs_tol, r2nd <= r2nd_tol)
			{
				return true;
			}

			false
		}
	}
}

pub(crate) fn check_float_list_rules<T>(
	in_list: Option<&[OrderedFloat<T>]>,
	not_in_list: Option<&[OrderedFloat<T>]>,
	abs_tol: T,
	r2nd_tol: T,
) -> Result<(), OverlappingListsError>
where
	T: FloatCore + Debug + FloatEq<Tol = T>,
{
	if let Some(in_list) = in_list
		&& let Some(not_in_list) = not_in_list
	{
		let mut overlapping: Vec<T> = Vec::with_capacity(in_list.len());

		for item in in_list {
			let is_overlapping = float_in_list(item.0, not_in_list, abs_tol, r2nd_tol);

			if is_overlapping {
				overlapping.push(**item);
			}
		}

		if overlapping.is_empty() {
			return Ok(());
		} else {
			return Err(OverlappingListsError {
				overlapping: overlapping
					.into_iter()
					.map(|i| format!("{i:#?}"))
					.collect(),
			});
		}
	}

	Ok(())
}

impl<Num> Validator<Num> for FloatValidator<Num>
where
	Num: FloatWrapper,
{
	type Target = Num;

	impl_testing_methods!();

	#[inline(never)]
	#[cold]
	fn check_consistency(&self) -> Result<(), Vec<ConsistencyError>> {
		let mut errors = Vec::new();

		macro_rules! check_prop_some {
      ($($id:ident),*) => {
        $(self.$id.is_some()) ||*
      };
    }

		if self.const_.is_some()
			&& (!self.cel.is_empty()
				|| self.finite
				|| check_prop_some!(in_, not_in, lt, lte, gt, gte))
		{
			errors.push(ConsistencyError::ConstWithOtherRules);
		}

		if let Some(custom_messages) = self.error_messages.as_deref() {
			let mut unused_messages: Vec<String> = Vec::new();

			for key in custom_messages.keys() {
				macro_rules! check_unused_messages {
          ($($name:ident),*) => {
            paste! {
              $(
                (*key == Num::[< $name:snake:upper _VIOLATION >] && self.$name.is_some())
              ) ||*
            }
          };
        }

				let is_used = check_unused_messages!(gt, gte, lt, lte, not_in)
					|| (*key == Num::REQUIRED_VIOLATION && self.required)
					|| (*key == Num::CONST_VIOLATION && self.const_.is_some())
					|| (*key == Num::IN_VIOLATION && self.in_.is_some())
					|| (*key == Num::FINITE_VIOLATION && self.finite);

				if !is_used {
					unused_messages.push(format!("{key:?}"));
				}
			}

			if !unused_messages.is_empty() {
				errors.push(ConsistencyError::UnusedCustomMessages(unused_messages));
			}
		}

		#[cfg(feature = "cel")]
		if let Err(e) = self.__check_cel_programs() {
			errors.extend(e.into_iter().map(ConsistencyError::from));
		}

		if let Err(e) = check_float_list_rules(
			self.in_.as_deref(),
			self.not_in.as_deref(),
			self.abs_tolerance,
			self.rel_tolerance,
		) {
			errors.push(e.into());
		}

		if let Err(e) = check_comparable_rules(self.lt, self.lte, self.gt, self.gte) {
			errors.push(e);
		}

		if errors.is_empty() {
			Ok(())
		} else {
			Err(errors)
		}
	}

	fn execute_validation(
		&self,
		ctx: &mut ValidationCtx,
		val: Option<&Self::Target>,
	) -> ValidationResult {
		handle_ignore_always!(&self.ignore);
		handle_ignore_if_zero_value!(&self.ignore, val.is_none_or(|v| v.is_default()));

		let mut is_valid = IsValid::Yes;

		macro_rules! handle_violation {
			($id:ident, $default:expr) => {
				paste::paste! {
				  is_valid &= ctx.add_violation(
					Num::[< $id:snake:upper _VIOLATION >].into(),
					self.custom_error_or_else(
					  Num::[< $id:snake:upper _VIOLATION >],
					  || $default
					)
				  )?;
				}
			};
		}

		if self.required && val.is_none_or(|v| v.is_default()) {
			handle_violation!(Required, "is required".to_string());
			return Ok(is_valid);
		}

		if let Some(&val) = val {
			if let Some(const_val) = self.const_ {
				if !self.float_is_eq(const_val, val) {
					handle_violation!(Const, format!("must be equal to {const_val}"));
				}

				// Using `const` implies no other rules
				return Ok(is_valid);
			}

			if self.finite && !val.is_finite() {
				handle_violation!(Finite, "must be a finite number".to_string());
			}

			if let Some(gt) = self.gt
				&& (val.is_nan() || self.float_is_eq(gt, val) || val < gt)
			{
				handle_violation!(Gt, format!("must be greater than {gt}"));
			}

			if let Some(gte) = self.gte
				&& (val.is_nan() || !self.float_is_eq(gte, val) && val < gte)
			{
				handle_violation!(Gte, format!("must be greater than or equal to {gte}"));
			}

			if let Some(lt) = self.lt
				&& (val.is_nan() || self.float_is_eq(lt, val) || val > lt)
			{
				handle_violation!(Lt, format!("must be smaller than {lt}"));
			}

			if let Some(lte) = self.lte
				&& (val.is_nan() || !self.float_is_eq(lte, val) && val > lte)
			{
				handle_violation!(Lte, format!("must be smaller than or equal to {lte}"));
			}

			if let Some(allowed_list) = &self.in_
				&& !float_in_list(val, allowed_list, self.abs_tolerance, self.rel_tolerance)
			{
				handle_violation!(
					In,
					format!(
						"must be one of these values: {}",
						OrderedFloat::<Num>::__format_list(allowed_list)
					)
				);
			}

			if let Some(forbidden_list) = &self.not_in
				&& float_in_list(val, forbidden_list, self.abs_tolerance, self.rel_tolerance)
			{
				handle_violation!(
					NotIn,
					format!(
						"cannot be one of these values: {}",
						OrderedFloat::<Num>::__format_list(forbidden_list)
					)
				);
			}

			#[cfg(feature = "cel")]
			if !self.cel.is_empty() {
				let cel_ctx = ProgramsExecutionCtx {
					programs: &self.cel,
					value: val,
					ctx,
				};

				is_valid &= cel_ctx.execute_programs()?;
			}
		}

		Ok(is_valid)
	}

	#[inline(never)]
	#[cold]
	fn schema(&self) -> Option<ValidatorSchema> {
		Some(ValidatorSchema {
			schema: self.clone().into(),
			cel_rules: self.__cel_rules(),
			imports: vec!["buf/validate/validate.proto".into()],
		})
	}
}

impl<Num> FloatValidator<Num>
where
	Num: FloatWrapper,
{
	#[must_use]
	#[inline]
	pub fn builder() -> FloatValidatorBuilder<Num> {
		FloatValidatorBuilder::default()
	}

	#[inline]
	fn float_is_eq(&self, first: Num, second: Num) -> bool {
		float_eq!(
			first,
			second,
			abs <= self.abs_tolerance,
			r2nd <= self.rel_tolerance
		)
	}
}

impl<N> From<FloatValidator<N>> for ProtoOption
where
	N: FloatWrapper,
{
	#[inline(never)]
	#[cold]
	fn from(validator: FloatValidator<N>) -> Self {
		let mut rules = OptionMessageBuilder::new();

		macro_rules! set_options {
      ($($name:ident),*) => {
        rules
        $(
          .maybe_set(stringify!($name), validator.$name)
        )*
      };
    }

		set_options!(lt, lte, gt, gte);

		rules
			.maybe_set("const", validator.const_)
			.set_boolean("finite", validator.finite)
			.maybe_set(
				"in",
				validator
					.in_
					.map(|list| OptionValue::List(list.items.iter().map(|of| of.0).collect())),
			)
			.maybe_set(
				"not_in",
				validator
					.not_in
					.map(|list| OptionValue::List(list.items.iter().map(|of| of.0).collect())),
			);

		let mut outer_rules = OptionMessageBuilder::new();

		if !rules.is_empty() {
			outer_rules.set(N::type_name(), OptionValue::Message(rules.into()));
		}

		outer_rules
			.add_cel_options(validator.cel)
			.set_required(validator.required)
			.set_ignore(validator.ignore);

		Self {
			name: "(buf.validate.field)".into(),
			value: OptionValue::Message(outer_rules.into()),
		}
	}
}

impl_proto_type!(f32, Float);
impl_proto_type!(f64, Double);

/// A sealed trait for protobuf-compatible floats
pub trait FloatWrapper:
	AsProtoType
	+ Default
	+ Copy
	+ PartialOrd
	+ PartialEq
	+ Into<OptionValue>
	+ Debug
	+ Display
	+ IntoCel
	+ ordered_float::FloatCore
	+ ordered_float::PrimitiveFloat
	+ float_eq::FloatEq<Tol = Self>
	+ Send
	+ Sync
{
	#[doc(hidden)]
	type ViolationEnum: Copy + Ord + Into<ViolationKind> + Debug + Send + Sync + MaybeSerde;
	#[doc(hidden)]
	const LT_VIOLATION: Self::ViolationEnum;
	#[doc(hidden)]
	const LTE_VIOLATION: Self::ViolationEnum;
	#[doc(hidden)]
	const GT_VIOLATION: Self::ViolationEnum;
	#[doc(hidden)]
	const GTE_VIOLATION: Self::ViolationEnum;
	#[doc(hidden)]
	const IN_VIOLATION: Self::ViolationEnum;
	#[doc(hidden)]
	const NOT_IN_VIOLATION: Self::ViolationEnum;
	#[doc(hidden)]
	const CONST_VIOLATION: Self::ViolationEnum;
	#[doc(hidden)]
	const FINITE_VIOLATION: Self::ViolationEnum;
	#[doc(hidden)]
	const REQUIRED_VIOLATION: Self::ViolationEnum;
	#[doc(hidden)]
	#[allow(private_interfaces)]
	const SEALED: Sealed;

	#[doc(hidden)]
	fn type_name() -> &'static str;
}

macro_rules! impl_float_wrapper {
  ($target_type:ty, $proto_type:ident) => {
    paste::paste! {
      impl FloatWrapper for $target_type {
        #[doc(hidden)]
        type ViolationEnum = [< $proto_type Violation >];
				#[doc(hidden)]
        const LT_VIOLATION: Self::ViolationEnum = [< $proto_type Violation >]::Lt;
        #[doc(hidden)]
        const LTE_VIOLATION: Self::ViolationEnum = [< $proto_type Violation >]::Lte;
        #[doc(hidden)]
        const GT_VIOLATION: Self::ViolationEnum = [< $proto_type Violation >]::Gt;
        #[doc(hidden)]
        const GTE_VIOLATION: Self::ViolationEnum = [< $proto_type Violation >]::Gte;
        #[doc(hidden)]
        const CONST_VIOLATION: Self::ViolationEnum = [< $proto_type Violation >]::Const;
        #[doc(hidden)]
        const FINITE_VIOLATION: Self::ViolationEnum = [< $proto_type Violation >]::Finite;
        #[doc(hidden)]
        const IN_VIOLATION: Self::ViolationEnum = [< $proto_type Violation >]::In;
        #[doc(hidden)]
        const NOT_IN_VIOLATION: Self::ViolationEnum = [< $proto_type Violation >]::NotIn;
        #[doc(hidden)]
        const REQUIRED_VIOLATION: Self::ViolationEnum = [< $proto_type Violation >]::Required;
        #[doc(hidden)]
        #[allow(private_interfaces)]
        const SEALED: Sealed = Sealed;

        #[doc(hidden)]
				#[inline]
        fn type_name() -> &'static str {
          stringify!([< $proto_type:lower >])
        }
      }

      impl ProtoValidation for $target_type {
        #[doc(hidden)]
        type Target = Self;
        #[doc(hidden)]
        type Stored = Self;
        type Validator = FloatValidator<Self>;
        type ValidatorBuilder = FloatValidatorBuilder<Self>;

        #[doc(hidden)]
        type UniqueStore<'a>
          = FloatEpsilonStore<Self>
        where
          Self: 'a;

        #[doc(hidden)]
        #[inline]
        fn __make_unique_store<'a>(
          validator: &Self::Validator,
          size: usize,
        ) -> Self::UniqueStore<'a>
        {
          FloatEpsilonStore::new(size, validator.abs_tolerance, validator.rel_tolerance)
        }
      }

      impl<S: builder::state::State> ValidatorBuilderFor<$target_type> for FloatValidatorBuilder<$target_type, S> {
        type Validator = FloatValidator<$target_type>;

        #[inline]
        fn build_validator(self) -> Self::Validator {
          self.build()
        }
      }
    }
  };
}

impl_float_wrapper!(f32, Float);
impl_float_wrapper!(f64, Double);