unlab-gpu 0.1.0

Micro scripting language for neural networks that uses unmtx-gpu.
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
//
// Copyright (c) 2025-2026 Ɓukasz Szpakowski
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//
//! A version module.
use std::cmp::Ordering;
use std::cmp::max;
use std::fmt;
use std::result;
use crate::serde::de;
use crate::serde::de::Visitor;
use crate::serde::Deserialize;
use crate::serde::Deserializer;
use crate::serde::Serialize;
use crate::serde::Serializer;
use crate::error::*;

/// A pre-release identifier.
#[derive(Clone, Debug)]
pub enum PreReleaseIdent
{
    /// A numeric identfier.
    Numeric(u32),
    /// An alphanumeric identifier.
    Alphanumeric(String),
}

impl Eq for PreReleaseIdent
{}

impl PartialEq for PreReleaseIdent
{
    fn eq(&self, other: &Self) -> bool
    { self.cmp(other) == Ordering::Equal }
}

impl Ord for PreReleaseIdent
{
    fn cmp(&self, other: &Self) -> Ordering 
    {
        match (self, other) {
            (PreReleaseIdent::Numeric(n), PreReleaseIdent::Numeric(m)) => n.cmp(&m),
            (PreReleaseIdent::Alphanumeric(_), PreReleaseIdent::Numeric(_)) => Ordering::Greater,
            (PreReleaseIdent::Numeric(_), PreReleaseIdent::Alphanumeric(_)) => Ordering::Less,
            (PreReleaseIdent::Alphanumeric(s), PreReleaseIdent::Alphanumeric(t)) => s.cmp(&t),
        }
    }
}

impl PartialOrd for PreReleaseIdent
{
    fn partial_cmp(&self, other: &Self) -> Option<Ordering>
    { Some(self.cmp(other)) }
}

impl fmt::Display for PreReleaseIdent
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
    {
        match self {
            PreReleaseIdent::Numeric(n) => write!(f, "{}", n),
            PreReleaseIdent::Alphanumeric(s) => write!(f, "{}", s),
        }
    }
}

/// A version structure.
///
/// The version structure has version field and fields compatible with
/// [SemVer](https://semver.org). 
#[derive(Clone, Debug)]
pub struct Version
{
    version: String,
    numeric_idents: Vec<u32>,
    pre_release_idents: Option<Vec<PreReleaseIdent>>,
    build_idents: Option<Vec<String>>,
}

impl Version
{
    /// Creates a version.
    pub fn new(version: String, numeric_idents: Vec<u32>, pre_release_idents: Option<Vec<PreReleaseIdent>>, build_idents: Option<Vec<String>>) -> Self
    { Version { version, numeric_idents, pre_release_idents, build_idents, } }
    
    /// Parses the string slice to a version.
    pub fn parse(s: &str) -> Result<Self>
    {
        let (pair_s, build) = match s.split_once('+') {
            Some(pair) => pair,
            None => (s, ""),
        };
        let (version_core, pre_release) = match pair_s.split_once('-') {
            Some(pair) => pair,
            None => (pair_s, ""),
        };
        let mut numeric_idents: Vec<u32> = Vec::new();
        for t in version_core.split('.') {
            match t.parse::<u32>() {
                Ok(n) => numeric_idents.push(n),
                Err(_) => return Err(Error::InvalidVersion),
            }
        }
        let pre_release_idents = if !pre_release.is_empty() {
            let mut tmp_pre_release_idents: Vec<PreReleaseIdent> = Vec::new();
            for t in pre_release.split('.') {
                match t.parse::<u32>() {
                    Ok(n) => tmp_pre_release_idents.push(PreReleaseIdent::Numeric(n)),
                    Err(_) => {
                        if t.is_empty() || t.contains('/') || t.contains('\\') {
                            return Err(Error::InvalidVersion);
                        }
                        tmp_pre_release_idents.push(PreReleaseIdent::Alphanumeric(String::from(t)))
                    },
                }
            }
            Some(tmp_pre_release_idents)
        } else {
            None
        };
        let build_idents = if !build.is_empty() {
            let mut tmp_build_idents: Vec<String> = Vec::new();
            for t in build.split('.') {
                if t.is_empty() || t.contains('/') || t.contains('\\') {
                    return Err(Error::InvalidVersion);
                }
                tmp_build_idents.push(String::from(t));
            }
            Some(tmp_build_idents)
        } else {
            None
        };
        Ok(Self::new(String::from(s), numeric_idents, pre_release_idents, build_idents))
    }
    
    /// Returns the version as the string slice.
    pub fn version(&self) -> &str
    { self.version.as_str() }
    
    /// Returns the numeric identifiers.
    pub fn numeric_idents(&self) -> &[u32]
    { self.numeric_idents.as_slice() }

    /// Retursn the pre-release identifiers.
    pub fn pre_release_idents(&self) -> Option<&[PreReleaseIdent]>
    {
        match &self.pre_release_idents {
            Some(pre_release_idents) => Some(pre_release_idents.as_slice()),
            None => None,
        }
    }

    /// Returns the build indentifiers.
    pub fn build_idents(&self) -> Option<&[String]>
    {
        match &self.build_idents {
            Some(build_idents) => Some(build_idents.as_slice()),
            None => None,
        }
    }

    /// Returns `true` if the numeric identifiers of versions are equal for the specified number
    /// of numeric identifiers, otherwise `false`.
    pub fn eq_numeric_idents(&self, version: &Version, count: usize) -> bool
    {
        for i in 0..count {
            let n = if i < self.numeric_idents.len() {
                self.numeric_idents[i]
            } else {
                0
            };
            let m = if i < version.numeric_idents.len() {
                version.numeric_idents[i]
            } else {
                0
            };
            if n != m {
                return false;
            }
        }
        true
    }
}

impl Eq for Version
{}

impl PartialEq for Version
{
    fn eq(&self, other: &Self) -> bool
    { self.cmp(other) == Ordering::Equal }
}

impl Ord for Version
{
    fn cmp(&self, other: &Self) -> Ordering 
    {
        let len = max(self.numeric_idents.len(), other.numeric_idents.len());
        for i in 0..len {
            let n = if i < self.numeric_idents.len() {
                self.numeric_idents[i]
            } else {
                0
            };
            let m = if i < other.numeric_idents.len() {
                other.numeric_idents[i]
            } else {
                0
            };
            match n.cmp(&m) {
                Ordering::Equal => (),
                ordering => return ordering,
            }
        }
        match (&self.pre_release_idents, &other.pre_release_idents) {
            (Some(pre_release_idents), Some(pre_release_idents2)) => pre_release_idents.cmp(&pre_release_idents2),
            (Some(_), None) => Ordering::Less,
            (None, Some(_)) => Ordering::Greater,
            (None, None) => Ordering::Equal,
        }
    }
}

impl PartialOrd for Version
{
    fn partial_cmp(&self, other: &Self) -> Option<Ordering>
    { Some(self.cmp(other)) }
}

impl fmt::Display for Version
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
    { write!(f, "{}", self.version) }
}

impl Serialize for Version
{
    fn serialize<S>(&self, serializer: S) -> result::Result<S::Ok, S::Error>
        where S: Serializer
    { serializer.serialize_str(format!("{}", self).as_str()) }
}

struct VersionVisitor;

impl<'de> Visitor<'de> for VersionVisitor
{
    type Value = Version;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result
    { write!(formatter, "a version") }

    fn visit_str<E>(self, v: &str) -> result::Result<Self::Value, E>
        where E: de::Error
    {
        match Version::parse(v) {
            Ok(version) => Ok(version),
            Err(err) => Err(E::custom(format!("{}", err))),
        }
    }
}

impl<'de> Deserialize<'de> for Version
{
    fn deserialize<D>(deserializer: D) -> result::Result<Self, D::Error>
        where D: Deserializer<'de>
    { deserializer.deserialize_str(VersionVisitor) }
}

/// An enumeration of version  operator.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub enum VersionOp
{
    /// Eqaul.
    Eq,
    /// Not equal.
    Ne,
    /// Less than.
    Lt,
    /// Greater than or equal to.
    Ge,
    /// Greater than.
    Gt,
    /// Less than or equal to.
    Le,
    /// A default operator.
    Default,
    /// A tylde operator.
    Tilde,
}

impl fmt::Display for VersionOp
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
    {
        match self {
            VersionOp::Eq => write!(f, "="),
            VersionOp::Ne => write!(f, "!="),
            VersionOp::Lt => write!(f, "<"),
            VersionOp::Ge => write!(f, ">="),
            VersionOp::Gt => write!(f, ">"),
            VersionOp::Le => write!(f, "<="),
            VersionOp::Default => write!(f, "^"),
            VersionOp::Tilde => write!(f, "~"),
        }
    }
}

/// An enumeration of single version requirement.
///
/// The single version requirement can have one version with a version operator or can be a
/// wildcard. A version requirement uses many single version requirements which can be matched to
/// a version while matching.
#[derive(Clone, Debug)]
pub enum SingleVersionReq
{
    /// A wildcard.
    Wildcard,
    /// A pair of version operator and version.
    Pair(VersionOp, Version),
}

impl SingleVersionReq
{
    /// Parsers the string slice to a single version requirement.
    pub fn parse(s: &str) -> Result<Self>
    {
        let trimmed_s = s.trim();
        if trimmed_s != "*" {
            let (op, t) = if trimmed_s.starts_with("=") {
                (VersionOp::Eq, &trimmed_s[1..])
            } else if trimmed_s.starts_with("!=") {
                (VersionOp::Ne, &trimmed_s[2..])
            } else if trimmed_s.starts_with("<=") {
                (VersionOp::Le, &trimmed_s[2..])
            } else if trimmed_s.starts_with("<") {
                (VersionOp::Lt, &trimmed_s[1..])
            } else if trimmed_s.starts_with(">=") {
                (VersionOp::Ge, &trimmed_s[2..])
            } else if trimmed_s.starts_with(">") {
                (VersionOp::Gt, &trimmed_s[1..])
            } else if trimmed_s.starts_with("^") {
                (VersionOp::Default, &trimmed_s[1..])
            } else if trimmed_s.starts_with("~") {
                (VersionOp::Tilde, &trimmed_s[1..])
            } else {
                (VersionOp::Default, trimmed_s)
            };
            let trimmed_t = t.trim();
            let version = Version::parse(trimmed_t)?;
            Ok(SingleVersionReq::Pair(op, version))
        } else {
            Ok(SingleVersionReq::Wildcard)
        }
    }
    
    /// Matches the single version requirement to the version.
    ///
    /// This method returns `true` if the single version requirement is matched to the version,
    /// otherwise `false`.
    pub fn matches(&self, version: &Version) -> bool
    {
        match self {
            SingleVersionReq::Wildcard => true,
            SingleVersionReq::Pair(op, version2) => {
                match op {
                    VersionOp::Eq => version == version2,
                    VersionOp::Ne => version != version2,
                    VersionOp::Lt => version < version2,
                    VersionOp::Ge => version >= version2,
                    VersionOp::Gt => version > version2,
                    VersionOp::Le => version <= version2,
                    VersionOp::Default => {
                        let mut count = 0usize;
                        if !version2.numeric_idents.is_empty() {
                            count += 1;
                            for i in 0..version2.numeric_idents.len() {
                                match version2.numeric_idents.get(i) {
                                    Some(0) if version2.numeric_idents.len() >= i + 2 => count += 1,
                                    _ => break,
                                }
                            }
                        }
                        version >= version2 && version.eq_numeric_idents(version2, count)
                    },
                    VersionOp::Tilde => {
                        let count = if !version2.numeric_idents.is_empty() {
                            if version2.numeric_idents.len() >= 2 {
                                2
                            } else {
                                1
                            }
                        } else {
                            0
                        };
                        version >= version2 && version.eq_numeric_idents(version2, count)
                    },
                }
            },
        }
    }
}

impl fmt::Display for SingleVersionReq
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
    {
        match self {
            SingleVersionReq::Wildcard => write!(f, "*"),
            SingleVersionReq::Pair(op, version) => write!(f, "{}{}", op, version),
        }
    }
}

/// A structure of version requirement.
///
/// The version requirement can be matched to the version and can contain many single version
/// requirements which can be matched to version while matching. The version requirements are used
/// to check versions by a package manager and a `reqver` built-in function.
#[derive(Clone, Debug)]
pub struct VersionReq
{
    single_reqs: Vec<SingleVersionReq>,
}

impl VersionReq
{
    /// Creates a version requirement.
    pub fn new(single_reqs: Vec<SingleVersionReq>) -> Self
    { VersionReq { single_reqs, } }
    
    /// Parsers the string slice to a version requirement.
    pub fn parse(s: &str) -> Result<Self>
    {
        let mut single_reqs: Vec<SingleVersionReq> = Vec::new();
        for t in s.split(',') {
            single_reqs.push(SingleVersionReq::parse(t)?);
        }
        Ok(VersionReq::new(single_reqs))
    }
    
    /// Returns the single version requirements.
    pub fn single_reqs(&self) -> &[SingleVersionReq]
    { self.single_reqs.as_slice() }

    /// Matches the version requirement to the version.
    ///
    /// This method returns `true` if the version requirement is matched to the version, otherwise
    /// `false`.
    pub fn matches(&self, version: &Version) -> bool
    { self.single_reqs.iter().all(|sr| sr.matches(version)) }
}

impl fmt::Display for VersionReq
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
    {
        let mut is_first = true;
        for single_req in &self.single_reqs {
            if !is_first {
                write!(f, ",")?;
            }
            write!(f, "{}", single_req)?;
            is_first = false;
        }
        Ok(())
    }
}

impl Serialize for VersionReq
{
    fn serialize<S>(&self, serializer: S) -> result::Result<S::Ok, S::Error>
        where S: Serializer
    { serializer.serialize_str(format!("{}", self).as_str()) }
}

struct VersionReqVisitor;

impl<'de> Visitor<'de> for VersionReqVisitor
{
    type Value = VersionReq;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result
    { write!(formatter, "a version requirement") }

    fn visit_str<E>(self, v: &str) -> result::Result<Self::Value, E>
        where E: de::Error
    {
        match VersionReq::parse(v) {
            Ok(req) => Ok(req),
            Err(err) => Err(E::custom(format!("{}", err))),
        }
    }
}

impl<'de> Deserialize<'de> for VersionReq
{
    fn deserialize<D>(deserializer: D) -> result::Result<Self, D::Error>
        where D: Deserializer<'de>
    { deserializer.deserialize_str(VersionReqVisitor) }
}

#[cfg(test)]
mod tests;