uuid_by_string/
uuid.rs

1#[path="./common.rs"]
2mod common;
3#[path="./for_namespace.rs"]
4mod for_namespace;
5
6const NIL_UUID: &str = "00000000-0000-0000-0000-000000000000";
7
8pub fn generate(target: &str, namespace: Option<&str>) -> Result<String, &'static str> {
9    generate_v5(target, namespace)
10}
11
12fn generate_common(target: &str, namespace: Option<&str>, f: &dyn Fn(Vec<u8>) -> [u8; 16], version: u8) -> Result<String, &'static str> {
13    let target_char_buffer = target.as_bytes();
14    let namespace_char_buffer = for_namespace::parse_uuid(namespace.unwrap_or(NIL_UUID));
15
16    match namespace_char_buffer {
17        Err(x) => return Err(x),
18        _ => (),
19    }
20
21    let namespace_char_buffer = namespace_char_buffer.unwrap();
22    let buffer = [&namespace_char_buffer, target_char_buffer].concat();
23    let result = f(buffer);
24    return Ok(common::hash_to_uuid(result, version));
25}
26
27pub fn generate_v3(target: &str, namespace: Option<&str>) -> Result<String, &'static str> {
28    generate_common(target, namespace, &common::md5_hash, 3)
29}
30
31pub fn generate_v5(target: &str, namespace: Option<&str>) -> Result<String, &'static str> {
32    generate_common(target, namespace, &common::sha1_hash, 5)
33}