1+ const CH_COLON = ':' . charCodeAt ( 0 )
2+ const CH_0 = '0' . charCodeAt ( 0 )
3+ const CH_9 = '9' . charCodeAt ( 0 )
4+
5+ module . exports = class {
6+
7+ raise ( s , o ) {
8+
9+ const err = Error ( s )
10+
11+ for ( const k in o ) err [ k ] = o [ k ]
12+
13+ throw err
14+
15+ }
16+
17+ verify ( str ) {
18+
19+ const type = typeof str ; if ( type !== 'string' ) this . raise ( `CadNum must be of type string` , { str, type} )
20+
21+ const { length} = str ; if ( length < 14 ) this . raise ( `CadNum must be at least 14 charaters long` , { str, length} )
22+
23+ const lastColonIndex = str . lastIndexOf ( ':' )
24+
25+ switch ( lastColonIndex ) {
26+
27+ case - 1 :
28+ this . raise ( `Invalid CadNum "${ str } ": colon not found` , { str, lastColonIndex} )
29+
30+ case 12 :
31+ case 13 :
32+ break
33+
34+ default :
35+ this . raise ( `Invalid CadNum "${ str } ": the last colon found at position ${ lastColonIndex } ` , { str, lastColonIndex} )
36+
37+ }
38+
39+ for ( let index = 0 ; index < length ; index ++ ) if ( index !== lastColonIndex ) {
40+
41+ const c = str . charCodeAt ( index )
42+
43+ switch ( index ) {
44+
45+ case 2 :
46+ case 5 :
47+ if ( c !== CH_COLON ) this . raise ( `Invalid CadNum "${ str } ": not a colon at position ${ index } ` , { str, index} )
48+ break
49+
50+ default :
51+ if ( c < CH_0 || c > CH_9 ) this . raise ( `Invalid CadNum "${ str } ": not a digit at position ${ index } ` , { str, index} )
52+
53+ }
54+
55+ }
56+
57+ }
58+
59+ random ( options = { } ) {
60+
61+ let { pre, length} = options
62+
63+ if ( ! pre ) pre = ''
64+
65+ if ( pre . length === 12 || pre . length === 13 ) if ( pre . charCodeAt ( pre . length - 1 ) !== CH_COLON ) pre += ':'
66+
67+ if ( ! length ) length = 14 + Math . floor ( 5 * Math . random ( ) )
68+
69+ if ( length <= pre . length ) length = pre . length + 1
70+
71+ const b = Buffer . alloc ( length )
72+
73+ for ( let i = 0 ; i < pre . length ; i ++ ) b [ i ] = pre . charCodeAt ( i )
74+
75+ for ( let i = pre . length ; i < length ; i ++ ) b [ i ] = 48 + Math . floor ( 10 * Math . random ( ) )
76+
77+ b [ 2 ] = CH_COLON
78+ b [ 5 ] = CH_COLON
79+
80+ if ( b . lastIndexOf ( CH_COLON ) < 12 ) {
81+
82+ let lastColonIndex = 12
83+
84+ if ( length > 14 && Math . random ( ) > 0.5 ) lastColonIndex ++
85+
86+ b [ lastColonIndex ] = CH_COLON
87+
88+ }
89+
90+ return b . toString ( )
91+
92+ }
93+
94+ }
0 commit comments