salps 1.0.0

random string generation
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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
//! random string generation.
//! 
//! `salps` provides a minimal api for creating silly randomly
//! generated strings of not particularly high quality.
//! 
//! ## usage
//! 
//! ```
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! # extern crate std;
//! # use std::prelude::rust_2024::*;
//! # struct Rng;
//! # impl Rng { fn new() -> Self { Self } }
//! # impl salps::Random for Rng {
//! # fn random(&mut self) -> f64 { 0.0 } }
//! use core::fmt::Write;
//! 
//! // first bring a type that implements `core::fmt::Write`
//! let mut string = String::new();
//! 
//! // then bring an rng generator (you will probably have
//! // to implement this crate's `Random` trait yourself)
//! let mut rng = Rng::new();
//! 
//! // and finally, create a configuration, or use the default:
//! let config = salps::Config::new();
//! 
//! // now generate a word!
//! salps::word(&mut string, &mut rng, &config)?;
//! # Ok(())
//! # }
//! ```

#![no_std]

/// trait for providing random numbers.
/// 
/// this crate does not provide a random number generator, instead
/// relying on you to bring your own. your rng must then implement `Random`.
/// this can be quite unfortunate if you want to use an rng from an
/// external crate, such as `rand`, as the orphan rule would prevent directly
/// implementing this trait onto such external types.
/// 
/// here is an example using the rand crate and the newtype pattern:
/// 
/// ```ignore
/// use rand::prelude::*;
/// 
/// struct Wrapper(rand::rngs::ThreadRng);
/// 
/// impl salps::Random for Wrapper {
///     fn random(&mut self) -> f64 {
///         self.0.random::<f64>()
///     }
/// }
/// 
/// let mut rng = Wrapper(rand::rng());
/// ```
/// 
/// note that this type is also blanket implemented for all `&mut T` where `T: Random`.
pub trait Random {
	/// returns a random, uniform, normalized f64.
	/// this number should be in range `0.0 .. 1.0` (exclusive). for the
	/// purposes of this crate, values outside this range will be truncated.
	/// 
	/// see [`Random`].
	fn random(&mut self) -> f64;
}

impl<T: Random> Random for &mut T {
	fn random(&mut self) -> f64 {
		(*self).random()
	}
}

// implementation details
mod private {
	#[derive(Debug, Clone)]
	pub enum ConfigRange {
		None,
		Exact(u32),
		Range(u32, u32),
	}

	impl ConfigRange {
		pub fn calc(&self, rng: &mut impl super::Random, default_min: u32, default_max: u32) -> u32 {
			let (x, y) = match self {
				ConfigRange::None => (default_min, default_max),
				ConfigRange::Exact(x) => (*x, *x),
				ConfigRange::Range(x, y) => (*x, *y),
			};

			let y = y.max(x);

			let x = x as f64;
			let y = y as f64;

			let norm = rng.random().clamp(0.0, 1.0f64.next_down());

			(norm * (y - x) + x) as u32
		}
	}
		
	pub trait IntoConfigRange {
		fn range(self) -> ConfigRange;
	}

	impl IntoConfigRange for () {
		fn range(self) -> ConfigRange {
			ConfigRange::None
		}
	}

	impl IntoConfigRange for u32 {
		fn range(self) -> ConfigRange {
			ConfigRange::Exact(self)
		}
	}
	
	impl IntoConfigRange for core::ops::Range<u32> {
		fn range(self) -> ConfigRange {
			ConfigRange::Range(self.start, self.end.saturating_sub(1))
		}
	}

	impl IntoConfigRange for core::ops::RangeInclusive<u32> {
		fn range(self) -> ConfigRange {
			ConfigRange::Range(*self.start(), *self.end())
		}
	}
}

/// default configuration used in [`Config`].
pub const DEFAULT_END: &[(f64, &str)] = &[
	(0.05, "!"),
	(0.02, "!!"),
	(0.07, "?"),
	(0.11, " :3"),
	(0.02, "..."),
];

/// default configuration used in [`Config`].
/// 
/// this is simply a period (`"."`).
pub const DEFAULT_END_FALLBACK: &str = ".";

/// default configuration used in [`Config`].
/// 
/// defines an 8% chance of a comma (`", "`) appearing.
pub const DEFAULT_MID: &[(f64, &str)] = &[
	(0.08, ", "),
];

/// default configuration used in [`Config`].
/// 
/// this is simply a space (`" "`).
pub const DEFAULT_MID_FALLBACK: &str = " ";

/// configuration for this crate.
/// 
/// first, you can configure how large any element can be using [`Config::word()`],
/// [`Config::sentence()`], and [`Config::paragraph()`].
/// 
/// ```
/// // set all word lengths to a range between 20 and 40 characters:
/// let config = salps::Config::new().word(20..40);
/// 
/// // set paragraphs to generate exactly 5 sentences:
/// let config = salps::Config::new().paragraph(5);
/// ```
/// 
/// second, you can configure what kind of punctuation can appear during a sentence
/// using [`Config::end()`] and [`Config::mid()`].
/// 
/// ```
/// // end all sentences with ":3"
/// let config = salps::Config::new()
///     .end(&[
///         (1.0, " :3"),
///     ]);
/// 
/// // 5% chance of a sentence ending with ":3", 5% chance with "!", with the rest ending in "."
/// let config = salps::Config::new()
///     .end(&[
///         (0.05, " :3"),
///         (0.05, "!"),
///     ])
///     .end_fallback(".");
/// 
/// // every word in a sentence has a 4% chance of having a comma after it
/// let config = salps::Config::new()
///     .mid(&[
///         (0.04, ", "),
///     ]);
/// ```
#[derive(Debug, Clone)]
pub struct Config<'a> {
	paragraph_range: private::ConfigRange,
	sentence_range: private::ConfigRange,
	word_range: private::ConfigRange,
	mid: (&'a str, &'a [(f64, &'a str)]),
	end: (&'a str, &'a [(f64, &'a str)]),
}

impl<'a> Config<'a> {
	/// creates a new [`Config`], default config. use the other inherent
	/// methods to make additional configurations.
	/// 
	/// ## examples
	/// 
	/// ```
	/// let config = salps::Config::new();
	/// ```
	pub fn new() -> Self {
		Self {
			paragraph_range: private::ConfigRange::None,
			sentence_range: private::ConfigRange::None,
			word_range: private::ConfigRange::None,
			mid: (
				DEFAULT_MID_FALLBACK,
				DEFAULT_MID,
			),
			end: (
				DEFAULT_END_FALLBACK,
				DEFAULT_END,
			),
		}
	}

	/// set word lengths.
	/// 
	/// ## examples
	/// 
	/// ```
	/// // exactly 5
	/// let config = salps::Config::new().word(5);
	/// 
	/// // between 5 and 8 (exclusive)
	/// let config = salps::Config::new().word(5..8);
	/// 
	/// // between 5 and 8 (inclusive)
	/// let config = salps::Config::new().word(5..=8);
	/// 
	/// // set to default
	/// let config = salps::Config::new().word(());
	/// ```
	pub fn word(mut self, range: impl private::IntoConfigRange) -> Self {
		self.word_range = range.range();
		self
	}

	/// set sentence lengths.
	/// 
	/// ## examples
	/// 
	/// ```
	/// // exactly 5
	/// let config = salps::Config::new().sentence(5);
	/// 
	/// // between 5 and 8 (exclusive)
	/// let config = salps::Config::new().sentence(5..8);
	/// 
	/// // between 5 and 8 (inclusive)
	/// let config = salps::Config::new().sentence(5..=8);
	/// 
	/// // set to default
	/// let config = salps::Config::new().sentence(());
	/// ```
	pub fn sentence(mut self, range: impl private::IntoConfigRange) -> Self {
		self.sentence_range = range.range();
		self
	}

	/// set paragraph lengths.
	/// 
	/// ## examples
	/// 
	/// ```
	/// // exactly 5
	/// let config = salps::Config::new().paragraph(5);
	/// 
	/// // between 5 and 8 (exclusive)
	/// let config = salps::Config::new().paragraph(5..8);
	/// 
	/// // between 5 and 8 (inclusive)
	/// let config = salps::Config::new().paragraph(5..=8);
	/// 
	/// // set to default
	/// let config = salps::Config::new().paragraph(());
	/// ```
	pub fn paragraph(mut self, range: impl private::IntoConfigRange) -> Self {
		self.paragraph_range = range.range();
		self
	}

	/// set a list of possible punctuation to be used at the end of a sentence.
	/// 
	/// for every entry of `values`, the first value of a tuple represents the overall
	/// percentage chance that the second value will be used.
	/// 
	/// an implication here is that logically, `values.iter().map(|x| x.0).reduce(|a, x| a + x)`
	/// should be equal to `1.0`. in actuality, it should be within `0.0 ..= 1.0`, with the
	/// value of [`Config::end_fallback()`] providing a fallback. otherwise, failing to meet
	/// this range may cause odd behaviour.
	/// 
	/// this is [`DEFAULT_END`] by default.
	/// 
	/// ## examples
	/// 
	/// ```
	/// let config = salps::Config::new().end(&[
	///     (0.2, "."), // 20% chance of "."
	///     (0.3, "!"), // 30% chance of "!"
	///     // implicit 50% chance of using the fallback value.
	/// ]);
	/// ```
	pub const fn end(mut self, values: &'a [(f64, &'a str)]) -> Self {
		self.end.1 = values;
		self
	}

	/// provides a 'fallback' value in case the chances provided in
	/// [`Config::end()`] don't add up to `1.0`.
	/// 
	/// this is [`DEFAULT_END_FALLBACK`] by default.
	/// 
	/// ## examples
	/// 
	/// ```
	/// let config = salps::Config::new().end_fallback("!");
	/// ```
	pub fn end_fallback(mut self, value: &'a str) -> Self {
		self.end.0 = value;
		self
	}

	/// set a list of possible punctuation to be used in the middle of a sentence.
	/// 
	/// for every entry of `values`, the first value of a tuple represents the overall
	/// percentage chance that the second value will be used.
	/// 
	/// an implication here is that logically, `values.iter().map(|x| x.0).reduce(|a, x| a + x)`
	/// should be equal to `1.0`. in actuality, it should be within `0.0 ..= 1.0`, with the
	/// value of [`Config::mid_fallback()`] providing a fallback. otherwise, failing to meet
	/// this range may cause odd behaviour.
	/// 
	/// this is [`DEFAULT_MID`] by default.
	/// 
	/// ## examples
	/// 
	/// ```
	/// let config = salps::Config::new().mid(&[
	///     (0.2, "."), // 20% chance of "."
	///     (0.3, "!"), // 30% chance of "!"
	///     // implicit 50% chance of using the fallback value.
	/// ]);
	/// ```
	pub fn mid(mut self, values: &'a [(f64, &'a str)]) -> Self {
		self.mid.1 = values;
		self
	}

	/// provides a 'fallback' value in case the chances provided in
	/// [`Config::mid()`] don't add up to `1.0`.
	/// 
	/// this is [`DEFAULT_MID_FALLBACK`] by default.
	/// 
	/// ## examples
	/// 
	/// ```
	/// let config = salps::Config::new().mid_fallback("!");
	/// ```
	pub fn mid_fallback(mut self, value: &'a str) -> Self {
		self.mid.0 = value;
		self
	}
}

impl Default for Config<'_> {
	fn default() -> Self {
		Self::new()
	}
}

/// generates a word.
pub fn word<W, R>(mut write: W, mut rng: R, config: &Config) -> Result<(), core::fmt::Error>
where W: core::fmt::Write, R: Random {
	const FULL: &[&str] = &[
		"a",
		"b",
		"c",
		"d",
		"e",
		"f",
		"g",
		"h",
		"i",
		"j",
		"k",
		"l",
		"m",
		"n",
		"o",
		"p",
		"q",
		"r",
		"s",
		"t",
		"u",
		"v",
		"w",
		"x",
		"y",
		"z",
	];

	const VOWEL: &[&str] = &[
		"a",
		"e",
		"i",
		"o",
		"u",
	];

	const FILL: &[&str] = &[
		"b",
		"c",
		"d",
		"f",
		"g",
		"h",
		"j",
		"k",
		"l",
		"m",
		"n",
		"p",
		"q",
		"r",
		"s",
		"t",
		"v",
		"w",
		"x",
		"y",
		"z",
	];

	const LAC: &[&str] = &[
		"s",
		"l",
		"w",
	];

	enum Kind {
		None,
		Consonant,
		Vowel,
		Lac,
	}

	#[inline]
	fn go(table: &[&'static str], random: f64) -> &'static str {
		let len = table.len() as f64;
		let index = (random * len).clamp(0.0, len.next_down()) as usize;
		table.get(index).expect("unreachable")
	}

	let len = config.word_range.calc(&mut rng, 2, 12);

	let mut state = Kind::None;

	for _ in 0..len {
		let s = match state {
			Kind::None => {
				state = Kind::Consonant;
				go(FULL, rng.random())
			}
			
			Kind::Consonant => {
				if rng.random() < 0.33 {
					state = Kind::Lac;
					go(LAC, rng.random())
				}
				else {
					state = Kind::Vowel;
					go(VOWEL, rng.random())
				}
			}
			
			Kind::Lac => {
				state = Kind::Vowel;
				go(VOWEL, rng.random())
			}
			
			Kind::Vowel => {
				if rng.random() < 0.25 {
					state = Kind::Vowel;
					go(VOWEL, rng.random())
				}
				else {
					state = Kind::Consonant;
					go(FILL, rng.random())
				}
			}
		};

		write!(write, "{}", s)?;
	}

	Ok(())
}

/// generates words to form a sentence.
pub fn sentence<W, R>(mut write: W, mut rng: R, config: &Config) -> Result<(), core::fmt::Error>
where W: core::fmt::Write, R: Random {
	let len = config.sentence_range.calc(&mut rng, 2, 14);

	for i in 0..len {
		word(&mut write, &mut rng, config)?;

		let (def, list) = if i == len - 1 {
				config.end
			}
			else {
				config.mid
			};

		let mut random = rng.random();

		let mut get = None;

		for (chance, value) in list {
			if random < *chance {
				get = Some(*value);
				break;
			}
			random -= *chance;
		}

		let mark = get.unwrap_or(def);

		write!(write, "{}", mark)?;
	}

	Ok(())
}

/// generates sentences to form a paragraph.
pub fn paragraph<W, R>(mut write: W, mut rng: R, config: &Config) -> Result<(), core::fmt::Error>
where W: core::fmt::Write, R: Random {
	let len = config.paragraph_range.calc(&mut rng, 6, 12);

	for _ in 0..len {
		sentence(&mut write, &mut rng, config)?;
		write!(write, " ")?;
	}

	Ok(())
}

#[cfg(test)]
mod test {
	extern crate std;

	struct Fake(f64);
	impl crate::Random for Fake {
		fn random(&mut self) -> f64 {
			self.0
		}
	}
	
	#[test]
	fn test() {
		let mut string = std::string::String::new();
		crate::word(&mut string, &mut Fake(0.0), &crate::Config::new().word(4)).unwrap();
		assert_eq!(string.len(), 4);

		let mut string = std::string::String::new();
		crate::word(&mut string, &mut Fake(0.0), &crate::Config::new().word(4..6)).unwrap();
		assert_eq!(string.len(), 4);

		let mut string = std::string::String::new();
		crate::word(&mut string, &mut Fake(1.0), &crate::Config::new().word(4..6)).unwrap();
		assert_eq!(string.len(), 5);

		let mut string = std::string::String::new();
		crate::word(&mut string, &mut Fake(1.0), &crate::Config::new().word(4..=6)).unwrap();
		assert_eq!(string.len(), 6);
	}
}