2021-09-11 17:03:59 +02:00
/ * *
* @ author Thomas Weißschuh [ thomas @ t - 8 ch . de ]
* @ copyright Crown Copyright 2021
* @ license Apache - 2.0
* /
2021-09-17 08:32:08 +02:00
import { ALPHABET , highlightToBase45 , highlightFromBase45 } from "../lib/Base45.mjs" ;
2021-09-11 17:03:59 +02:00
import Operation from "../Operation.mjs" ;
import OperationError from "../errors/OperationError.mjs" ;
import Utils from "../Utils.mjs" ;
/ * *
* From Base45 operation
* /
class FromBase45 extends Operation {
/ * *
* FromBase45 constructor
* /
constructor ( ) {
super ( ) ;
this . name = "From Base45" ;
this . module = "Default" ;
this . description = "Base45 is a notation for encoding arbitrary byte data using a restricted set of symbols that can be conveniently used by humans and processed by computers. The high number base results in shorter strings than with the decimal or hexadecimal system. Base45 is optimized for usage with QR codes." ;
this . infoURL = "https://wikipedia.org/wiki/List_of_numeral_systems" ;
this . inputType = "string" ;
this . outputType = "byteArray" ;
2022-03-28 17:15:37 +02:00
this . args = [
{
name : "Alphabet" ,
type : "string" ,
value : ALPHABET
2022-06-14 11:23:13 +02:00
} ,
{
name : "Remove non-alphabet chars" ,
type : "boolean" ,
value : true
} ,
2022-03-28 17:15:37 +02:00
] ;
2021-09-17 08:32:08 +02:00
this . highlight = highlightFromBase45 ;
this . highlightReverse = highlightToBase45 ;
2021-09-11 17:03:59 +02:00
}
/ * *
* @ param { string } input
* @ param { Object [ ] } args
* @ returns { byteArray }
* /
run ( input , args ) {
if ( ! input ) return [ ] ;
2022-06-14 11:23:13 +02:00
const alphabet = Utils . expandAlphRange ( args [ 0 ] ) . join ( "" ) ;
const removeNonAlphChars = args [ 1 ] ;
2021-09-11 17:03:59 +02:00
const res = [ ] ;
2022-06-14 11:23:13 +02:00
// Remove non-alphabet characters
if ( removeNonAlphChars ) {
const re = new RegExp ( "[^" + alphabet . replace ( /[[\]\\\-^$]/g , "\\$&" ) + "]" , "g" ) ;
input = input . replace ( re , "" ) ;
}
2021-09-11 17:03:59 +02:00
for ( const triple of Utils . chunked ( input , 3 ) ) {
triple . reverse ( ) ;
let b = 0 ;
for ( const c of triple ) {
2022-03-28 17:15:37 +02:00
const idx = alphabet . indexOf ( c ) ;
2021-09-11 17:03:59 +02:00
if ( idx === - 1 ) {
throw new OperationError ( ` Character not in alphabet: ' ${ c } ' ` ) ;
}
b *= 45 ;
b += idx ;
}
if ( b > 65535 ) {
throw new OperationError ( ` Triplet too large: ' ${ triple . join ( "" ) } ' ` ) ;
}
if ( triple . length > 2 ) {
/ * *
* The last triple may only have 2 bytes so we push the MSB when we got 3 bytes
* Pushing MSB
* /
res . push ( b >> 8 ) ;
}
/ * *
* Pushing LSB
* /
res . push ( b & 0xff ) ;
}
return res ;
}
}
export default FromBase45 ;