diff --git a/README.md b/README.md index 6f8cdb55a10cad991050127d5298fb63ec3b0362..a189511c18e9683f0a373a4acfc87a302a765785 100755 --- a/README.md +++ b/README.md @@ -10,52 +10,159 @@ ## Introduction The interface of util is used for character Textencoder, TextDecoder and HelpFunction module.The TextEncoder represents a text encoder that accepts a string as input, encodes it in UTF-8 format, and outputs UTF-8 byte stream. The TextDecoder interface represents a text decoder. The decoder takes the byte stream as the input and outputs the Stirng string. HelpFunction is mainly used to callback and promise functions, write and output error codes, and format class strings. +Encodes all bytes from the specified u8 array into a newly-allocated u8 array using the Base64 encoding scheme or Encodes the specified byte array into a String using the Base64 encoding scheme.Decodes a Base64 encoded String or input u8 array into a newly-allocated u8 array using the Base64 encoding scheme.The rational number is mainly to compare rational numbers and obtain the numerator and denominator.The LruBuffer algorithm replaces the least used data with new data when the buffer space is insufficient. The algorithm derives from the need to access resources: recently accessed data can be Will visit again in the near future. The least accessed data is the least valuable data that should be kicked out of the cache space. The Scope interface is used to describe the valid range of a field. The constructor for the Scope instance is used to create objects with specified lower and upper bounds and require that these objects be comparable. ## 目录 ``` base/compileruntime/js_util_module/ ├── Class:TextEncoder # TextEncoder class -│ ├── new TextEncoder() # create textencoder object -│ ├── encode() # encode method -│ ├── encoding # encoding property +│ ├── new TextEncoder() # create textencoder object +│ ├── encode() # encode method +│ ├── encoding # encoding property │ └── encodeInto() # encodeInto method ├── Class:TextDecoder # TextDecoder class │ ├── new TextDecoder() # create TextDecoder object -│ ├── decode() # decode method -│ ├── encoding # encoding property -│ ├── fatal # fatal property +│ ├── decode() # decode method +│ ├── encoding # encoding property +│ ├── fatal # fatal property │ └── ignoreBOM # ignoreBOM property -├── printf() # printf method -├── getErrorString() # getErrorString method -├── callbackWrapper() # callbackWrapper method -└── promiseWrapper() # promiseWrapper method +├── printf() # printf method +├── getErrorString() # getErrorString method +├── callbackWrapper() # callbackWrapper method +├── promiseWrapper() # promiseWrapper method +├── Class:Base64 # Base64 class +│ ├── new Base64() # create Base64 object +│ ├── encode() # encode method +│ ├── encodeToString() # encodeToString method +│ ├── decode() # decode method +│ ├── encodeAsync() # encodeAsync method +│ ├── encodeToStringAsync() # encodeToStringAsync method +│ └── decodeAsync() # decodeAsync method +├── Class:RationalNumber # RationalNumber class +│ ├── new RationalNumber() # create RationalNumber object +│ ├── createRationalFromString() # creatRationalFromString method +│ ├── compareTo() # compareTo method +│ ├── equals() # equals method +│ ├── value() # value method +│ ├── getCommonDivisor() # getCommonDivisor method +│ ├── getDenominator() # getDenominator method +│ ├── getNumerator() # getNumerator method +│ ├── isFinite() # isFinite method +│ ├── isNaN() # isNaN method +│ ├── isZero() # isZero method +│ └── toString() # toString method +├── Class:LruBuffer # LruBuffer class +│ ├── new LruBuffer() # create RationalNumber object +│ ├── updateCapacity() # updateCapacity method +│ ├── toString() # toString method +│ ├── values() # values method +│ ├── size() # size method +│ ├── capacity() # capacity method +│ ├── clear() # clear method +│ ├── getCreateCount # getCreateCount method +│ ├── getMissCount() # getMissCount method +│ ├── getRemovalCount() # getRemovalCount method +│ ├── getMatchCount() # getMatchCount method +│ ├── getPutCount() # getPutCount method +│ ├── isEmpty() # isEmpty method +│ ├── get() # get method +│ ├── put() # put method +│ ├── keys() # keys method +│ ├── remove() # remove method +│ ├── afterRemoval() # afterRemoval method +│ ├── contains() # contains method +│ ├── createDefault() # createDefault method +│ ├── entries() # entries method +│ └── [Symbol.iterator]() # Symboliterator method +└── Class:Scope # Scope class + ├── constructor() # create Scope object + ├── toString() # toString method + ├── intersect() # intersect method + ├── intersect() # intersect method + ├── getUpper() # getUpper method + ├── getLower() # getLower method + ├── expand() # expand method + ├── expand() # expand method + ├── expand() # expand method + ├── contains() # contains method + ├── contains() # contains method + └── clamp() # clamp method ``` ## Description ### Interface description - - | Interface name | Description | | -------- | -------- | -| readonly encoding : string | Get the encoding format, only UTF-8 is supported. | +| readonly encoding : string | In the TextEncoder module, get the encoding format, only UTF-8 is supported. | | encode(input : string) : Uint8Array | Input stirng string, encode and output UTF-8 byte stream. | | encodeInto(input : string, dest : Uint8Array) : {read : number, written : number} | Enter the stirng string, dest represents the storage location after encoding, and returns an object, read represents the number of characters that have been encoded,and written represents the size of bytes occupied by the encoded characters. | | constructor(encoding? : string, options? : {fatal? : boolean, ignoreBOM? : boolean}) | Constructor, the first parameter encoding indicates the format of decoding.The second parameter represents some attributes.Fatal in the attribute indicates whether an exception is thrown, and ignoreBOM indicates whether to ignore the bom flag. | -| readonly encoding : string | Get the set decoding format. | +| readonly encoding : string | In the TextDecoder module, get the set decoding format. | | readonly fatal : boolean | Get the setting that throws the exception. | | readonly ignoreBOM : boolean | Get whether to ignore the setting of the bom flag. | -| decode(input : ArrayBuffer | Input the data to be decoded, and solve the corresponding string character string.The first parameter input represents the data to be decoded, and the second parameter options represents a bool flag, which means that additional data will be followed. The default is false. | +| decode(input : Uint8Array, options?: { stream?: false }) : string | Input the data to be decoded, and solve the corresponding string character string.The first parameter input represents the data to be decoded, and the second parameter options represents a bool flag, which means that additional data will be followed. The default is false. | +| encode(src: Uint8Array): Uint8Array; | Encodes all bytes in the specified u8 array into the newly allocated u8 array using the Base64 encoding scheme. | +| encodeToString(src: Uint8Array): string; | Encodes the specified byte array as a String using the Base64 encoding scheme. | +| decode(src: Uint8Array \| string): Uint8Array; | Decodes the Base64-encoded string or input u8 array into the newly allocated u8 array using the Base64 encoding scheme. | +| encodeAsync(src: Uint8Array): Promise\; | Asynchronously encodes all bytes in the specified u8 array into the newly allocated u8 array using the Base64 encoding scheme. | +| encodeToStringAsync(src: Uint8Array): Promise\; | Asynchronously encodes the specified byte array into a String using the Base64 encoding scheme. | +| decodeAsync(src: Uint8Array \| string): Promise\; | Use the Base64 encoding scheme to asynchronously decode a Base64-encoded string or input u8 array into a newly allocated u8 array. | +| static createRationalFromString(rationalString: string): RationalNumber | Create a RationalNumber object based on the given string. | +| compareTo(another: RationalNumber): number | Compare the current RationalNumber object with the given object. | +| equals(obj: object): number | Check if the given object is the same as the current RationalNumber object.| +| value(): number | Take the current RationalNumber object to an integer value or a floating point value. | +| static getCommonDivisor(number1: number, number2: number,): number | Obtain the greatest common divisor of two specified numbers. | +| getDenominator(): number | Get the denominator of the current RationalNumber object. | +| getNumerator(): number | Get the numerator of the current RationalNumber object. | +| isFinite(): boolean | Check that the current RationalNumber object is limited. | +| isNaN(): boolean | Check whether the current RationalNumber object represents a non-number (NaN) value. | +| isZero(): boolean | Check whether the current RationalNumber object represents a zero value. | +| toString(): string | Get the string representation of the current RationalNumber object. | +| constructor(capacity?: number) | The Create Default constructor is used to create a new LruBuffer instance with a default capacity of 64. | +| updateCapacity(newCapacity: number): void | Updates the buffer capacity to the specified capacity. This exception is thrown if newCapacity is less than or equal to 0. | +| toString(): string | Returns the string representation of the object and outputs the string representation of the object. | +| values(): V[ ] | Gets a list of all values in the current buffer, and the output returns a list of all values in the current buffer in ascending order, from most recently accessed to least recently accessed. | +| size(): number | Gets the total number of values in the current buffer. The output returns the total number of values in the current buffer. | +| capacity(): number | Gets the capacity of the current buffer. The output returns the capacity of the current buffer. | +| clear(): void | The key value pairs are cleared from the current buffer, after the key value is cleared, the afterRemoval () method is invoked to perform subsequent operations in turn. | +| getCreateCount(): number | Get the number of times the returned value of createdefault(), and output the number of times the returned value of createdefault(). | +| getMissCount(): number | Get the number of times the query value does not match, and output the number of times the query value does not match. | +| getRemovalCount(): number | Gets the number of evictions from the buffer, and outputs the number of evictions from the buffer. | +| getMatchCount​(): number | Obtain the number of successful matching of query values, and output the number of successful matching of query values. | +| getPutCount(): number | Gets the number of times the value was added to the buffer, and the output returns the number of times the value was added to the buffer. | +| isEmpty(): boolean | Checks whether the current buffer is empty and returns true if the current buffer does not contain any values. | +| get(k: key):V \| undefined | Indicates the key to query. If the specified key exists in the buffer, the value associated with the key will be returned; Otherwise, undefined is returned. | +| put(K: key, V: value): V | Adding the key value pair to the buffer and outputting the value associated with the added key; If the key to be added already exists, the original value is returned. If the key or value is empty, this exception is thrown. | +| keys(): K[ ] | Get the key list of the value in the current buffer, and the output returns the key list sorted from the most recent access to the least recent access. | +| remove​(k: key):V \| undefined | Deletes the specified key and its associated value from the current buffer. | +| afterRemoval(boolean: isEvict, K: key, V: value, V: newValue):void | Perform subsequent operations after deleting the value. | +| contains(k: key):boolean | Checks whether the current buffer contains the specified key, and returns true if the buffer contains the specified key. | +| createDefault(k: key): V | If the value of a specific key is not calculated, subsequent operations are performed. The parameter represents the missing key, and the output returns the value associated with the key. | +| entries(): [K,V] | Allows you to iterate over all key value pairs contained in this object. The keys and values of each pair are objects. | +| \[Symbol.iterator\](): [K,V]| Returns a two-dimensional array in the form of key value pairs. | +| constructor(lowerObj: ScopeType, upperObj: ScopeType) | Creates and returns a Scope object that creates a constructor for a scope instance that specifies a lower and upper bound. | +| toString():string | The stringification method returns a string representation that contains the current range. | +| intersect(range: Scope): Scope | Gets the intersection of the given range and the current range. | +| intersect(lowerObj: ScopeType, upperObj: ScopeType): Scope | Gets the intersection of the current range with a given lower and upper bound range. | +| getUpper(): ScopeType | Gets the upper bound of the current scope. | +| getLower(): ScopeType | Gets the lower bound of the current scope. | +| expand(lowerObj: ScopeType, upperObj: ScopeType): Scope | Creates and returns a union that includes the current range and a given lower and upper bound. | +| expand(range: Scope): Scope | Creates and returns a union that includes the current range and the given range. | +| expand(value: ScopeType): Scope | Creates and returns a union that includes the current range and the given value. | +| contains(value: ScopeType): boolean | Checks whether the given value is included in the current range. | +| contains(range: Scope): boolean | Checks whether the given range is within the current range. | +| clamp(value: ScopeType): ScopeType | Clips the specified value to the current range. | | function printf(format: string, ...args: Object[]): string | The util.format() method returns a formatted string using the first argument as a printf-like format string which can contain zero or more format specifiers. | | function getErrorString(errno: number): string | The geterrorstring () method uses a system error number as a parameter to return system error information. | | function callbackWrapper(original: Function): (err: Object, value: Object) => void | Takes an async function (or a function that returns a Promise) and returns a function following the error-first callback style, i.e. taking an (err, value) => ... callback as the last argument. In the callback, the first argument will be the rejection reason (or null if the Promise resolved), and the second argument will be the resolved value. | -| function promiseWrapper(original: (err: Object, value: Object) => void): Object | Takes a function following the common error-first callback style, i.e. taking an (err, value) => ... callback as the last argument, and returns a version that returns promises. | +| function promiseWrapper(original: (err: Object, value: Object) => void): Object | Takes a function following the common error-first callback style, i.e. taking an (err, value) => ... callback as the last argument, and returns a version that returns promises. | Each specifier in printf is replaced with a converted value from the corresponding parameter. Supported specifiers are: | Stylized character | Style requirements | | -------- | -------- | -| %s: | String will be used to convert all values except BigInt, Object and -0. | -| %d: | Number will be used to convert all values except BigInt and Symbol. | +| %s: | String will be used to convert all values except BigInt, Object and -0. | +| %d: | Number will be used to convert all values except BigInt and Symbol. | | %i: | parseInt(value, 10) is used for all values except BigInt and Symbol. | | %f: | parseFloat(value) is used for all values expect Symbol. | | %j: | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | @@ -70,6 +177,7 @@ Each specifier in printf is replaced with a converted value from the correspondi The use methods of each interface are as follows: 1.readonly encoding() + ``` import util from '@ohos.util' var textEncoder = new util.TextEncoder(); @@ -158,8 +266,415 @@ newPromiseObj.then(res => { expect(res).strictEqual('HelloWorld'); }) ``` +13.encode() +``` +import util from '@ohos.util' +var that = new util.Base64(); +var array = new Uint8Array([115,49,51]); +var result = that.encode(array); +``` +14.encodeToString() +``` +import util from '@ohos.util' +var that = new util.Base64(); +var array = new Uint8Array([115,49,51]); +var result = that.encodeToString(array); +``` +15.decode() +``` +import util from '@ohos.util' +var that = new util.Base64() +var buff = 'czEz'; +var result = that.decode(buff); +``` +16.encodeAsync() +``` +import util from '@ohos.util' +var that = new util.Base64() +var array = new Uint8Array([115,49,51]); +that.encodeAsync(array).then(val=>{ +}) +``` +7.encodeToStringAsync() +``` +import util from '@ohos.util' +var that = new util.Base64() +var array = new Uint8Array([115,49,51]); +that.encodeToStringAsync(array).then(val=>{ +}) +``` +18.decodeAsync() +``` +import util from '@ohos.util' +var that = new util.Base64() +var buff = 'czEz'; +that.decodeAsync(buff).then(val=>{ +}) +``` +19.createRationalFromString() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(0, 0); +var res = pro.createRationalFromString("-1:2"); +var result1 = res.value(); +``` +20.compareTo() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(2, 1); +var proc = new util.RationalNumber(3, 4); +var res = pro.compareTo(proc); +``` +21.equals() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(2, 1); +var proc = new util.RationalNumber(3, 4); +var res = pro.equals(proc); +``` +22.value() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(2, 1); +var res = pro.value(); +``` +23.getCommonDivisor() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(0, 0); +var res = pro.getCommonDivisor(4, 8); +``` +24.getDenominator() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(2, 1); +var res = pro.getDenominator(); +``` +25.getNumerator() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(-2, 1); +var res = pro.getNumerator(); +``` +26.isFinite() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(-2, 1); +var res = pro.isFinite(); +``` +27.isNaN() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(-2, 1); +var res = pro.isNaN(); +``` +28.isZero() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(-2, 1); +var res = pro.isZero(); + +``` +29.toString() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(-2, 1); +var res = pro.toString(); + +``` +30.updateCapacity() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +var result = pro.updateCapacity(100); +``` +31.toString() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +pro.get(2); +pro.remove(20); +var result = pro.toString(); +``` +32.values() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +pro.put(2,"anhu"); +pro.put("afaf","grfb"); +var result = pro.values(); +``` +33.size() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +pro.put(1,8); +var result = pro.size(); +``` +34.capacity() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +var result = pro.capacity(); +``` +35.clear() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +pro.clear(); +``` +36.getCreatCount() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(1,8); +var result = pro.getCreatCount(); +``` +37.getMissCount() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +pro.get(2) +var result = pro.getMissCount(); +``` +38.getRemovalCount() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +pro.updateCapacity(2); +pro.put(50,22); +var result = pro.getRemovalCount(); +``` +39.getMatchCount() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +pro.get(2); +var result = pro.getMatchCount(); +``` +40.getPutCount() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var result = pro.getPutCount(); +``` +41.isEmpty() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var result = pro.isEmpty(); +``` +42.get() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var result = pro.get(2); +``` +43.put() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +var result = pro.put(2,10); +``` +44.keys() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var result = pro.keys(); +``` +45.remove() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var result = pro.remove(20); +``` +46.contains() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var result = pro.contains(20); +``` +47.createDefault() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +var result = pro.createDefault(50); +``` +48.entries() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var result = pro.entries(); +``` +49.\[Symbol.iterator\]() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var result = aa[symbol.iterator](); +``` +50.afterRemoval() +``` +import util from '@ohos.util' +var arr = []; +class ChildLruBuffer extends util.LruBuffer +{ + constructor() + { + super(); + } + static getInstance() + { + if(this.instance == null) + { + this.instance = new ChildLruBuffer(); + } + return this.instance; + } + afterRemoval(isEvict, key, value, newValue) + { + if (isEvict === false) + { + arr = [key, value, newValue]; + } + } +} +ChildLruBuffer.getInstance().afterRemoval(false,10,30,null) +``` +Construct a new class in the Scope interface to implement the compareTo method. + +``` +class Temperature { + constructor(value) { + this._temp = value; + } + compareTo(value) { + return this._temp >= value.getTemp(); + } + getTemp() { + return this._temp; + } + toString() { + return this._temp.toString(); + } +} +``` +51.constructor() +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var range = new Scope(tempLower, tempUpper); +``` +52.toString() +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var range = new Scope(tempLower, tempUpper); +var result = range.toString() // => [30,40] +``` +53.intersect() +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var range = new Scope(tempLower, tempUpper); +var tempMiDF = new Temperature(35); +var tempMidS = new Temperature(39); +var rangeFir = new Scope(tempMiDF, tempMidS); +var result = range.intersect(rangeFir) // => [35,39] +``` +54.intersect() +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var tempMiDF = new Temperature(35); +var tempMidS = new Temperature(39); +var range = new Scope(tempLower, tempUpper); +var result = range.intersect(tempMiDF, tempMidS) // => [35,39] +``` +55.getUpper() +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var range = new Scope(tempLower, tempUpper); +var result = range.getUpper() // => 40 +``` +56.getLower() +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var range = new Scope(tempLower, tempUpper); +var result = range.getLower() // => 30 +``` +57.expand() +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var tempMiDF = new Temperature(35); +var tempMidS = new Temperature(39); +var range = new Scope(tempLower, tempUpper); +var result = range.expand(tempMiDF, tempMidS) // => [30,40] +``` +58.expand() +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var tempMiDF = new Temperature(35); +var tempMidS = new Temperature(39); +var range = new Scope(tempLower, tempUpper); +var rangeFir = new Scope(tempMiDF, tempMidS); +var result = range.expand(rangeFir) // => [30,40] +``` +59.expand() +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var tempMiDF = new Temperature(35); +var range = new Scope(tempLower, tempUpper); +var result = range.expand(tempMiDF) // => [30,40] +``` +60.contains() +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var tempMiDF = new Temperature(35); +var range = new Scope(tempLower, tempUpper); +var result = range.contains(tempMiDF) // => true +``` +61.contains() +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var range = new Scope(tempLower, tempUpper); +var tempLess = new Temperature(20); +var tempMore = new Temperature(45); +var rangeSec = new Scope(tempLess, tempMore); +var result = range.contains(rangeSec) // => true +``` +62.clamp() +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var tempMiDF = new Temperature(35); +var range = new Scope(tempLower, tempUpper); +var result = range.clamp(tempMiDF) // => 35 +``` ## Related warehouse [js_util_module subsystem](https://gitee.com/OHOS_STD/js_util_module) [base/compileruntime/js_util_module/](base/compileruntime/js_util_module-readme.md) + diff --git a/README_zh.md b/README_zh.md old mode 100755 new mode 100644 index 9210368799c511a43d04d2d67a8fafa28d736ae7..a0e4d860f01c4831cb69876c1f4381c24420fc9a --- a/README_zh.md +++ b/README_zh.md @@ -1,165 +1,681 @@ -# js_util_module子系统/组件 - -- [简介](#简介) -- [目录](#目录) -- [说明](#说明) - - [接口说明](#接口说明) - - [使用说明](#使用说明) - -- [相关仓](#相关仓) - -## 简介 - -UTIL接口用于字符编码TextEncoder、解码TextDecoder和帮助函数HelpFunction。TextEncoder表示一个文本编码器,接受字符串作为输入,以UTF-8格式进行编码,输出UTF-8字节流。TextDecoder接口表示一个文本解码器,解码器将字节流作为输入,输出stirng字符串。HelpFunction主要是对函数做callback化、promise化以及对错误码进行编写输出,及类字符串的格式化输出。 -## 目录 - -``` -base/compileruntime/js_util_module/ -├── Class:TextEncoder # TextEncoder类 -│ ├── new TextEncoder() # 创建TextEncoder对象 -│ ├── encode() # encode方法 -│ ├── encoding # encoding属性 -│ └── encodeInto() # encodeInto方法 -├── Class:TextDecoder # TextDecoder类 -│ ├── new TextDecoder() # 创建TextDecoder对象 -│ ├── decode() # decode方法 -│ ├── encoding # encoding属性 -│ ├── fatal # fatal属性 -│ └── ignoreBOM # ignoreBOM属性 -├── printf() # printf方法 -├── getErrorString() # getErrorString方法 -├── callbackWrapper() # callbackWrapper方法 -└── promiseWrapper() # promiseWrapper方法 -``` - -## 说明 - -### 接口说明 - - -| 接口名 | 说明 | -| -------- | -------- | -| readonly encoding : string | 获取编码的格式,只支持UTF-8。 | -| encode(input : string) : Uint8Array | 输入stirng字符串,编码并输出UTF-8字节流。 | -| encodeInto(input : string, dest : Uint8Array) : {read : number, written : number} | 输入stirng字符串,dest表示编码后存放位置,返回一个对象,read表示已经编码的字符的个数,written表示已编码字符所占字节的大小。 | -| constructor(encoding? : string, options? : {fatal? : boolean, ignoreBOM? : boolean}) | 构造函数,第一个参数encoding表示解码的格式。第二个参数表示一些属性。属性中fatal表示是否抛出异常,ignoreBOM表示是否忽略bom标志。 | -| readonly encoding : string | 获取设置的解码格式。 | -| readonly fatal : boolean | 获取抛出异常的设置 | -| readonly ignoreBOM : boolean | 获取是否忽略bom标志的设置 | -| decode(input : ArrayBuffer | 输入要解码的数据,解出对应的string字符串。第一个参数input表示要解码的数据,第二个参数options表示一个bool标志,表示将跟随附加数据,默认为false。 | -| function printf(format: string, ...args: Object[]): string | printf()方法使用第一个参数作为格式字符串(其可以包含零个或多个格式说明符)来返回格式化的字符串。 | -| function getErrorString(errno: number): string | getErrorString()方法使用一个系统的错误数字作为参数,用来返回系统的错误信息。 | -| function callbackWrapper(original: Function): (err: Object, value: Object) => void | 参数为一个采用 async 函数(或返回 Promise 的函数)并返回遵循错误优先回调风格的函数,即将 (err, value) => ... 回调作为最后一个参数。 在回调中,第一个参数将是拒绝原因(如果 Promise 已解决,则为 null),第二个参数将是已解决的值。 | -| function promiseWrapper(original: (err: Object, value: Object) => void): Object | 参数为采用遵循常见的错误优先的回调风格的函数(也就是将 (err, value) => ... 回调作为最后一个参数),并返回一个返回 promise 的版本。 | - -printf中每个说明符都替换为来自相应参数的转换后的值。 支持的说明符有: -| 式样化字符 | 式样要求 | -| -------- | -------- | -| %s: | String 将用于转换除 BigInt、Object 和 -0 之外的所有值。| -| %d: |Number 将用于转换除 BigInt 和 Symbol 之外的所有值。| -| %i: |parseInt(value, 10) 用于除 BigInt 和 Symbol 之外的所有值。| -| %f: |parseFloat(value) 用于除 Symbol 之外的所有值。| -| %j: |JSON。 如果参数包含循环引用,则替换为字符串 '[Circular]'。| -| %o: |Object. 具有通用 JavaScript 对象格式的对象的字符串表示形式。类似于具有选项 { showHidden: true, showProxy: true } 的 util.inspect()。这将显示完整的对象,包括不可枚举的属性和代理。| -| %O: |Object. 具有通用 JavaScript 对象格式的对象的字符串表示形式。类似于没有选项的 util.inspect()。 这将显示完整的对象,但不包括不可枚举的属性和代理。| -| %c: | 此说明符被忽略,将跳过任何传入的 CSS。| -| %%: |单个百分号 ('%')。 这不消耗待式样化参数。| - -### 使用说明 - -各接口使用方法如下: - -1.readonly encoding() -``` -import util from '@ohos.util' -var textEncoder = new util.TextEncoder(); -var getEncoding = textEncoder.encoding(); -``` -2.encode() -``` -import util from '@ohos.util' -var textEncoder = new util.TextEncoder(); -var result = textEncoder.encode('abc'); -``` -3.encodeInto() -``` -import util from '@ohos.util' -var textEncoder = new util.TextEncoder(); -var obj = textEncoder.encodeInto('abc', dest); -``` -4.textDecoder() -``` -import util from '@ohos.util' -var textDecoder = new util.textDecoder("utf-16be", {fatal : ture, ignoreBOM : false}); -``` -5.readonly encoding() -``` -import util from '@ohos.util' -var textDecoder = new util.textDecoder("utf-16be", {fatal : ture, ignoreBOM : false}); -var getEncoding = textDecoder.encoding(); -``` -6.readonly fatal() -``` -import util from '@ohos.util' -var textDecoder = new util.textDecoder("utf-16be", {fatal : ture, ignoreBOM : false}); -var fatalStr = textDecoder.fatal(); -``` -7.readonly ignoreBOM() -``` -import util from '@ohos.util' -var textDecoder = new util.textDecoder("utf-16be", {fatal : ture, ignoreBOM : false}); -var ignoreBom = textDecoder.ignoreBOM(); -``` -8.decode() -``` -import util from '@ohos.util' -var textDecoder = new util.textDecoder("utf-16be", {fatal : ture, ignoreBOM : false}); -var result = textDecoder.decode(input, {stream : true}); -``` -9.printf() -``` -import util from '@ohos.util' -var format = "%%%o%%%i%s"; -var value = function aa(){}; -var value1 = 1.5; -var value2 = "qwer"; -var result = util.printf(format,value,value1,value2); -``` -10.getErrorString() -``` -import util from '@ohos.util' -var errnum = 13; -var result = util.getErrorString(errnum); -``` -11.callbackWrapper() -``` -import util from '@ohos.util' -async function promiseFn() { - return Promise.resolve('value'); -}; -var cb = util.callbackWrapper(promiseFn); -cb((err, ret) => { - expect(err).strictEqual(null); - expect(ret).strictEqual('value'); -}) -``` -12.promiseWrapper() -``` -import util from '@ohos.util' -function aysnFun(str1, str2, callback) { - if (typeof str1 === 'string' && typeof str1 === 'string') { - callback(null, str1 + str2); - } else { - callback('type err'); - } -} -let newPromiseObj = util.promiseWrapper(aysnFun)("Hello", 'World'); -newPromiseObj.then(res => { - expect(res).strictEqual('HelloWorld'); -}) -``` -## 相关仓 - -[js_util_module子系统](https://gitee.com/OHOS_STD/js_util_module) - -[base/compileruntime/js_util_module/](base/compileruntime/js_util_module-readme.md) +# js_util_module子系统/组件 + +- [简介](#简介) +- [目录](#目录) +- [说明](#说明) + - [接口说明](#接口说明) + - [使用说明](#使用说明) + +- [相关仓](#相关仓) + +## 简介 + +UTIL接口用于字符编码TextEncoder、解码TextDecoder、帮助函数HelpFunction、基于Base64的字节编码encode和解码decode、有理数RationalNumber。TextEncoder表示一个文本编码器,接受字符串作为输入,以UTF-8格式进行编码,输出UTF-8字节流。TextDecoder接口表示一个文本解码器,解码器将字节流作为输入,输出stirng字符串。HelpFunction主要是对函数做callback化、promise化以及对错误码进行编写输出,及类字符串的格式化输出。encode接口使用Base64编码方案将指定u8数组中的所有字节编码到新分配的u8数组中或者使用Base64编码方案将指定的字节数组编码为String。decode接口使用Base64编码方案将Base64编码的字符串或输入u8数组解码为新分配的u8数组。RationalNumber有理数主要是对有理数进行比较,获取分子分母等方法。LruBuffer该算法在缓存空间不够的时候,将近期最少使用的数据替换为新数据。该算法源自这样一种访问资源的需求:近期访问的数据,可能在不久的将来会再次访问。于是最少访问的数据就是价值最小的,是最应该踢出缓存空间的数据。Scope接口用于描述一个字段的有效范围。 Scope实例的构造函数用于创建具有指定下限和上限的对象,并要求这些对象必须具有可比性。 +## 目录 + +``` +base/compileruntime/js_util_module/ +├── Class:TextEncoder # TextEncoder类 +│ ├── new TextEncoder() # 创建TextEncoder对象 +│ ├── encode() # encode方法 +│ ├── encoding # encoding属性 +│ └── encodeInto() # encodeInto方法 +├── Class:TextDecoder # TextDecoder类 +│ ├── new TextDecoder() # 创建TextDecoder对象 +│ ├── decode() # decode方法 +│ ├── encoding # encoding属性 +│ ├── fatal # fatal属性 +│ └── ignoreBOM # ignoreBOM属性 +├── printf() # printf方法 +├── getErrorString() # getErrorString方法 +├── callbackWrapper() # callbackWrapper方法 +├── promiseWrapper() # promiseWrapper方法 +├── Class:Base64 # Base64类 +│ ├── new Base64() # 创建Base64对象 +│ ├── encode() # encode方法 +│ ├── encodeToString() # encodeToString方法 +│ ├── decode() # decode方法 +│ ├── encodeAsync() # encodeAsync方法 +│ ├── encodeToStringAsync() # encodeToStringAsync方法 +│ └── decodeAsync() # decodeAsync方法 +├── Class:RationalNumber # RationalNumber类 +│ ├── new RationalNumber() # 创建RationalNumber对象 +│ ├── createRationalFromString() # createRationalFromString方法 +│ ├── compareTo() # compareTo方法 +│ ├── equals() # equals方法 +│ ├── value() # value方法 +│ ├── getCommonDivisor() # getCommonDivisor方法 +│ ├── getDenominator() # getDenominator方法 +│ ├── getNumerator() # getNumerator方法 +│ ├── isFinite() # isFinite方法 +│ ├── isNaN() # isNaN方法 +│ ├── isZero() # isZero方法 +│ └── toString() # toString方法 +├── Class:LruBuffer # LruBuffer类 +│ ├── new LruBuffer() # 创建LruBuffer对象 +│ ├── updateCapacity() # updateCapacity方法 +│ ├── toString() # toString方法 +│ ├── values() # values方法 +│ ├── size() # size方法 +│ ├── capacity() # capacity方法 +│ ├── clear() # clear方法 +│ ├── getCreateCount() # getCreateCount方法 +│ ├── getMissCount() # getMissCount方法 +│ ├── getRemovalCount() # getRemovalCount方法 +│ ├── getMatchCount() # getMatchCount方法 +│ ├── getPutCount() # getPutCount方法 +│ ├── isEmpty() # isEmpty方法 +│ ├── get() # get方法 +│ ├── put() # put方法 +│ ├── keys() # keys方法 +│ ├── remove() # remove方法 +│ ├── afterRemoval() # afterRemoval方法 +│ ├── contains() # contains方法 +│ ├── createDefault() # createDefault方法 +│ ├── entries() # entries方法 +│ └── [Symbol.iterator]() # Symboliterator方法 +└── Class:Scope # Scope类 + ├── constructor() # 创建Scope对象 + ├── toString() # toString方法 + ├── intersect() # intersect方法 + ├── intersect() # intersect方法 + ├── getUpper() # getUpper方法 + ├── getLower() # getLower方法 + ├── expand() # expand方法 + ├── expand() # expand方法 + ├── expand() # expand法 + ├── contains() # contains方法 + ├── contains() # contains方法 + └── clamp() # clamp方法 +``` +## 说明 + +### 接口说明 + + +| 接口名 | 说明 | +| -------- | -------- | +| readonly encoding : string | 在TextEncoder类中,获取编码的格式,只支持UTF-8。 | +| encode(input : string) : Uint8Array | 输入stirng字符串,编码并输出UTF-8字节流。 | +| encodeInto(input : string, dest : Uint8Array) : {read : number, written : number} | 输入stirng字符串,dest表示编码后存放位置,返回一个对象,read表示已经编码的字符的个数,written表示已编码字符所占字节的大小。 | +| constructor(encoding? : string, options? : {fatal? : boolean, ignoreBOM? : boolean}) | 构造函数,第一个参数encoding表示解码的格式。第二个参数表示一些属性。属性中fatal表示是否抛出异常,ignoreBOM表示是否忽略bom标志。 | +| readonly encoding : string | 在TextDecoder类中,获取设置的解码格式。 | +| readonly fatal : boolean | 获取抛出异常的设置。 | +| readonly ignoreBOM : boolean | 获取是否忽略bom标志的设置。 | +| decode(input : Uint8Array, options?: { stream?: false }) : string | 输入要解码的数据,解出对应的string字符串。第一个参数input表示要解码的数据,第二个参数options表示一个bool标志,表示将跟随附加数据,默认为false。 | +| encode(src: Uint8Array): Uint8Array; | 使用Base64编码方案将指定u8数组中的所有字节编码到新分配的u8数组中。 | +| encodeToString(src: Uint8Array): string; | 使用Base64编码方案将指定的字节数组编码为String。 | +| decode(src: Uint8Array \| string): Uint8Array; | 使用Base64编码方案将Base64编码的字符串或输入u8数组解码为新分配的u8数组。 | +| encodeAsync(src: Uint8Array): Promise\; | 使用Base64编码方案将指定u8数组中的所有字节异步编码到新分配的u8数组中。 | +| encodeToStringAsync(src: Uint8Array): Promise\; | 使用Base64编码方案将指定的字节数组异步编码为String。 | +| decodeAsync(src: Uint8Array \| string): Promise\; | 使用Base64编码方案将Base64编码的字符串或输入u8数组异步解码为新分配的u8数组。 | +| static createRationalFromString(rationalString: string): RationalNumber | 基于给定的字符串创建一个RationalNumber对象。 | +| compareTo(another: RationalNumber): number | 将当前的RationalNumber对象与给定的对象进行比较。 | +| equals(obj: object): number | 检查给定对象是否与当前 RationalNumber 对象相同。 | +| value(): number | 将当前的RationalNumber对象进行取整数值或者浮点数值。 | +| static getCommonDivisor(number1: number, number2: number,): number | 获得两个指定数的最大公约数。 | +| getDenominator(): number | 获取当前的RationalNumber对象的分母。 | +| getNumerator(): number | 获取当前的RationalNumber对象的分子。 | +| isFinite(): boolean | 检查当前的RationalNumber对象是有限的。 | +| isNaN(): boolean | 检查当前RationalNumber对象是否表示非数字(NaN)值。 | +| isZero(): boolean | 检查当前RationalNumber对象是否表示零值。 | +| toString(): string | 获取当前RationalNumber对象的字符串表示形式。 | +| constructor(capacity?: number) | 创建默认构造函数用于创建一个新的LruBuffer实例,默认容量为64。 | +| updateCapacity(newCapacity:number):void | 将缓冲区容量更新为指定容量,如果 newCapacity 小于或等于 0,则抛出此异常。 | +| toString():string | 返回对象的字符串表示形式,输出对象的字符串表示 | +| values():V[] | 获取当前缓冲区中所有值的列表,输出按升序返回当前缓冲区中所有值的列表,从最近访问到最近最少访问。 | +| size():number | 获取当前缓冲区中值的总数,输出返回当前缓冲区中值的总数。 | +| capacity():number | 获取当前缓冲区的容量,输出返回当前缓冲区的容量。 | +| clear():void | 从当前缓冲区清除键值对,清除键值对后,调用afterRemoval()方法依次对其执行后续操作。 | +| getCreateCount():number | 获取createDefault()返回值的次数,输出返回createDefault()返回值的次数。 | +| getMissCount():number | 获取查询值不匹配的次数,输出返回查询值不匹配的次数。 | +| getRemovalCount():number | 获取从缓冲区中逐出值的次数,输出从缓冲区中驱逐的次数。 | +| getMatchCount​():number | 获取查询值匹配成功的次数,输出返回查询值匹配成功的次数。 | +| getPutCount():number | 获取将值添加到缓冲区的次数,输出返回将值添加到缓冲区的次数。 | +| isEmpty():boolean | 检查当前缓冲区是否为空,输出如果当前缓冲区不包含任何值,则返回 true 。 | +| get(k:key):V \| undefined | 表示要查询的键,输出如果指定的键存在于缓冲区中,则返回与键关联的值;否则返回undefined。 | +| put(K key, V value):V | 将键值对添加到缓冲区,输出与添加的键关联的值;如果要添加的键已经存在,则返回原始值,如果键或值为空,则抛出此异常。 | +| keys():K[ ] | 获取当前缓冲区中值的键列表,输出返回从最近访问到最近最少访问排序的键列表。 | +| remove​(k:key):V \| undefined | 从当前缓冲区中删除指定的键及其关联的值。 | +| afterRemoval(boolean isEvict, K key, V value, V newValue):void | 删除值后执行后续操作。 | +| contains(k:key):boolean | 检查当前缓冲区是否包含指定的键,输出如果缓冲区包含指定的键,则返回 true 。 | +| createDefault(k:key):V | 如果未计算特定键的值,则执行后续操作,参数表示丢失的键,输出返回与键关联的值。 | +| entries():[K,V] | 允许迭代包含在这个对象中的所有键值对。每对的键和值都是对象。 | +| Symbol.iterator():[K,V] | 返回以键值对得形式得一个二维数组。 | +| constructor(lowerObj: ScopeType, upperObj: ScopeType) | 创建并返回一个Scope对象,用于创建指定下限和上限的作用域实例的构造函数。 | +| toString():string | 该字符串化方法返回一个包含当前范围的字符串表示形式。 | +| intersect(range: Scope): Scope | 获取给定范围和当前范围的交集。 | +| intersect(lowerObj: ScopeType, upperObj: ScopeType): Scope | 获取当前范围与给定下限和上限范围的交集。 | +| getUpper(): ScopeType | 获取当前范围的上限。 | +| getLower(): ScopeType | 获取当前范围的下限。 | +| expand(lowerObj: ScopeType, upperObj: ScopeType): Scope | 创建并返回包括当前范围和给定下限和上限的并集。 | +| expand(range: Scope): Scope | 创建并返回包括当前范围和给定范围的并集。 | +| expand(value: ScopeType): Scope | 创建并返回包括当前范围和给定值的并集。 | +| contains(value: ScopeType): boolean | 检查给定value是否包含在当前范围内。 | +| contains(range: Scope): boolean | 检查给定range是否在当前范围内。 | +| clamp(value: ScopeType): ScopeType | 将给定value限定到当前范围内。 | +| function printf(format: string, ...args: Object[]): string | printf()方法使用第一个参数作为格式字符串(其可以包含零个或多个格式说明符)来返回格式化的字符串。 | +| function getErrorString(errno: number): string | getErrorString()方法使用一个系统的错误数字作为参数,用来返回系统的错误信息。 | +| function callbackWrapper(original: Function): (err: Object, value: Object) => void | 参数为一个采用 async 函数(或返回 Promise 的函数)并返回遵循错误优先回调风格的函数,即将 (err, value) => ... 回调作为最后一个参数。 在回调中,第一个参数将是拒绝原因(如果 Promise 已解决,则为 null),第二个参数将是已解决的值。 | +| function promiseWrapper(original: (err: Object, value: Object) => void): Object | 参数为采用遵循常见的错误优先的回调风格的函数(也就是将 (err, value) => ... 回调作为最后一个参数),并返回一个返回 promise 的版本。 | + +printf中每个说明符都替换为来自相应参数的转换后的值。 支持的说明符有: +| 式样化字符 | 式样要求 | +| -------- | -------- | +| %s: | String 将用于转换除 BigInt、Object 和 -0 之外的所有值。| +| %d: | Number 将用于转换除 BigInt 和 Symbol 之外的所有值。| +| %i: | parseInt(value, 10) 用于除 BigInt 和 Symbol 之外的所有值。| +| %f: | parseFloat(value) 用于除 Symbol 之外的所有值。| +| %j: | JSON。 如果参数包含循环引用,则替换为字符串 '[Circular]'。| +| %o: | Object. 具有通用 JavaScript 对象格式的对象的字符串表示形式。类似于具有选项 { showHidden: true, showProxy: true } 的 util.inspect()。这将显示完整的对象,包括不可枚举的属性和代理。| +| %O: | Object. 具有通用 JavaScript 对象格式的对象的字符串表示形式。类似于没有选项的 util.inspect()。 这将显示完整的对象,但不包括不可枚举的属性和代理。| +| %c: | 此说明符被忽略,将跳过任何传入的 CSS 。| +| %%: | 单个百分号 ('%')。 这不消耗待式样化参数。| + +### 使用说明 +各接口使用方法如下: + +1.readonly encoding() + +``` +import util from '@ohos.util' +var textEncoder = new util.TextEncoder(); +var getEncoding = textEncoder.encoding(); +``` +2.encode() +``` +import util from '@ohos.util' +var textEncoder = new util.TextEncoder(); +var result = textEncoder.encode('abc'); +``` +3.encodeInto() +``` +import util from '@ohos.util' +var textEncoder = new util.TextEncoder(); +var obj = textEncoder.encodeInto('abc', dest); +``` +4.textDecoder() +``` +import util from '@ohos.util' +var textDecoder = new util.textDecoder("utf-16be", {fatal : ture, ignoreBOM : false}); +``` +5.readonly encoding() +``` +import util from '@ohos.util' +var textDecoder = new util.textDecoder("utf-16be", {fatal : ture, ignoreBOM : false}); +var getEncoding = textDecoder.encoding(); +``` +6.readonly fatal() +``` +import util from '@ohos.util' +var textDecoder = new util.textDecoder("utf-16be", {fatal : ture, ignoreBOM : false}); +var fatalStr = textDecoder.fatal(); +``` +7.readonly ignoreBOM() +``` +import util from '@ohos.util' +var textDecoder = new util.textDecoder("utf-16be", {fatal : ture, ignoreBOM : false}); +var ignoreBom = textDecoder.ignoreBOM(); +``` +8.decode() +``` +import util from '@ohos.util' +var textDecoder = new util.textDecoder("utf-16be", {fatal : ture, ignoreBOM : false}); +var result = textDecoder.decode(input, {stream : true}); +``` +9.printf() +``` +import util from '@ohos.util' +var format = "%%%o%%%i%s"; +var value = function aa(){}; +var value1 = 1.5; +var value2 = "qwer"; +var result = util.printf(format,value,value1,value2); +``` +10.getErrorString() +``` +import util from '@ohos.util' +var errnum = 13; +var result = util.getErrorString(errnum); +``` +11.callbackWrapper() +``` +import util from '@ohos.util' +async function promiseFn() { + return Promise.resolve('value'); +}; +var cb = util.callbackWrapper(promiseFn); +cb((err, ret) => { + expect(err).strictEqual(null); + expect(ret).strictEqual('value'); +}) +``` +12.promiseWrapper() +``` +import util from '@ohos.util' +function aysnFun(str1, str2, callback) { + if (typeof str1 === 'string' && typeof str1 === 'string') { + callback(null, str1 + str2); + } else { + callback('type err'); + } +} +let newPromiseObj = util.promiseWrapper(aysnFun)("Hello", 'World'); +newPromiseObj.then(res => { + expect(res).strictEqual('HelloWorld'); +}) +``` +13.encode() +``` +import util from '@ohos.util' +var that = new util.Base64(); +var array = new Uint8Array([115,49,51]); +var result = that.encode(array); +``` +14.encodeToString() +``` +import util from '@ohos.util' +var that = new util.Base64(); +var array = new Uint8Array([115,49,51]); +var result = that.encodeToString(array); +``` +15.decode() +``` +import util from '@ohos.util' +var that = new util.Base64() +var buff = 'czEz'; +var result = that.decode(buff); + +``` +16.encodeAsync() +``` +import util from '@ohos.util' +var that = new util.Base64() +var array = new Uint8Array([115,49,51]); +that.encodeAsync(array).then(val=>{ +}) +``` +17.encodeToStringAsync() +``` +import util from '@ohos.util' +var that = new util.Base64() +var array = new Uint8Array([115,49,51]); +that.encodeToStringAsync(array).then(val=>{ +}) +``` +18.decodeAsync() +``` +import util from '@ohos.util' +var that = new util.Base64() +var buff = 'czEz'; +that.decodeAsync(buff).then(val=>{ +}) +``` +19.createRationalFromString() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(0, 0); +var res = pro.createRationalFromString("-1:2"); +var result1 = res.value(); +``` +20.compareTo() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(2, 1); +var proc = new util.RationalNumber(3, 4); +var res = pro.compareTo(proc); +``` +21.equals() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(2, 1); +var proc = new util.RationalNumber(3, 4); +var res = pro.equals(proc); +``` +22.value() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(2, 1); +var res = pro.value(); +``` +23.getCommonDivisor() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(0, 0); +var res = pro.getCommonDivisor(4, 8); +``` +24.getDenominator() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(2, 1); +var res = pro.getDenominator(); +``` +25.getNumerator() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(-2, 1); +var res = pro.getNumerator(); +``` +26.isFinite() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(-2, 1); +var res = pro.isFinite(); +``` +27.isNaN() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(-2, 1); +var res = pro.isNaN(); +``` +28.isZero() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(-2, 1); +var res = pro.isZero(); + +``` +29.toString() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(-2, 1); +var res = pro.toString(); + +``` +30.updateCapacity() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +var result = pro.updateCapacity(100); +``` +31.toString() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +pro.get(2); +pro.remove(20); +var result = pro.toString(); +``` +32.values() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +pro.put(2,"anhu"); +pro.put("afaf","grfb"); +var result = pro.values(); +``` +33.size() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +pro.put(1,8); +var result = pro.size(); +``` +34.capacity() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +var result = pro.capacity(); +``` +35.clear() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +pro.clear(); +``` +36.getCreatCount() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(1,8); +var result = pro.getCreatCount(); +``` +37.getMissCount() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +pro.get(2) +var result = pro.getMissCount(); +``` +38.getRemovalCount() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +pro.updateCapacity(2); +pro.put(50,22); +var result = pro.getRemovalCount(); +``` +39.getMatchCount() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +pro.get(2); +var result = pro.getMatchCount(); +``` +40.getPutCount() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var result = pro.getPutCount(); +``` +41.isEmpty() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var result = pro.isEmpty(); +``` +42.get() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var result = pro.get(2); +``` +43.put() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +var result = pro.put(2,10); +``` +44.keys() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var result = pro.keys(); +``` +45.remove() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var result = pro.remove(20); +``` +46.contains() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var result = pro.contains(20); +``` +47.createDefault() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +var result = pro.createDefault(50); +``` +48.entries() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var result = pro.entries(); +``` +49.\[Symbol.iterator\]() + +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var result = aa[symbol.iterator](); +``` +50.afterRemoval() +``` +import util from '@ohos.util' +var arr = [ ]; +class ChildLruBuffer extends util.LruBuffer +{ + constructor() + { + super(); + } + static getInstance() + { + if(this.instance == null) + { + this.instance = new ChildLruBuffer(); + } + return this.instance; + } + afterRemoval(isEvict, key, value, newValue) + { + if (isEvict === false) + { + arr = [key, value, newValue]; + } + } +} +ChildLruBuffer.getInstance().afterRemoval(false,10,30,null) +``` +Scope接口中构造新类,实现compareTo方法。 + +``` +class Temperature { + constructor(value) { + this._temp = value; + } + compareTo(value) { + return this._temp >= value.getTemp(); + } + getTemp() { + return this._temp; + } + toString() { + return this._temp.toString(); + } +} +``` +51.constructor() +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var range = new Scope(tempLower, tempUpper); +``` +52.toString() +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var range = new Scope(tempLower, tempUpper); +var result = range.toString() // => [30,40] +``` +53.intersect() +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var range = new Scope(tempLower, tempUpper); +var tempMiDF = new Temperature(35); +var tempMidS = new Temperature(39); +var rangeFir = new Scope(tempMiDF, tempMidS); +var result = range.intersect(rangeFir) // => [35,39] +``` +54.intersect() +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var tempMiDF = new Temperature(35); +var tempMidS = new Temperature(39); +var range = new Scope(tempLower, tempUpper); +var result = range.intersect(tempMiDF, tempMidS) // => [35,39] +``` +55.getUpper() +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var range = new Scope(tempLower, tempUpper); +var result = range.getUpper() // => 40 +``` +56.getLower() +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var range = new Scope(tempLower, tempUpper); +var result = range.getLower() // => 30 +``` +57.expand() +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var tempMiDF = new Temperature(35); +var tempMidS = new Temperature(39); +var range = new Scope(tempLower, tempUpper); +var result = range.expand(tempMiDF, tempMidS) // => [30,40] +``` +58.expand() +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var tempMiDF = new Temperature(35); +var tempMidS = new Temperature(39); +var range = new Scope(tempLower, tempUpper); +var rangeFir = new Scope(tempMiDF, tempMidS); +var result = range.expand(rangeFir) // => [30,40] +``` +59.expand() +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var tempMiDF = new Temperature(35); +var range = new Scope(tempLower, tempUpper); +var result = range.expand(tempMiDF) // => [30,40] +``` +60.contains() +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var tempMiDF = new Temperature(35); +var range = new Scope(tempLower, tempUpper); +var result = range.contains(tempMiDF) // => true +``` +61.contains() +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var range = new Scope(tempLower, tempUpper); +var tempLess = new Temperature(20); +var tempMore = new Temperature(45); +var rangeSec = new Scope(tempLess, tempMore); +var result = range.contains(rangeSec) // => true +``` +62.clamp() +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var tempMiDF = new Temperature(35); +var range = new Scope(tempLower, tempUpper); +var result = range.clamp(tempMiDF) // => 35 +``` +## 相关仓 + +[js_util_module子系统](https://gitee.com/OHOS_STD/js_util_module) + +[base/compileruntime/js_util_module/](base/compileruntime/js_util_module-readme.md) + diff --git a/lrubuffer/BUILD.gn b/lrubuffer/BUILD.gn deleted file mode 100755 index 97eae7a6ca836ab85cb684b3af98dc42010ee90f..0000000000000000000000000000000000000000 --- a/lrubuffer/BUILD.gn +++ /dev/null @@ -1,59 +0,0 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/ohos.gni") -import("//build/ohos/ace/ace.gni") - -base_output_path = get_label_info(":js_lrubuffer", "target_out_dir") -js_lrubuffer_obj_path = base_output_path + "/lrubuffer.o" - -gen_js_obj("js_lrubuffer") { - input = "//base/compileruntime/js_util_module/lrubuffer/js_lrubuffer.js" - output = js_lrubuffer_obj_path -} - -ohos_shared_library("lrubuffer") { - include_dirs = [ - "//foundation/ace/napi", - "//foundation/ace/napi/native_engine", - "//third_party/icu/icu4c/source/common", - "//third_party/node/src", - "//foundation/ace/napi/interfaces/kits", - "//base/compileruntime/js_util_module/lrubuffer", - ] - - sources = [ "native_module_lrubuffer.cpp" ] - - deps = [ - ":js_lrubuffer", - "//base/compileruntime/js_util_module/lrubuffer/:js_lrubuffer", - "//foundation/ace/napi/:ace_napi", - "//foundation/ace/napi/:ace_napi_quickjs", - "//third_party/icu/icu4c:static_icuuc", - "//utils/native/base:utils", - ] - - if (is_standard_system) { - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] - } else { - external_deps = [ "hilog:libhilog" ] - } - subsystem_name = "ccruntime" - part_name = "jsapi_util" - - relative_install_dir = "module" -} - -group("lrubuffer_packages") { - deps = [ ":lrubuffer" ] -} diff --git a/lrubuffer/js_lrubuffer.js b/lrubuffer/js_lrubuffer.js deleted file mode 100755 index 71a4752da1ba1649253907ff8cbaa8951cce30bf..0000000000000000000000000000000000000000 --- a/lrubuffer/js_lrubuffer.js +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the 'License'); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an 'AS IS' BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -'use strict'; -class LruBuffer { - constructor(capacity) { - this.maxSize = 64; - this.putCount = 0; - this.createCount = 0; - this.evictionCount = 0; - this.hitCount = 0; - this.missCount = 0; - if (capacity !== undefined) { - if (capacity <= 0) { - throw new Error('data error'); - } - this.maxSize = capacity; - } - this.cache = new Map(); - } - updateCapacity(newCapacity) { - if (newCapacity <= 0) { - throw new Error('data error'); - } - else if (this.cache.size > newCapacity) { - this.changeCapacity(newCapacity); - } - this.maxSize = newCapacity; - } - get(key) { - if (key === null) { - throw new Error('key search failed'); - } - let value; - if (this.cache.has(key)) { - value = this.cache.get(key); - this.hitCount++; - this.cache.delete(key); - this.cache.set(key, value); - return value; - } - this.missCount++; - let createValue = this.createDefault(key); - if (createValue === undefined) { - return undefined; - } - else { - value = this.put(key, createValue); - this.createCount++; - if (value !== null) { - this.put(key, value); - this.afterRemoval(false, key, createValue, value); - return value; - } - return createValue; - } - } - put(key, value) { - if (key === null || value === null) { - throw new Error('key or value search failed'); - } - let former; - this.putCount++; - if (this.cache.has(key)) { - former = this.cache.get(key); - this.cache.delete(key); - this.afterRemoval(false, key, former, null); - } - else if (this.cache.size >= this.maxSize) { - this.cache.delete(this.cache.keys().next().value); - this.evictionCount++; - } - this.cache.set(key, value); - return former; - } - getCreatCount() { - return this.createCount; - } - getMissCount() { - return this.missCount; - } - getRemovalCount() { - return this.evictionCount; - } - getMatchCount() { - return this.hitCount; - } - getPutCount() { - return this.putCount; - } - capacity() { - return this.maxSize; - } - size() { - return this.cache.size; - } - clear() { - this.cache.clear(); - this.afterRemoval(false, this.cache.keys(), this.cache.values(), null); - } - isEmpty() { - let temp = false; - if (this.cache.size === 0) { - temp = true; - } - return temp; - } - contains(key) { - let flag = false; - if (this.cache.has(key)) { - flag = true; - let value; - this.hitCount++; - value = this.cache.get(key); - this.cache.delete(key); - this.cache.set(key, value); - return flag; - } - this.missCount++; - return flag; - } - remove(key) { - if (key === null) { - throw new Error('key search failed'); - } - else if (this.cache.has(key)) { - let former; - former = this.cache.get(key); - this.cache.delete(key); - if (former !== null) { - this.afterRemoval(false, key, former, null); - return former; - } - } - return undefined; - } - toString() { - let peek = 0; - let hitRate = 0; - peek = this.hitCount + this.missCount; - if (peek !== 0) { - hitRate = 100 * this.hitCount / peek; - } - else { - hitRate = 0; - } - let str = ''; - str = 'Lrubuffer[ maxSize = ' + this.maxSize + ', hits = ' + this.hitCount + ', misses = ' + this.missCount - + ', hitRate = ' + hitRate + '% ]'; - return str; - } - values() { - let arr = []; - for (let value of this.cache.values()) { - arr.push(value); - } - return arr; - } - keys() { - let arr = []; - for (let key of this.cache.keys()) { - arr.push(key); - } - return arr; - } - afterRemoval(isEvict, key, value, newValue) { - } - createDefault(key) { - return undefined; - } - changeCapacity(newCapacity) { - while (this.cache.size > newCapacity) { - this.cache.delete(this.cache.keys().next().value); - this.evictionCount++; - this.afterRemoval(true, this.cache.keys(), this.cache.values(), null); - } - } -} -export default { - LruBuffer: LruBuffer, -}; diff --git a/lrubuffer/native_module_lrubuffer.cpp b/lrubuffer/native_module_lrubuffer.cpp deleted file mode 100755 index cbd5a66d1938fc2c22e49218d64f54f0cf3d90dc..0000000000000000000000000000000000000000 --- a/lrubuffer/native_module_lrubuffer.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include - -#include "napi/native_api.h" -#include "napi/native_node_api.h" - -static napi_value LruBufferInit(napi_env env, napi_value exports) -{ - const char *lruBufferClassName = "lrubuffer"; - napi_value lruBufferClass = nullptr; - NAPI_CALL(env, napi_define_class(env, lruBufferClassName, strlen(lruBufferClassName), nullptr, - nullptr, 0, nullptr, &lruBufferClass)); - static napi_property_descriptor desc[] = { - DECLARE_NAPI_PROPERTY("lrubuffer", lruBufferClass), - }; - napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); - return exports; -} - -// lrubuffer module define -static napi_module lrubufferModule = { - .nm_version = 1, - .nm_flags = 0, - .nm_filename = nullptr, - .nm_register_func = LruBufferInit, - .nm_modname = "lrubuffer", - .nm_priv = ((void*)0), - .reserved = { 0 }, -}; - -extern "C" __attribute__ ((constructor)) void RegisterModule() -{ - napi_module_register(&lrubufferModule); -} - -// lrubuffer JS register -extern "C" -__attribute__((visibility("default"))) void NAPI_lrubuffer_GetJSCode(const char **buf, int *buflen) -{ - extern const char _binary_js_lrubuffer_js_start[]; - extern const char _binary_js_lrubuffer_js_end[]; - if (buf != nullptr) { - *buf = _binary_js_lrubuffer_js_start; - } - if (buflen != nullptr) { - *buflen = _binary_js_lrubuffer_js_end - _binary_js_lrubuffer_js_start; - } -} \ No newline at end of file diff --git a/ohos.build b/ohos.build index b49feec8679cc7adc16bafbe5249ce644cd6b65f..e5737bd24e47b197bb6bce8f9b9cc367ff4e96dd 100755 --- a/ohos.build +++ b/ohos.build @@ -7,9 +7,7 @@ "phone" ], "module_list": [ - "//base/compileruntime/js_util_module/util:util_packages", - "//base/compileruntime/js_util_module/scope:scope_packages", - "//base/compileruntime/js_util_module/lrubuffer:lrubuffer_packages" + "//base/compileruntime/js_util_module/util:util_packages" ], "inner_kits": [ ], diff --git a/scope/native_module_scope.cpp b/scope/native_module_scope.cpp deleted file mode 100755 index 3dd9411a1ce81ca5d7b2e28cda20943076047c92..0000000000000000000000000000000000000000 --- a/scope/native_module_scope.cpp +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include - -#include "napi/native_api.h" -#include "napi/native_node_api.h" - -static napi_value ScopeInit(napi_env env, napi_value exports) -{ - const char *ClassName = "scope"; - napi_value scopeClass = nullptr; - NAPI_CALL(env, napi_define_class(env, ClassName, strlen(ClassName), nullptr, - nullptr, 0, nullptr, &scopeClass)); - static napi_property_descriptor desc[] = { - DECLARE_NAPI_PROPERTY("scope", scopeClass) - }; - napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); - return exports; -} - -// Scope module define -static napi_module scopeModule = { - .nm_version = 1, - .nm_flags = 0, - .nm_filename = nullptr, - .nm_register_func = ScopeInit, - .nm_modname = "scope", - .nm_priv = ((void*)0), - .reserved = {0}, -}; - -// Scope module register -extern "C" -__attribute__((constructor)) void RegisterModule() -{ - napi_module_register(&scopeModule); -} - -// Scope JS register -extern "C" -__attribute__((visibility("default"))) void NAPI_scope_GetJSCode(const char **buf, int *buflen) -{ - extern const char _binary_scope_js_js_start[]; - extern const char _binary_scope_js_js_end[]; - if (buf != nullptr) { - *buf = _binary_scope_js_js_start; - } - if (buflen != nullptr) { - *buflen = _binary_scope_js_js_end - _binary_scope_js_js_start; - } -} \ No newline at end of file diff --git a/scope/scope_js.js b/scope/scope_js.js deleted file mode 100755 index c93eec79e4932d70788547ecae6d60e85d03254c..0000000000000000000000000000000000000000 --- a/scope/scope_js.js +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -class Scope { - constructor(lowerObj, upperObj) { - this.lowerObj = lowerObj; - this.upperObj = upperObj; - this.checkNull(lowerObj, 'lower limit not be null'); - this.checkNull(upperObj, 'upper limit not be null'); - if (lowerObj.compareTo(upperObj)) { - throw new Error('lower limit must be less than or equal to upper limit'); - } - this._lowerLimit = lowerObj; - this._upperLimit = upperObj; - } - - getLower() { - return this._lowerLimit; - } - - getUpper() { - return this._upperLimit; - } - - contains(x) { - let resLower; - let resUpper; - this.checkNull(x, 'value must not be null'); - if (x instanceof Scope) { - resLower = x._lowerLimit.compareTo(this._lowerLimit); - resUpper = this._upperLimit.compareTo(x._upperLimit); - } else { - resLower = x.compareTo(this._lowerLimit); - resUpper = this._upperLimit.compareTo(x); - } - return resLower && resUpper; - } - - clamp(value) { - this.checkNull(value, 'value must not be null'); - if (!value.compareTo(this._lowerLimit)) { - return this._lowerLimit; - } else if (value.compareTo(this._upperLimit)) { - return this._upperLimit; - } else { - return value; - } - } - - intersect(x, y) { - let reLower; - let reUpper; - let mLower; - let mUpper; - if (y) { - this.checkNull(x, 'lower limit must not be null'); - this.checkNull(y, 'upper limit must not be null'); - reLower = this._lowerLimit.compareTo(x); - reUpper = y.compareTo(this._upperLimit); - if (reLower && reUpper) { - return this; - } else { - mLower = reLower ? this._lowerLimit : x; - mUpper = reUpper ? this._upperLimit : y; - return new Scope(mLower, mUpper); - } - } else { - this.checkNull(x, 'scope must not be null'); - reLower = this._lowerLimit.compareTo(x._lowerLimit); - reUpper = x._upperLimit.compareTo(this._upperLimit); - if (!reLower && !reUpper) { - return x; - } else if (reLower && reUpper) { - return this; - } else { - mLower = reLower ? this._lowerLimit : x._lowerLimit; - mUpper = reUpper ? this._upperLimit : x._upperLimit; - return new Scope(mLower, mUpper); - } - } - } - - expand(x, y) { - let reLower; - let reUpper; - let mLower; - let mUpper; - if (!y) { - this.checkNull(x, 'value must not be null'); - if (!(x instanceof Scope)) { - this.checkNull(x, 'value must not be null'); - return this.expand(x, x); - } - let reLower = x._lowerLimit.compareTo(this._lowerLimit); - let reUpper = this._upperLimit.compareTo(x._upperLimit); - if (reLower && reUpper) { - return this; - } else if (!reLower && !reUpper) { - return x; - } else { - let mLower = reLower ? this._lowerLimit : x._lowerLimit; - let mUpper = reUpper ? this._upperLimit : x._upperLimit; - return new Scope(mLower, mUpper); - } - } - else { - this.checkNull(x, 'lower limit must not be null'); - this.checkNull(y, 'upper limit must not be null'); - let reLower = x.compareTo(this._lowerLimit); - let reUpper = this._upperLimit.compareTo(y); - if (reLower && reUpper) { - return this; - } - let mLower = reLower ? this._lowerLimit : x; - let mUpper = reUpper ? this._upperLimit : y; - return new Scope(mLower, mUpper); - } - } - - toString() { - let strLower = this._lowerLimit.toString(); - let strUpper = this._upperLimit.toString(); - return `[${strLower}, ${strUpper}]`; - } - - checkNull(o, str) { - if (o == null) { - throw new Error(str); - } - } -} - -export default { - Scope: Scope, -}; \ No newline at end of file diff --git a/test/unittest/test_util.cpp b/test/unittest/test_util.cpp index 00ee99790ff76a669375db0a0c9a73ae806596c6..af2dbbf5dadbd77c2a369fd3bb30561093d6424e 100755 --- a/test/unittest/test_util.cpp +++ b/test/unittest/test_util.cpp @@ -93,7 +93,7 @@ HWTEST_F(NativeEngineTest, textEncodeTest001, testing::ext::TestSize.Level0) env, result, &type, &srcLength, &srcData, &srcBuffer, &byteOffset); ASSERT_EQ(srcLength, 6); - char* res = (char*)srcData; + char* res = reinterpret_cast(srcData); res[srcLength] = 0; ASSERT_STREQ(res, excepted); @@ -193,7 +193,7 @@ HWTEST_F(NativeEngineTest, GetEncoding001, testing::ext::TestSize.Level0) size_t strLength = 0; char* buffer = nullptr; if (bufferSize > 0) { - buffer = new char[bufferSize + 1]{ 0 }; + buffer = new char[bufferSize + 1](); napi_get_value_string_utf8(env, testString, buffer, bufferSize + 1, &strLength); } const char *result = tmpTestStr.c_str(); diff --git a/util/BUILD.gn b/util/BUILD.gn index ea5e47e21e07ea1bba26b2c1a3c2082e3ac36a00..7a16da96baaf3e2c9c6f70a8b52bf532714bf400 100755 --- a/util/BUILD.gn +++ b/util/BUILD.gn @@ -11,15 +11,59 @@ # See the License for the specific language governing permissions and # limitations under the License. +import("//ark/ts2abc/ts2panda/ts2abc_config.gni") import("//build/ohos.gni") import("//build/ohos/ace/ace.gni") +import("//foundation/ace/ace_engine/ace_config.gni") +# compile .ts to .js. +action("build_ts_js") { + script = "//base/compileruntime/js_util_module/util/build_ts_js.py" + depfile = "$target_gen_dir/$target_name.d" + outputs = [target_out_dir + "/util_js.js" + ] +} base_output_path = get_label_info(":util_js", "target_out_dir") util_js_obj_path = base_output_path + "/util.o" gen_js_obj("util_js") { - input = "//base/compileruntime/js_util_module/util/util_js.js" + input = "$target_out_dir/util_js.js" output = util_js_obj_path + dep = ":build_ts_js" +} + +# compile .js to .abc. +action("gen_util_abc") { + visibility = [ ":*" ] + script = "//ark/ts2abc/ts2panda/scripts/generate_js_bytecode.py" + + args = [ + "--src-js", + rebase_path(target_out_dir + "/util_js.js"), + "--dst-file", + rebase_path(target_out_dir + "/util.abc"), + "--node", + rebase_path("${node_path}"), + "--frontend-tool-path", + rebase_path("${ts2abc_build_path}"), + "--node-modules", + rebase_path("${node_modules}"), + ] + deps = [ "//ark/ts2abc/ts2panda:ark_ts2abc_build" , + ":build_ts_js" ] + + inputs = [ target_out_dir + "/util_js.js" ] + outputs = [ target_out_dir + "/util.abc" ] +} + + + +abc_output_path = get_label_info(":util_abc", "target_out_dir") +util_abc_obj_path = abc_output_path + "/util_abc.o" +gen_js_obj("util_abc") { + input = "$target_out_dir/util.abc" + output = util_abc_obj_path + dep = ":gen_util_abc" } ohos_shared_library("util") { @@ -34,13 +78,13 @@ ohos_shared_library("util") { sources = [ "js_base64.cpp", - "js_rational.cpp", "js_textdecoder.cpp", "js_textencoder.cpp", "native_module_util.cpp", ] deps = [ + ":util_abc", ":util_js", "//base/compileruntime/js_util_module/util/:util_js", "//foundation/ace/napi/:ace_napi", diff --git a/scope/BUILD.gn b/util/build_ts_js.py similarity index 33% rename from scope/BUILD.gn rename to util/build_ts_js.py index 81b858000701adc0902d743d43cfba01b0cb88a9..a48b9653813c17123d066f7ccb1cb3acec9e0b27 100755 --- a/scope/BUILD.gn +++ b/util/build_ts_js.py @@ -1,3 +1,5 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- # Copyright (c) 2021 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -10,50 +12,18 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - -import("//build/ohos.gni") -import("//build/ohos/ace/ace.gni") - -base_output_path = get_label_info(":scope_js", "target_out_dir") -scope_js_obj_path = base_output_path + "/scope.o" - -gen_js_obj("scope_js") { - input = "//base/compileruntime/js_util_module/scope/scope_js.js" - output = scope_js_obj_path -} - -ohos_shared_library("scope") { - include_dirs = [ - "//foundation/ace/napi", - "//foundation/ace/napi/native_engine", - "//third_party/icu/icu4c/source/common", - "//third_party/node/src", - "//foundation/ace/napi/interfaces/kits", - "//base/compileruntime/js_util_module/scope", - ] - - sources = [ "native_module_scope.cpp" ] - - deps = [ - ":scope_js", - "//base/compileruntime/js_util_module/scope/:scope_js", - "//foundation/ace/napi/:ace_napi", - "//foundation/ace/napi/:ace_napi_quickjs", - "//third_party/icu/icu4c:static_icuuc", - "//utils/native/base:utils", - ] - - if (is_standard_system) { - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] - } else { - external_deps = [ "hilog:libhilog" ] - } - subsystem_name = "ccruntime" - part_name = "jsapi_util" - - relative_install_dir = "module" -} - -group("scope_packages") { - deps = [ ":scope" ] -} +import os + +if __name__ == '__main__': + + build_path = os.path.abspath(os.path.join(os.getcwd(), "../..")) + os.chdir("%s/base/compileruntime/js_util_module/util" % build_path) + os.system('../../../../developtools/ace-ets2bundle/compiler/node_modules/typescript/bin/tsc') + + if os.access("../../../../out/ohos-arm64-release", os.F_OK): + os.system('cp -r ./out/util_js.js ../../../../out/ohos-arm64-release/obj/base/compileruntime/js_util_module/util/util_js.js') + + if os.access("../../../../out/ohos-arm-release", os.F_OK): + os.system('cp -r ./out/util_js.js ../../../../out/ohos-arm-release/obj/base/compileruntime/js_util_module/util/util_js.js') + + os.system('rm -rf ./out') \ No newline at end of file diff --git a/util/js_base64.cpp b/util/js_base64.cpp index 475bb727ad6ef0141b25946515f04009f18540ab..4581bb471cc22ac2f36cf319033ec0cb77451f4f 100755 --- a/util/js_base64.cpp +++ b/util/js_base64.cpp @@ -28,23 +28,18 @@ namespace OHOS::Util { static const size_t TRAGET_FOUR = 4; static const size_t TRAGET_SIX = 6; static const size_t TRAGET_EIGHT = 8; - const char base[] = { + static const size_t TRAGET_SIXTYFIVE = 65; + const char BASE[] = { 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, 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, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43, 47, 61 }; - const char base0[] = { - 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, 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, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 45, 95, 61 - }; } Base64::Base64(napi_env env_) : env(env_) {} /* base64 encode */ - napi_value Base64::Encode(napi_value src, napi_value flags) + napi_value Base64::Encode(napi_value src) { napi_typedarray_type type; size_t byteOffset = 0; @@ -52,12 +47,8 @@ namespace OHOS::Util { void *resultData = nullptr; napi_value resultBuffer = nullptr; NAPI_CALL(env, napi_get_typedarray_info(env, src, &type, &length, &resultData, &resultBuffer, &byteOffset)); - inputEncode = static_cast(resultData) + byteOffset; - int32_t iflag = 0; - NAPI_CALL(env, napi_get_value_int32(env, flags, &iflag)); - size_t flag = 0; - flag = static_cast(iflag); - const unsigned char *rets = EncodeAchieve(inputEncode, length, flag); + inputEncode_ = static_cast(resultData) + byteOffset; + const unsigned char *rets = EncodeAchieve(inputEncode_, length); void *data = nullptr; napi_value arrayBuffer = nullptr; size_t bufferSize = outputLen; @@ -74,7 +65,7 @@ namespace OHOS::Util { } /* base64 encodeToString */ - napi_value Base64::EncodeToString(napi_value src, napi_value flags) + napi_value Base64::EncodeToString(napi_value src) { napi_typedarray_type type; size_t byteOffset = 0; @@ -82,43 +73,22 @@ namespace OHOS::Util { void *resultData = nullptr; napi_value resultBuffer = nullptr; NAPI_CALL(env, napi_get_typedarray_info(env, src, &type, &length, &resultData, &resultBuffer, &byteOffset)); - inputEncode = static_cast(resultData) + byteOffset; - int32_t iflag = 0; - NAPI_CALL(env, napi_get_value_int32(env, flags, &iflag)); - size_t flag = 0; - flag = static_cast(iflag); - unsigned char *ret = EncodeAchieve(inputEncode, length, flag); - char *rstring = nullptr; - if (outputLen > 0) { - rstring = new char[outputLen + 1]; - if (memset_s(rstring, outputLen + 1, '\0', outputLen + 1) != 0) { - FreeMemory(ret); - FreeMemory(rstring); - napi_throw_error(env, "-1", "decode rstring memset_s failed"); - } - } else { - napi_throw_error(env, "-2", "outputLen is error !"); - } - for (size_t i = 0; i < outputLen; i++) { - rstring[i] = char(ret[i]); - } - std::string finalString = rstring; - const char *outString = finalString.c_str(); - const char *encString = static_cast(outString); + inputEncode_ = static_cast(resultData) + byteOffset; + unsigned char *ret = EncodeAchieve(inputEncode_, length); + const char *encString = reinterpret_cast(ret); napi_value resultStr = nullptr; NAPI_CALL(env, napi_create_string_utf8(env, encString, strlen(encString), &resultStr)); FreeMemory(ret); - FreeMemory(rstring); return resultStr; } - unsigned char *Base64::EncodeAchieve(const unsigned char *input, size_t inputLen, size_t iflag) + unsigned char *Base64::EncodeAchieve(const unsigned char *input, size_t inputLen) { size_t inp = 0; size_t temp = 0; size_t bitWise = 0; unsigned char *ret = nullptr; - unsigned char *bosom = nullptr; + size_t index = 0; outputLen = (inputLen / TRAGET_THREE) * TRAGET_FOUR; if ((inputLen % TRAGET_THREE) > 0) { outputLen += TRAGET_FOUR; @@ -132,7 +102,6 @@ namespace OHOS::Util { } else { napi_throw_error(env, "-2", "outputLen is error !"); } - bosom = ret; while (inp < inputLen) { temp = 0; bitWise = 0; @@ -146,24 +115,19 @@ namespace OHOS::Util { } bitWise = (bitWise << ((TRAGET_THREE - temp) * TRAGET_EIGHT)); for (size_t i = 0; i < TRAGET_FOUR; i++) { - if (temp < i && iflag == 0) { - *bosom = base[BIT_FLG]; - } else if (temp < i && iflag != 0) { - *bosom = base0[BIT_FLG]; - } else if (temp >= i && iflag == 0) { - *bosom = base[(bitWise >> ((TRAGET_THREE - i) * TRAGET_SIX)) & SIXTEEN_FLG]; - } else if (temp >= i && iflag != 0) { - *bosom = base0[(bitWise >> ((TRAGET_THREE - i) * TRAGET_SIX)) & SIXTEEN_FLG]; + if (temp < i) { + ret[index++] = BASE[BIT_FLG]; + } else if (temp >= i) { + ret[index++] = BASE[(bitWise >> ((TRAGET_THREE - i) * TRAGET_SIX)) & SIXTEEN_FLG]; } - bosom++; } } - *bosom = '\0'; + ret[index] = 0; return ret; } /* base64 decode */ - napi_value Base64::Decode(napi_value src, napi_value flags) + napi_value Base64::Decode(napi_value src) { napi_valuetype valuetype = napi_undefined; napi_typeof(env, src, &valuetype); @@ -176,10 +140,6 @@ namespace OHOS::Util { if (valuetype != napi_valuetype::napi_string) { NAPI_CALL(env, napi_get_typedarray_info(env, src, &type, &length, &resultData, &resultBuffer, &byteOffset)); } - int32_t iflag = 0; - NAPI_CALL(env, napi_get_value_int32(env, flags, &iflag)); - size_t flag = 0; - flag = static_cast(iflag); if (valuetype == napi_valuetype::napi_string) { size_t prolen = 0; napi_get_value_string_utf8(env, src, nullptr, 0, &prolen); @@ -193,10 +153,10 @@ namespace OHOS::Util { napi_throw_error(env, "-2", "prolen is error !"); } napi_get_value_string_utf8(env, src, inputString, prolen + 1, &prolen); - pret = DecodeAchieve(inputString, prolen, flag); + pret = DecodeAchieve(inputString, prolen); } else if (type == napi_typedarray_type::napi_uint8_array) { - inputDecode = static_cast(resultData) + byteOffset; - pret = DecodeAchieve(inputDecode, length, flag); + inputDecode_ = static_cast(resultData) + byteOffset; + pret = DecodeAchieve(inputDecode_, length); } void *data = nullptr; napi_value arrayBuffer = nullptr; @@ -215,12 +175,12 @@ namespace OHOS::Util { return result; } - unsigned char *Base64::DecodeAchieve(const char *input, size_t inputLen, size_t iflag) + unsigned char *Base64::DecodeAchieve(const char *input, size_t inputLen) { retLen = (inputLen / TRAGET_FOUR) * TRAGET_THREE; decodeOutLen = retLen; size_t equalCount = 0; - unsigned char *bosom = nullptr; + size_t index = 0; size_t inp = 0; size_t temp = 0; size_t bitWise = 0; @@ -243,7 +203,6 @@ namespace OHOS::Util { } else { napi_throw_error(env, "-2", "retLen is error !"); } - bosom = retDecode; while (inp < (inputLen - equalCount)) { temp = 0; bitWise = 0; @@ -251,7 +210,7 @@ namespace OHOS::Util { if (inp >= (inputLen - equalCount)) { break; } - bitWise = (bitWise << TRAGET_SIX) | (Finds(input[inp], iflag)); + bitWise = (bitWise << TRAGET_SIX) | (Finds(input[inp])); inp++; temp++; } @@ -260,11 +219,10 @@ namespace OHOS::Util { if (i == temp) { break; } - *bosom = static_cast((bitWise >> ((TRAGET_TWO - i) * TRAGET_EIGHT)) & XFF_FLG); - bosom++; + retDecode[index++] = static_cast((bitWise >> ((TRAGET_TWO - i) * TRAGET_EIGHT)) & XFF_FLG); } } - *bosom = '\0'; + retDecode[index] = 0; return retDecode; } @@ -295,22 +253,13 @@ namespace OHOS::Util { } /* Decoding lookup function */ - size_t Base64::Finds(char ch, size_t iflag) + size_t Base64::Finds(char ch) { size_t couts = 0; - if (iflag == 0) { // 65:Number of elements in the encoding table. - for (size_t i = 0; i < 65; i++) { - if (base[i] == ch) { - couts = i; - } - } - } else { - // 65:Number of elements in the encoding table. - for (size_t i = 0; i < 65; i++) { - if (base0[i] == ch) { - couts = i; - } + for (size_t i = 0; i < 65; i++) { + if (BASE[i] == ch) { + couts = i; } } return couts; @@ -333,4 +282,316 @@ namespace OHOS::Util { temp = nullptr; } } -} \ No newline at end of file + + napi_value Base64::EncodeAsync(napi_value src) + { + napi_typedarray_type type; + size_t byteOffset = 0; + size_t length = 0; + void *resultData = nullptr; + napi_value resultBuffer = nullptr; + NAPI_CALL(env, napi_get_typedarray_info(env, src, &type, &length, &resultData, &resultBuffer, &byteOffset)); + unsigned char *inputEncode = nullptr; + inputEncode = static_cast(resultData) + byteOffset; + CreateEncodePromise(inputEncode, length); + return stdEncodeInfo_->promise; + } + + napi_value Base64::EncodeToStringAsync(napi_value src) + { + napi_typedarray_type type; + size_t byteOffset = 0; + size_t length = 0; + void *resultData = nullptr; + napi_value resultBuffer = nullptr; + NAPI_CALL(env, napi_get_typedarray_info(env, src, &type, &length, &resultData, &resultBuffer, &byteOffset)); + unsigned char *inputEncode = nullptr; + inputEncode = static_cast(resultData) + byteOffset; + CreateEncodeToStringPromise(inputEncode, length); + return stdEncodeInfo_->promise; + } + + void Base64::CreateEncodePromise(unsigned char *inputDecode, size_t length) + { + napi_value resourceName = nullptr; + stdEncodeInfo_ = new EncodeInfo(); + stdEncodeInfo_->sinputEncode = inputDecode; + stdEncodeInfo_->slength = length; + stdEncodeInfo_->env = env; + napi_create_promise(env, &stdEncodeInfo_->deferred, &stdEncodeInfo_->promise); + napi_create_string_utf8(env, "ReadStdEncode", NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work(env, nullptr, resourceName, ReadStdEncode, EndStdEncode, + reinterpret_cast(stdEncodeInfo_), &stdEncodeInfo_->worker); + napi_queue_async_work(env, stdEncodeInfo_->worker); + } + + void Base64::CreateEncodeToStringPromise(unsigned char *inputDecode, size_t length) + { + napi_value resourceName = nullptr; + stdEncodeInfo_ = new EncodeInfo(); + stdEncodeInfo_->sinputEncode = inputDecode; + stdEncodeInfo_->slength = length; + napi_create_promise(env, &stdEncodeInfo_->deferred, &stdEncodeInfo_->promise); + napi_create_string_utf8(env, "ReadStdEncodeToString", NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work(env, nullptr, resourceName, ReadStdEncodeToString, EndStdEncodeToString, + reinterpret_cast(stdEncodeInfo_), &stdEncodeInfo_->worker); + napi_queue_async_work(env, stdEncodeInfo_->worker); + } + + unsigned char *EncodeAchieves(EncodeInfo *encodeInfo) + { + const unsigned char *input = encodeInfo->sinputEncode; + size_t inputLen = encodeInfo->slength; + size_t inp = 0; + size_t temp = 0; + size_t bitWise = 0; + unsigned char *ret = nullptr; + size_t index = 0; + size_t outputLen = 0; + outputLen = (inputLen / TRAGET_THREE) * TRAGET_FOUR; + if ((inputLen % TRAGET_THREE) > 0) { + outputLen += TRAGET_FOUR; + } + encodeInfo->soutputLen = outputLen; + if (outputLen > 0) { + ret = new unsigned char[outputLen + 1]; + if (memset_s(ret, outputLen + 1, '\0', outputLen + 1) != 0) { + napi_throw_error(encodeInfo->env, "-1", "ret path memset_s failed"); + } + } else { + napi_throw_error(encodeInfo->env, "-2", "outputLen is error !"); + } + while (inp < inputLen) { + temp = 0; + bitWise = 0; + while (temp < TRAGET_THREE) { + if (inp >= inputLen) { + break; + } + bitWise = ((bitWise << TRAGET_EIGHT) | (input[inp] & XFF_FLG)); + inp++; + temp++; + } + bitWise = (bitWise << ((TRAGET_THREE - temp) * TRAGET_EIGHT)); + for (size_t i = 0; i < TRAGET_FOUR; i++) { + if (temp < i) { + ret[index++] = BASE[BIT_FLG]; + } else if (temp >= i) { + ret[index++] = BASE[(bitWise >> ((TRAGET_THREE - i) * TRAGET_SIX)) & SIXTEEN_FLG]; + } + } + } + ret[index] = 0; + return ret; + } + + void Base64::ReadStdEncode(napi_env env, void *data) + { + auto stdEncodeInfo = reinterpret_cast(data); + unsigned char *rets = EncodeAchieves(stdEncodeInfo); + stdEncodeInfo->sinputEncoding = rets; + } + + void Base64::EndStdEncode(napi_env env, napi_status status, void *buffer) + { + auto stdEncodeInfo = reinterpret_cast(buffer); + void *data = nullptr; + napi_value arrayBuffer = nullptr; + size_t bufferSize = stdEncodeInfo->soutputLen; + napi_create_arraybuffer(env, bufferSize, &data, &arrayBuffer); + if (memcpy_s(data, bufferSize, reinterpret_cast(stdEncodeInfo->sinputEncoding), bufferSize) != 0) { + HILOG_ERROR("copy ret to arraybuffer error"); + napi_delete_async_work(env, stdEncodeInfo->worker); + return; + } + napi_value result = nullptr; + napi_create_typedarray(env, napi_uint8_array, bufferSize, arrayBuffer, 0, &result); + napi_resolve_deferred(env, stdEncodeInfo->deferred, result); + napi_delete_async_work(env, stdEncodeInfo->worker); + delete[] stdEncodeInfo->sinputEncoding; + delete stdEncodeInfo; + } + + void Base64::ReadStdEncodeToString(napi_env env, void *data) + { + auto stdEncodeInfo = reinterpret_cast(data); + unsigned char *rets = EncodeAchieves(stdEncodeInfo); + stdEncodeInfo->sinputEncoding = rets; + } + + void Base64::EndStdEncodeToString(napi_env env, napi_status status, void *buffer) + { + auto stdEncodeInfo = reinterpret_cast(buffer); + const char *encString = reinterpret_cast(stdEncodeInfo->sinputEncoding); + napi_value resultStr = nullptr; + napi_create_string_utf8(env, encString, strlen(encString), &resultStr); + napi_resolve_deferred(env, stdEncodeInfo->deferred, resultStr); + napi_delete_async_work(env, stdEncodeInfo->worker); + delete[] stdEncodeInfo->sinputEncoding; + delete stdEncodeInfo; + } + + napi_value Base64::DecodeAsync(napi_value src) + { + napi_valuetype valuetype = napi_undefined; + napi_typeof(env, src, &valuetype); + napi_typedarray_type type; + size_t byteOffset = 0; + size_t length = 0; + void *resultData = nullptr; + napi_value resultBuffer = nullptr; + char *inputString = nullptr; + char *inputDecode = nullptr; + if (valuetype != napi_valuetype::napi_string) { + NAPI_CALL(env, napi_get_typedarray_info(env, src, &type, &length, &resultData, &resultBuffer, &byteOffset)); + } + if (valuetype == napi_valuetype::napi_string) { + size_t prolen = 0; + napi_get_value_string_utf8(env, src, nullptr, 0, &prolen); + if (prolen > 0) { + inputString = new char[prolen + 1]; + if (memset_s(inputString, prolen + 1, '\0', prolen + 1) != 0) { + napi_throw_error(env, "-1", "decode inputString memset_s failed"); + } + } else { + napi_throw_error(env, "-2", "prolen is error !"); + } + napi_get_value_string_utf8(env, src, inputString, prolen+1, &prolen); + CreateDecodePromise(inputString, prolen); + } else if (type == napi_typedarray_type::napi_uint8_array) { + inputDecode = static_cast(resultData) + byteOffset; + CreateDecodePromise(inputDecode, length); + } + delete[] inputString; + return stdDecodeInfo_->promise; + } + + void Base64::CreateDecodePromise(char *inputDecode, size_t length) + { + napi_value resourceName = nullptr; + stdDecodeInfo_ = new DecodeInfo(); + stdDecodeInfo_->sinputDecode = inputDecode; + stdDecodeInfo_->slength = length; + stdDecodeInfo_->env = env; + napi_create_promise(env, &stdDecodeInfo_->deferred, &stdDecodeInfo_->promise); + napi_create_string_utf8(env, "ReadStdDecode", NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work(env, nullptr, resourceName, ReadStdDecode, EndStdDecode, + reinterpret_cast(stdDecodeInfo_), &stdDecodeInfo_->worker); + napi_queue_async_work(env, stdDecodeInfo_->worker); + } + + /* Decoding lookup function */ + size_t Finds(char ch) + { + size_t couts = 0; + for (size_t i = 0; i < TRAGET_SIXTYFIVE; i++) { + if (BASE[i] == ch) { + couts = i; + } + } + return couts; + } + + size_t DecodeOut(size_t equalCount, size_t retLen, DecodeInfo *decodeInfo) + { + if (equalCount == 1) { + decodeInfo->decodeOutLen -= 1; + } + if (equalCount == TRAGET_TWO) { + decodeInfo->decodeOutLen -= TRAGET_TWO; + } + switch (equalCount) { + case 0: + retLen += TRAGET_FOUR; + break; + case 1: + retLen += TRAGET_FOUR; + break; + case TRAGET_TWO: + retLen += TRAGET_THREE; + break; + default: + retLen += TRAGET_TWO; + break; + } + return retLen; + } + + unsigned char *DecodeAchieves(DecodeInfo *decodeInfo) + { + const char *input = decodeInfo->sinputDecode; + size_t inputLen = decodeInfo->slength; + size_t retLen = 0; + retLen = (inputLen / TRAGET_FOUR) * TRAGET_THREE; + decodeInfo->decodeOutLen = retLen; + size_t equalCount = 0; + size_t inp = 0; + size_t temp = 0; + size_t bitWise = 0; + size_t index = 0; + unsigned char *retDecode = nullptr; + if (*(input + inputLen - 1) == '=') { + equalCount++; + } + if (*(input + inputLen - TRAGET_TWO) == '=') { + equalCount++; + } + retLen = DecodeOut(equalCount, retLen, decodeInfo); + if (retLen > 0) { + retDecode = new unsigned char[retLen + 1]; + if (memset_s(retDecode, retLen + 1, '\0', retLen + 1) != 0) { + napi_throw_error(decodeInfo->env, "-1", "decode retDecode memset_s failed"); + } + } else { + napi_throw_error(decodeInfo->env, "-2", "retLen is error !"); + } + while (inp < (inputLen - equalCount)) { + temp = 0; + bitWise = 0; + while (temp < TRAGET_FOUR) { + if (inp >= (inputLen - equalCount)) { + break; + } + bitWise = (bitWise << TRAGET_SIX) | (Finds(input[inp])); + inp++; + temp++; + } + bitWise = bitWise << ((TRAGET_FOUR - temp) * TRAGET_SIX); + for (size_t i = 0; i < TRAGET_THREE; i++) { + if (i == temp) { + break; + } + retDecode[index++] = static_cast((bitWise >> ((TRAGET_TWO - i) * TRAGET_EIGHT)) & XFF_FLG); + } + } + retDecode[index] = 0; + return retDecode; + } + + void Base64::ReadStdDecode(napi_env env, void *data) + { + auto stdDecodeInfo = reinterpret_cast(data); + unsigned char *rets = DecodeAchieves(stdDecodeInfo); + stdDecodeInfo->sinputDecoding = rets; + } + + void Base64::EndStdDecode(napi_env env, napi_status status, void *buffer) + { + auto stdDecodeInfo = reinterpret_cast(buffer); + void *data = nullptr; + napi_value arrayBuffer = nullptr; + size_t bufferSize = stdDecodeInfo->decodeOutLen; + napi_create_arraybuffer(env, bufferSize, &data, &arrayBuffer); + if (memcpy_s(data, bufferSize, reinterpret_cast(stdDecodeInfo->sinputDecoding), bufferSize) != 0) { + HILOG_ERROR("copy ret to arraybuffer error"); + napi_delete_async_work(env, stdDecodeInfo->worker); + return; + } + napi_value result = nullptr; + napi_create_typedarray(env, napi_uint8_array, bufferSize, arrayBuffer, 0, &result); + napi_resolve_deferred(env, stdDecodeInfo->deferred, result); + napi_delete_async_work(env, stdDecodeInfo->worker); + delete[] stdDecodeInfo->sinputDecoding; + delete stdDecodeInfo; + } +} diff --git a/util/js_base64.h b/util/js_base64.h index ff0ce011b2d43e4520b807b6216317cddf3686e2..44de67b2323e0b532dd22201557965e3bd34de5d 100755 --- a/util/js_base64.h +++ b/util/js_base64.h @@ -23,24 +23,54 @@ #define BASE_COMPILERUNTIME_JS_UTIL_MODULE_BASE64_CLASS_H namespace OHOS::Util { + struct EncodeInfo { + napi_async_work worker = nullptr; + napi_deferred deferred = nullptr; + napi_value promise = nullptr; + unsigned char *sinputEncode = nullptr; + unsigned char *sinputEncoding = nullptr; + size_t slength = 0; + size_t soutputLen = 0; + napi_env env; + }; + + struct DecodeInfo { + napi_async_work worker = nullptr; + napi_deferred deferred = nullptr; + napi_value promise = nullptr; + char *sinputDecode = nullptr; + unsigned char *sinputDecoding = nullptr; + size_t slength = 0; + size_t decodeOutLen = 0; + size_t retLen = 0; + napi_env env; + }; + + enum ConverterFlags { + BIT_FLG = 0x40, + SIXTEEN_FLG = 0x3F, + XFF_FLG = 0xFF, + }; + + unsigned char *EncodeAchieves(EncodeInfo *encodeInfo); + unsigned char *DecodeAchieves(DecodeInfo *decodeInfo); + class Base64 { - public: - enum ConverterFlags { - BIT_FLG = 0x40, - SIXTEEN_FLG = 0x3F, - XFF_FLG = 0xFF, - }; public: explicit Base64(napi_env env); virtual ~Base64(){} - napi_value Encode(napi_value src, napi_value flags); - napi_value EncodeToString(napi_value src, napi_value flags); - napi_value Decode(napi_value src, napi_value flags); + napi_value Encode(napi_value src); + napi_value EncodeToString(napi_value src); + napi_value Decode(napi_value src); + + napi_value EncodeAsync(napi_value src); + napi_value EncodeToStringAsync(napi_value src); + napi_value DecodeAsync(napi_value src); private: napi_env env; - unsigned char *DecodeAchieve(const char *input, size_t inputLen, size_t iflag); - unsigned char *EncodeAchieve(const unsigned char *input, size_t inputLen, size_t iflag); - size_t Finds(char ch, size_t iflag); + unsigned char *DecodeAchieve(const char *input, size_t inputLen); + unsigned char *EncodeAchieve(const unsigned char *input, size_t inputLen); + size_t Finds(char ch); size_t DecodeOut(size_t equalCount, size_t retLen); void FreeMemory(const unsigned char *address); void FreeMemory(const char *address); @@ -48,9 +78,21 @@ namespace OHOS::Util { size_t decodeOutLen = 0; size_t outputLen = 0; unsigned char *pret = nullptr; - const unsigned char *inputEncode = nullptr; - const char *inputDecode = nullptr; + const unsigned char *inputEncode_ = nullptr; + const char *inputDecode_ = nullptr; unsigned char *retDecode = nullptr; + + void CreateEncodePromise(unsigned char *inputDecode, size_t length); + void CreateEncodeToStringPromise(unsigned char *inputDecode, size_t length); + void CreateDecodePromise(char *inputDecode, size_t length); + EncodeInfo *stdEncodeInfo_ = nullptr; + DecodeInfo *stdDecodeInfo_ = nullptr; + static void ReadStdEncode(napi_env env, void *data); + static void EndStdEncode(napi_env env, napi_status status, void *buffer); + static void ReadStdEncodeToString(napi_env env, void *data); + static void EndStdEncodeToString(napi_env env, napi_status status, void *buffer); + static void ReadStdDecode(napi_env env, void *data); + static void EndStdDecode(napi_env env, napi_status status, void *buffer); }; } #endif \ No newline at end of file diff --git a/util/js_rational.cpp b/util/js_rational.cpp deleted file mode 100755 index 544974093abcc367e4cef881437451d8956f49da..0000000000000000000000000000000000000000 --- a/util/js_rational.cpp +++ /dev/null @@ -1,328 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "js_rational.h" -#include -#include -#include -#include "utils/log.h" -#include "securec.h" -namespace OHOS::Util { - RationalNumber::RationalNumber(napi_env env, int molecule, int denominator) - { - env_ = env; - napi_value result = nullptr; - int num = molecule; - int den = denominator; - num = den < 0 ? num * (-1) : num; - den = den < 0 ? den * (-1) : den; - if (den == 0) { - if (num > 0) { - mnum = 1; - mden = 0; - } else if (num < 0) { - mnum = -1; - mden = 0; - } else { - mnum = 0; - mden = 0; - } - } else if (num == 0) { - mnum = 0; - mden = 1; - } else { - napi_value num1 = nullptr; - napi_value num2 = nullptr; - napi_create_int32(env_, num, &num1); - napi_create_int32(env_, den, &num2); - result = GetCommonDivisor(num1, num2); - int gnum = 0; - napi_get_value_int32(env_, result, &gnum); - if (gnum != 0) { - mnum = num / gnum; - mden = den / gnum; - } - } - } - - napi_value RationalNumber::CreateRationalFromString(napi_value str, napi_value RationalNumberClass) const - { - size_t len = 0; - int flag = 0; - napi_get_value_string_utf8(env_, str, nullptr, 0, &len); - char *buffer = nullptr; - if (len > 0) { - buffer = new char[len + 1]; - if (memset_s(buffer, len + 1, '\0', len + 1) != 0) { - napi_throw_error(env_, "-1", "memset_s failed"); - } - } else { - napi_throw_error(env_, "NullPointerException", "string must not be null!"); - } - napi_get_value_string_utf8(env_, str, buffer, len + 1, &len); - std::string buf = ""; - if (buffer != nullptr) { - buf = buffer; - delete []buffer; - buffer = nullptr; - } - if (buf.compare("NaN") == 0) { - return CreateObj(0, 0, RationalNumberClass); - } - size_t colon = buf.find(':'); - size_t semicolon = buf.find('/'); - if ((colon == std::string::npos && semicolon == std::string::npos) - || (colon != std::string::npos && semicolon != std::string::npos)) { - napi_throw_error(env_, "invalidRational", "string invalid!"); - } - size_t index = (colon != std::string::npos) ? colon : semicolon; - std::string s1 = buf.substr(0, index); - std::string s2 = buf.substr(index + 1, buf.size()); - for (int i = 1; i < s1.size(); i++) { - if (((s1[0] == '+') || (s1[0] == '-') || (isdigit(s1[0]))) && (isdigit(s1[i]))) { - flag = 1; - } else { - napi_throw_error(env_, "invalidRational", "string invalid!"); - } - } - int num1 = stoi(s1) * flag; - for (int i = 1; i < s2.size(); i++) { - if (((s2[0] == '+') || (s2[0] == '-') || (isdigit(s2[0]))) && (isdigit(s2[i]))) { - flag = 1; - } else { - napi_throw_error(env_, "invalidRational", "string invalid!"); - } - } - int num2 = stoi(s2) * flag; - return CreateObj(num1, num2, RationalNumberClass); - } - - napi_value RationalNumber::CreateObj(int num1, int num2, napi_value RationalNumberClass) const - { - napi_value argvs[2] = { nullptr }; - NAPI_CALL(env_, napi_create_int32(env_, num1, &argvs[0])); - NAPI_CALL(env_, napi_create_int32(env_, num2, &argvs[1])); - size_t argc = 2; - napi_value res = nullptr; - NAPI_CALL(env_, napi_new_instance(env_, RationalNumberClass, argc, argvs, &res)); - return res; - } - - napi_value RationalNumber::CompareTo(napi_value rational) const - { - RationalNumber *other = nullptr; - NAPI_CALL(env_, napi_unwrap(env_, rational, reinterpret_cast(&other))); - if (mnum == other->mnum && mden == other->mden) { - napi_value result = nullptr; - NAPI_CALL(env_, napi_create_int32(env_, 0, &result)); - return result; - } else if (mnum == 0 && mden == 0) { - napi_value result = nullptr; - NAPI_CALL(env_, napi_create_int32(env_, 1, &result)); - return result; - } else if ((other->mnum == 0) && (other->mden == 0)) { - napi_value result = nullptr; - NAPI_CALL(env_, napi_create_int32(env_, -1, &result)); - return result; - } else if ((mden == 0 && mnum > 0) || (other->mden == 0 && other->mnum < 0)) { - napi_value result = nullptr; - NAPI_CALL(env_, napi_create_int32(env_, 1, &result)); - return result; - } else if ((mden == 0 && mnum < 0) || (other->mden == 0 && other->mnum > 0)) { - napi_value result = nullptr; - NAPI_CALL(env_, napi_create_int32(env_, -1, &result)); - return result; - } - long thisnum = static_cast(mnum) * other->mden; - long othernum = static_cast(other->mnum) * mden; - if (thisnum < othernum) { - napi_value result = nullptr; - NAPI_CALL(env_, napi_create_int32(env_, -1, &result)); - return result; - } else if (thisnum > othernum) { - napi_value result = nullptr; - NAPI_CALL(env_, napi_create_int64(env_, 1, &result)); - return result; - } else { - napi_value result = nullptr; - NAPI_CALL(env_, napi_create_int32(env_, 0, &result)); - return result; - } - } - - napi_value RationalNumber::Equals(napi_value obj) const - { - RationalNumber *object = nullptr; - napi_status status = napi_unwrap(env_, obj, reinterpret_cast(&object)); - bool flag = false; - long thisnum = static_cast(mnum) * object->mden; - long objnum = static_cast(object->mnum) * mden; - if (status != napi_ok) { - napi_value result = nullptr; - NAPI_CALL(env_, napi_get_boolean(env_, flag, &result)); - return result; - } - if (mnum == object->mnum && mden == object->mden) { - flag = true; - napi_value result = nullptr; - NAPI_CALL(env_, napi_get_boolean(env_, flag, &result)); - return result; - } else if ((thisnum == objnum) && (mnum != 0 && mden != 0) && (object->mnum != 0 && object->mden != 0)) { - flag = true; - napi_value result = nullptr; - NAPI_CALL(env_, napi_get_boolean(env_, flag, &result)); - return result; - } else if ((mnum == 0 && mden != 0) && (object->mnum == 0 && object->mden != 0)) { - flag = true; - napi_value result = nullptr; - NAPI_CALL(env_, napi_get_boolean(env_, flag, &result)); - return result; - } else if ((mnum > 0 && mden == 0) && (object->mnum > 0 && object->mden == 0)) { - flag = true; - napi_value result = nullptr; - NAPI_CALL(env_, napi_get_boolean(env_, flag, &result)); - return result; - } else if ((mnum < 0 && mden == 0) && (object->mnum < 0 && object->mden == 0)) { - flag = true; - napi_value result = nullptr; - NAPI_CALL(env_, napi_get_boolean(env_, flag, &result)); - return result; - } else { - napi_value result = nullptr; - NAPI_CALL(env_, napi_get_boolean(env_, flag, &result)); - return result; - } - } - - napi_value RationalNumber::Value() const - { - if (mnum > 0 && mden == 0) { - napi_value result = nullptr; - NAPI_CALL(env_, napi_create_int32(env_, INT_MAX, &result)); - return result; - } else if (mnum < 0 && mden == 0) { - napi_value result = nullptr; - NAPI_CALL(env_, napi_create_int32(env_, INT_MIN, &result)); - return result; - } else if ((mnum == 0) && (mden == 0)) { - napi_value result = nullptr; - NAPI_CALL(env_, napi_create_int32(env_, 0, &result)); - return result; - } else { - if (mnum % mden == 0) { - int val = mnum / mden; - napi_value result = nullptr; - NAPI_CALL(env_, napi_create_int32(env_, val, &result)); - return result; - } else { - double num = mnum; - double den = mden; - double res = num / den; - napi_value result = nullptr; - NAPI_CALL(env_, napi_create_double(env_, res, &result)); - return result; - } - } - } - - napi_value RationalNumber::GetCommonDivisor(napi_value num1, napi_value num2) const - { - int temp = 0; - int number1 = 0; - int number2 = 0; - napi_get_value_int32(env_, num1, &number1); - napi_get_value_int32(env_, num2, &number2); - if (number1 == 0 || number2 == 0) { - napi_throw_error(env_, "invalidnumber", "Parameter cannot be zero!"); - } - if (number1 < number2) { - temp = number1; - number1 = number2; - number2 = temp; - } - while (number1 % number2 != 0) { - temp = number1 % number2; - number1 = number2; - number2 = temp; - } - napi_value result = nullptr; - NAPI_CALL(env_, napi_create_int32(env_, number2, &result)); - return result; - } - - napi_value RationalNumber::GetDenominator() const - { - napi_value result = nullptr; - NAPI_CALL(env_, napi_create_int32(env_, mden, &result)); - return result; - } - - napi_value RationalNumber::GetNumerator() const - { - napi_value result = nullptr; - NAPI_CALL(env_, napi_create_int32(env_, mnum, &result)); - return result; - } - - napi_value RationalNumber::IsFinite() const - { - bool flag = false; - if (mden != 0) { - flag = true; - } - napi_value result = nullptr; - NAPI_CALL(env_, napi_get_boolean(env_, flag, &result)); - return result; - } - - napi_value RationalNumber::IsNaN() const - { - bool flag = false; - if ((mnum == 0) && (mden == 0)) { - flag = true; - } - napi_value result = nullptr; - NAPI_CALL(env_, napi_get_boolean(env_, flag, &result)); - return result; - } - - napi_value RationalNumber::IsZero() const - { - bool flag = false; - if ((mnum == 0) && (mden != 0)) { - flag = true; - } - napi_value result = nullptr; - NAPI_CALL(env_, napi_get_boolean(env_, flag, &result)); - return result; - } - - napi_value RationalNumber::ToString() const - { - std::string buf; - if (mnum == 0 && mden == 0) { - buf = "NaN"; - } else if (mnum > 0 && mden == 0) { - buf = "Infinity"; - } else if (mnum < 0 && mden == 0) { - buf = "-Infinity"; - } else { - buf = std::to_string(mnum) + "/" + std::to_string(mden); - } - napi_value res = nullptr; - napi_create_string_utf8(env_, buf.c_str(), buf.size(), &res); - return res; - } -} \ No newline at end of file diff --git a/util/js_rational.h b/util/js_rational.h deleted file mode 100755 index 8e6f022940d668b2e0d6d43f633342e688a66f62..0000000000000000000000000000000000000000 --- a/util/js_rational.h +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef BASE_COMPILERUNTIME_JS_UTIL_MODULE_RATIONALNUMBER_CLASS_H -#define BASE_COMPILERUNTIME_JS_UTIL_MODULE_RATIONALNUMBER_CLASS_H - -#include - -#include "napi/native_api.h" -#include "napi/native_node_api.h" -namespace OHOS::Util { - class RationalNumber { - public: - explicit RationalNumber(napi_env env, int numerator, int denominator); - virtual ~RationalNumber(){} - napi_value CreateRationalFromString(napi_value str, napi_value RationalNumberClass) const; - napi_value CompareTo(napi_value rational) const; - napi_value Equals(napi_value obj) const; - napi_value Value() const; - napi_value GetCommonDivisor(napi_value num1, napi_value num2) const; - napi_value GetDenominator() const; - napi_value GetNumerator() const; - napi_value IsFinite() const; - napi_value IsNaN() const; - napi_value IsZero() const; - napi_value ToString() const; - private: - int mnum = 0; - int mden = 0; - napi_env env_; - napi_value CreateObj(int num1, int num2, napi_value RationalNumberClass) const; - }; -} -#endif \ No newline at end of file diff --git a/util/js_textdecoder.cpp b/util/js_textdecoder.cpp index 8f38672f9318202954338916cc9c0d714d36fd5f..05e574f3c095cd75c38b02eff1330dc7e5729f39 100755 --- a/util/js_textdecoder.cpp +++ b/util/js_textdecoder.cpp @@ -88,7 +88,7 @@ namespace OHOS::Util { return nullptr; } UChar *target = arr; - size_t tarStartPos = (intptr_t)arr; + size_t tarStartPos = reinterpret_cast(arr); ucnv_toUnicode(GetConverterPtr(), &target, target + len, &source, source + length, nullptr, flush, &codeFlag); size_t resultLength = 0; bool omitInitialBom = false; @@ -179,7 +179,7 @@ namespace OHOS::Util { } if (U_SUCCESS(codeFlag)) { if (decArr.limitLen > 0) { - rstLen = (intptr_t)decArr.target - decArr.tarStartPos; + rstLen = reinterpret_cast(decArr.target) - decArr.tarStartPos; if (rstLen > 0 && IsUnicode() && !IsIgnoreBom() && !IsBomFlag()) { bomFlag = (arr[0] == 0xFEFF) ? true : false; label_ |= static_cast(ConverterFlags::BOM_SEEN_FLG); diff --git a/util/native_module_util.cpp b/util/native_module_util.cpp index dea60e780d6be783a4e98779869a23819f43f9ba..e16c369ff0d935dff59565027f374f753d4df45a 100755 --- a/util/native_module_util.cpp +++ b/util/native_module_util.cpp @@ -18,7 +18,6 @@ #include "js_textdecoder.h" #include "js_textencoder.h" -#include "js_rational.h" #include "js_base64.h" #include "napi/native_api.h" @@ -27,9 +26,10 @@ extern const char _binary_util_js_js_start[]; extern const char _binary_util_js_js_end[]; +extern const char _binary_util_abc_start[]; +extern const char _binary_util_abc_end[]; namespace OHOS::Util { static std::string temp = "cdfijoOs"; - napi_value RationalNumberClass = nullptr; static std::string DealWithPrintf(const std::string &format, const std::vector &value) { size_t i = 0; @@ -451,192 +451,6 @@ namespace OHOS::Util { return result; } - static napi_value RationalNumberConstructor(napi_env env, napi_callback_info info) - { - napi_value thisVar = nullptr; - void *data = nullptr; - size_t argc = 3; - napi_value args[2] = { nullptr }; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, &data)); - int num = 0; - int den = 0; - napi_get_value_int32(env, args[0], &num); - napi_get_value_int32(env, args[1], &den); - auto objectInfo = new RationalNumber(env, num, den); - NAPI_CALL(env, napi_wrap( - env, thisVar, objectInfo, - [](napi_env env, void *data, void *hint) { - auto objInfo = (RationalNumber*)data; - if (objInfo != nullptr) { - delete objInfo; - } - }, - nullptr, nullptr)); - return thisVar; - } - - static napi_value CreateRationalFromString(napi_env env, napi_callback_info info) - { - napi_value thisVar = nullptr; - size_t requireArgc = 1; - size_t argc = 1; - napi_value args = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &args, &thisVar, nullptr)); - NAPI_ASSERT(env, argc >= requireArgc, "Wrong nuamber of arguments"); - napi_valuetype valuetype; - NAPI_CALL(env, napi_typeof(env, args, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected"); - RationalNumber *object = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&object)); - if (RationalNumberClass == nullptr) { - napi_throw_error(env, "NullException", "RationalNumberClass must not be null!"); - } - return object->CreateRationalFromString(args, RationalNumberClass); - } - - static napi_value CompareTo(napi_env env, napi_callback_info info) - { - napi_value thisVar = nullptr; - size_t requireArgc = 1; - size_t argc = 1; - napi_value args = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &args, &thisVar, nullptr)); - NAPI_ASSERT(env, argc >= requireArgc, "Wrong nuamber of arguments"); - RationalNumber *object = nullptr; - napi_unwrap(env, thisVar, (void**)&object); - return object->CompareTo(args); - } - - static napi_value Equals(napi_env env, napi_callback_info info) - { - napi_value thisVar = nullptr; - size_t requireArgc = 1; - size_t argc = 1; - napi_value args = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &args, &thisVar, nullptr)); - NAPI_ASSERT(env, argc >= requireArgc, "Wrong nuamber of arguments"); - RationalNumber *object = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&object)); - return object->Equals(args); - } - - static napi_value Value(napi_env env, napi_callback_info info) - { - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); - RationalNumber *object = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&object)); - return object->Value(); - } - - static napi_value GetCommonDivisor(napi_env env, napi_callback_info info) - { - size_t argc = 2; - napi_value argv[2] = {0}; - napi_value thisVar = nullptr; - void *data = nullptr; - napi_value args = nullptr; - napi_get_cb_info(env, info, &argc, argv, &thisVar, &data); - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &args, &thisVar, nullptr)); - napi_valuetype valuetype1; - napi_valuetype valuetype2; - NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype1)); - NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype2)); - NAPI_ASSERT(env, valuetype1 == napi_number, "Wrong argument type. String expected"); - NAPI_ASSERT(env, valuetype2 == napi_number, "Wrong argument type. String expected"); - RationalNumber *object = nullptr; - napi_unwrap(env, thisVar, (void**)&object); - napi_value result = nullptr; - result = object->GetCommonDivisor(argv[0], argv[1]); - return result; - } - - static napi_value GetDenominator(napi_env env, napi_callback_info info) - { - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); - RationalNumber *object = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&object)); - napi_value result = object->GetDenominator(); - return result; - } - - static napi_value GetNumerator(napi_env env, napi_callback_info info) - { - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); - RationalNumber *object = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&object)); - napi_value result = object->GetNumerator(); - return result; - } - - static napi_value IsFinite(napi_env env, napi_callback_info info) - { - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); - RationalNumber *object = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&object)); - napi_value result = object->IsFinite(); - return result; - } - - static napi_value IsNaN(napi_env env, napi_callback_info info) - { - napi_value thisVar = nullptr; - napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); - RationalNumber *object = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&object)); - napi_value result = object->IsNaN(); - return result; - } - static napi_value IsZero(napi_env env, napi_callback_info info) - { - napi_value thisVar = nullptr; - napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); - RationalNumber *object = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&object)); - napi_value result = object->IsZero(); - return result; - } - - static napi_value ToString(napi_env env, napi_callback_info info) - { - napi_value thisVar = nullptr; - napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); - RationalNumber *object = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&object)); - napi_value result = object->ToString(); - return result; - } - - static napi_value RationalNumberInit(napi_env env, napi_value exports) - { - const char *RationalNumberClassName = "RationalNumber"; - static napi_property_descriptor RationalNumberDesc[] = { - DECLARE_NAPI_FUNCTION("createRationalFromString", CreateRationalFromString), - DECLARE_NAPI_FUNCTION("compareTo", CompareTo), - DECLARE_NAPI_FUNCTION("equals", Equals), - DECLARE_NAPI_FUNCTION("value", Value), - DECLARE_NAPI_FUNCTION("getCommonDivisor", GetCommonDivisor), - DECLARE_NAPI_FUNCTION("getDenominator", GetDenominator), - DECLARE_NAPI_FUNCTION("getNumerator", GetNumerator), - DECLARE_NAPI_FUNCTION("isFinite", IsFinite), - DECLARE_NAPI_FUNCTION("isNaN", IsNaN), - DECLARE_NAPI_FUNCTION("isZero", IsZero), - DECLARE_NAPI_FUNCTION("toString", ToString), - }; - NAPI_CALL(env, napi_define_class(env, RationalNumberClassName, strlen(RationalNumberClassName), - RationalNumberConstructor, nullptr, - sizeof(RationalNumberDesc) / sizeof(RationalNumberDesc[0]), - RationalNumberDesc, &RationalNumberClass)); - static napi_property_descriptor desc[] = { - DECLARE_NAPI_PROPERTY("RationalNumber", RationalNumberClass) - }; - NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); - return exports; - } - static napi_value TextcoderInit(napi_env env, napi_value exports) { const char *textEncoderClassName = "TextEncoder"; @@ -694,9 +508,9 @@ namespace OHOS::Util { static napi_value EncodeBase64(napi_env env, napi_callback_info info) { napi_value thisVar = nullptr; - size_t requireArgc = 2; - size_t argc = 2; - napi_value args[2] = { nullptr }; + size_t requireArgc = 1; + size_t argc = 1; + napi_value args[1] = { nullptr }; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr)); NAPI_ASSERT(env, argc >= requireArgc, "Wrong number of arguments"); napi_typedarray_type valuetype0; @@ -705,22 +519,19 @@ namespace OHOS::Util { napi_value arraybuffer = nullptr; size_t byteOffset = 0; NAPI_CALL(env, napi_get_typedarray_info(env, args[0], &valuetype0, &length, &data, &arraybuffer, &byteOffset)); - napi_valuetype valuetype1; - NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1)); NAPI_ASSERT(env, valuetype0 == napi_uint8_array, "Wrong argument type. napi_uint8_array expected."); - NAPI_ASSERT(env, valuetype1 == napi_number, "Wrong argument type. Nmuber expected."); Base64 *object = nullptr; NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&object)); - napi_value result = object->Encode(args[0], args[1]); + napi_value result = object->Encode(args[0]); return result; } static napi_value EncodeToString(napi_env env, napi_callback_info info) { napi_value thisVar = nullptr; - size_t requireArgc = 2; - size_t argc = 2; - napi_value args[2] = { nullptr }; + size_t requireArgc = 1; + size_t argc = 1; + napi_value args[1] = { nullptr }; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr)); NAPI_ASSERT(env, argc >= requireArgc, "Wrong number of arguments"); napi_typedarray_type valuetype0; @@ -729,22 +540,19 @@ namespace OHOS::Util { napi_value arraybuffer = nullptr; size_t byteOffset = 0; NAPI_CALL(env, napi_get_typedarray_info(env, args[0], &valuetype0, &length, &data, &arraybuffer, &byteOffset)); - napi_valuetype valuetype1; - NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1)); NAPI_ASSERT(env, valuetype0 == napi_uint8_array, "Wrong argument type. napi_uint8_array expected."); - NAPI_ASSERT(env, valuetype1 == napi_number, "Wrong argument type. Nmuber expected."); Base64 *object = nullptr; NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&object)); - napi_value result = object->EncodeToString(args[0], args[1]); + napi_value result = object->EncodeToString(args[0]); return result; } static napi_value DecodeBase64(napi_env env, napi_callback_info info) { napi_value thisVar = nullptr; - size_t requireArgc = 2; - size_t argc = 2; - napi_value args[2] = { nullptr }; + size_t requireArgc = 1; + size_t argc = 1; + napi_value args[1] = { nullptr }; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr)); NAPI_ASSERT(env, argc >= requireArgc, "Wrong number of arguments"); napi_typedarray_type valuetype0; @@ -761,12 +569,79 @@ namespace OHOS::Util { if ((valuetype1 != napi_valuetype::napi_string) && (valuetype0 != napi_typedarray_type::napi_uint8_array)) { napi_throw_error(env, nullptr, "The parameter type is incorrect"); } - napi_valuetype valuetype2; - NAPI_CALL(env, napi_typeof(env, args[1], &valuetype2)); - NAPI_ASSERT(env, valuetype2 == napi_number, "Wrong argument type. Nmuber expected."); Base64 *object = nullptr; NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&object)); - napi_value result = object->Decode(args[0], args[1]); + napi_value result = object->Decode(args[0]); + return result; + } + + static napi_value EncodeAsync(napi_env env, napi_callback_info info) + { + napi_value thisVar = nullptr; + size_t requireArgc = 1; + size_t argc = 1; + napi_value args[1] = { nullptr }; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr)); + NAPI_ASSERT(env, argc >= requireArgc, "Wrong number of arguments"); + napi_typedarray_type valuetype0; + size_t length = 0; + void *data = nullptr; + napi_value arraybuffer = nullptr; + size_t byteOffset = 0; + NAPI_CALL(env, napi_get_typedarray_info(env, args[0], &valuetype0, &length, &data, &arraybuffer, &byteOffset)); + NAPI_ASSERT(env, valuetype0 == napi_uint8_array, "Wrong argument type. napi_uint8_array expected."); + Base64 *object = nullptr; + NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&object)); + napi_value result = object->EncodeAsync(args[0]); + return result; + } + + static napi_value EncodeToStringAsync(napi_env env, napi_callback_info info) + { + napi_value thisVar = nullptr; + size_t requireArgc = 1; + size_t argc = 1; + napi_value args[1] = { nullptr }; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr)); + NAPI_ASSERT(env, argc >= requireArgc, "Wrong number of arguments"); + napi_typedarray_type valuetype0; + size_t length = 0; + void *data = nullptr; + napi_value arraybuffer = nullptr; + size_t byteOffset = 0; + NAPI_CALL(env, napi_get_typedarray_info(env, args[0], &valuetype0, &length, &data, &arraybuffer, &byteOffset)); + NAPI_ASSERT(env, valuetype0 == napi_uint8_array, "Wrong argument type. napi_uint8_array expected."); + Base64 *object = nullptr; + NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&object)); + napi_value result = object->EncodeToStringAsync(args[0]); + return result; + } + + static napi_value DecodeAsync(napi_env env, napi_callback_info info) + { + napi_value thisVar = nullptr; + size_t requireArgc = 1; + size_t argc = 1; + napi_value args[1] = { nullptr }; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr)); + NAPI_ASSERT(env, argc >= requireArgc, "Wrong number of arguments"); + napi_typedarray_type valuetype0; + napi_valuetype valuetype1; + size_t length = 0; + void *data = nullptr; + napi_value arraybuffer = nullptr; + size_t byteOffset = 0; + NAPI_CALL(env, napi_typeof(env, args[0], &valuetype1)); + if (valuetype1 != napi_valuetype::napi_string) { + NAPI_CALL(env, napi_get_typedarray_info(env, args[0], &valuetype0, + &length, &data, &arraybuffer, &byteOffset)); + } + if ((valuetype1 != napi_valuetype::napi_string) && (valuetype0 != napi_typedarray_type::napi_uint8_array)) { + napi_throw_error(env, nullptr, "The parameter type is incorrect"); + } + Base64 *object = nullptr; + NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&object)); + napi_value result = object->DecodeAsync(args[0]); return result; } @@ -778,6 +653,9 @@ namespace OHOS::Util { DECLARE_NAPI_FUNCTION("encode", EncodeBase64), DECLARE_NAPI_FUNCTION("encodeToString", EncodeToString), DECLARE_NAPI_FUNCTION("decode", DecodeBase64), + DECLARE_NAPI_FUNCTION("encodeAsync", EncodeAsync), + DECLARE_NAPI_FUNCTION("encodeToStringAsync", EncodeToStringAsync), + DECLARE_NAPI_FUNCTION("decodeAsync", DecodeAsync), }; NAPI_CALL(env, napi_define_class(env, base64ClassName, strlen(base64ClassName), Base64Constructor, nullptr, sizeof(base64Desc) / sizeof(base64Desc[0]), base64Desc, @@ -798,7 +676,6 @@ namespace OHOS::Util { }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); TextcoderInit(env, exports); - RationalNumberInit(env, exports); Base64Init(env, exports); return exports; } @@ -832,4 +709,14 @@ namespace OHOS::Util { *buflen = _binary_util_js_js_end - _binary_util_js_js_start; } } + extern "C" + __attribute__((visibility("default"))) void NAPI_util_GetABCCode(const char** buf, int* buflen) + { + if (buf != nullptr) { + *buf = _binary_util_abc_start; + } + if (buflen != nullptr) { + *buflen = _binary_util_abc_end - _binary_util_abc_start; + } + } } \ No newline at end of file diff --git a/util/util_js.js b/util/src/util_js.ts old mode 100755 new mode 100644 similarity index 39% rename from util/util_js.js rename to util/src/util_js.ts index f3ce3a0a334c7dfb5f341f3af4e50c8592bfd9c6..589662fe003d774dab66dbc495d8504fe5ccb5bf --- a/util/util_js.js +++ b/util/src/util_js.ts @@ -1,437 +1,966 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -const helpUtil = requireInternal('util'); -let TextEncoder = helpUtil.TextEncoder; -let TextDecoder = helpUtil.TextDecoder; -let RationalNumber = helpUtil.RationalNumber; -let Base64 = helpUtil.Base64; - -function switchLittleObject(enter, obj, count) -{ - var str = ''; - if (obj === null) { - str += obj; - } else if (obj instanceof Array) { - str += '[ ' + arrayToString(enter, obj, count) + '[length]: ' + obj.length + ' ]'; - } else if (typeof obj === 'function') { - str += '{ [Function: ' + obj.name + ']' + enter - + '[length]: ' + obj.length + ',' + enter - + '[name] :\'' + obj.name + '\',' + enter - + '[prototype]: ' + obj.name + ' { [constructor]: [Circular] } }'; - } else if (typeof obj === 'object') { - str += '{ '; - var i = 0; - for (i in obj) { - str += switchLittleValue(enter, i, obj, count); - } - if (i === 0) { - return obj; - } - str = str.substr(0, str.length - enter.length - 1); - str += ' }'; - } else if (typeof obj === 'string') { - str += '\'' + obj + '\''; - } else { - str += obj; - } - return str; -} - -function switchLittleValue(enter, protoName, obj, count) -{ - var str = ''; - if (obj[protoName] === null) { - str += protoName + ': null,' + enter; - } else if (obj[protoName] instanceof Array) { - str += protoName + ':' + enter - + '[ ' + arrayToString(enter + ' ', obj[protoName], count) + '[length]: ' - + obj[protoName].length + ' ],' + enter; - } else if (typeof obj[protoName] === 'object') { - if (obj[protoName] === obj) { - str += protoName + ': [Circular]' + enter; - } else { - str += protoName + ':' + enter; - str += switchLittleObject(enter + ' ', obj[protoName], count + 1) + ',' + enter; - } - } else if (typeof obj[protoName] === 'function') { - var space = enter; - if (obj[protoName].name !== '') { - str += obj[protoName].name + ':' + space; - } - space += ' '; - str += '{ [Function: ' + obj[protoName].name + ']' + space - + '[length]: ' + obj[protoName].length + ',' + space - + '[name] :\'' + obj[protoName].name + '\',' + space - + '[prototype]: ' + obj[protoName].name - + ' { [constructor]: [Circular] } },' + enter; - } else { - if (typeof obj[protoName] === 'string') { - str += protoName + ': \'' + obj[protoName] + '\',' + enter; - } else { - str += protoName + ': ' + obj[protoName] + ',' + enter; - } - } - return str; -} - -function arrayToString(enter, arr, count) -{ - var str = ''; - if (!arr.length) { - return ''; - } - var i = 0; - var arrayEnter = ', '; - for (i in arr) { - if (arr[i] !== null && (typeof arr[i] === 'function' || typeof arr[i] === 'object') && count <= 2) { - arrayEnter += enter; - break; - } - } - i = 0; - for (i in arr) { - if (typeof arr[i] === 'string') { - str += '\'' + arr[i].toString() + '\'' + arrayEnter; - } else if (typeof arr[i] === 'object') { - str += switchLittleObject(enter + ' ', arr[i], count + 1); - str += arrayEnter; - } else if (typeof arr[i] === 'function') { - var space = enter; - space += ' '; - var end = ''; - if (arr[i].name !== '') { - str += '{ [Function: ' + arr[i].name + ']' + space; - end = arr[i].name + ' { [constructor]: [Circular] } }' + arrayEnter; - } else { - str += '{ [Function]' + space; - end = '{ [constructor]: [Circular] } }' + arrayEnter; - } - str += '[length]: ' - + arr[i].length + ',' + space - + '[name] :\'' + arr[i].name + '\',' + space - + '[prototype]: ' + end; - } else { - str += arr[i] + arrayEnter; - } - } - return str; -} - -function switchBigObject(enter, obj, count) -{ - var str = ''; - if (obj === null) { - str += obj; - } else if (obj instanceof Array) { - str += '[ ' + arrayToBigString(enter, obj, count) + ' ]'; - } else if (typeof obj === 'function') { - str += '{ [Function: ' + obj.name + '] }'; - } else if (typeof obj === 'object') { - str += '{ '; - var i = 0; - for (i in obj) { - str += switchBigValue(enter, i, obj, count); - } - if (i === 0) { - return obj; - } - str = str.substr(0, str.length - enter.length - 1); - str += ' }'; - } else if (typeof obj === 'string') { - str += '\'' + obj + '\''; - } else { - str += obj; - } - return str; -} - -function switchBigValue(enter, protoName, obj, count) -{ - var str = ''; - if (obj[protoName] === null) { - str += protoName + ': null,' + enter; - } else if (obj[protoName] instanceof Array) { - str += protoName + ':' + enter - + '[ ' + arrayToBigString(enter + ' ', obj[protoName], count) + ' ],' + enter; - } else if (typeof obj[protoName] === 'object') { - if (obj[protoName] === obj) { - str += protoName + ': [Circular]' + enter; - } else { - str += protoName + ':' + enter; - str += switchBigObject(enter + ' ', obj[protoName], count + 1) + ',' + enter; - } - } else if (typeof obj[protoName] === 'function') { - if (obj[protoName].name !== '') { - str += obj[protoName].name + ': '; - } - str += '[Function: ' + obj[protoName].name + '],' + enter; - } else { - if (typeof obj[protoName] === 'string') { - str += protoName + ': \'' + obj[protoName] + '\',' + enter; - } else { - str += protoName + ': ' + obj[protoName] + ',' + enter; - } - } - return str; -} - -function arrayToBigString(enter, arr, count) -{ - var str = ''; - if (!arr.length) { - return ''; - } - var i = 0; - var arrayEnter = ', '; - for (i in arr) { - if (arr[i] !== null && (typeof arr[i] === 'object') && count <= 2) { - arrayEnter += enter; - break; - } - } - i = 0; - for (i in arr) { - if (typeof arr[i] === 'string') { - str += '\'' + arr[i] + '\'' + arrayEnter; - } else if (typeof arr[i] === 'object') { - str += switchBigObject(enter + ' ', arr[i], count + 1); - str += arrayEnter; - } else if (typeof arr[i] === 'function') { - var end = ''; - if (arr[i].name !== '') { - str += '[Function: ' + arr[i].name + ']' + arrayEnter; - } else { - str += '[Function]' + arrayEnter; - } - } else { - str += arr[i] + arrayEnter; - } - } - str = str.substr(0, str.length - arrayEnter.length); - return str; -} - -function switchIntValue(value) -{ - var str = ''; - if (value === '') { - str += 'NaN'; - } else if (typeof value === 'bigint') { - str += value + 'n'; - } else if (typeof value === 'symbol') { - str += 'NaN'; - } else if (typeof value === 'number') { - str += parseInt(value, 10); // 10:The function uses decimal. - } else if (value instanceof Array) { - if (typeof value[0] === 'number') { - str += parseInt(value[0], 10); // 10:The function uses decimal. - } else if (typeof value[0] === 'string') { - if (isNaN(value[0])) { - str += 'NaN'; - } else { - str += parseInt(value[0], 10); // 10:The function uses decimal. - } - } - } else if (typeof value === 'string') { - if (isNaN(value)) { - str += 'NaN'; - } else { - str += parseInt(value, 10); // 10:The function uses decimal. - } - } else { - str += 'NaN'; - } - return str; -} - -function switchFloatValue(value) -{ - var str = ''; - if (value === '') { - str += 'NaN'; - } else if (typeof value === 'symbol') { - str += 'NaN'; - } else if (typeof value === 'number') { - str += value; - } else if (value instanceof Array) { - if (typeof value[0] === 'number') { - str += parseFloat(value); - } else if (typeof value[0] === 'string') { - if (isNaN(value[0])) { - str += 'NaN'; - } else { - str += parseFloat(value[0]); - } - } - } else if (typeof value === 'string') { - if (isNaN(value)) { - str += 'NaN'; - } else { - str += parseFloat(value); - } - } else if (typeof value === 'bigint') { - str += value; - } else { - str += 'NaN'; - } - return str; -} - -function switchNumberValue(value) -{ - var str = ''; - if (value === '') { - str += '0'; - } else if (typeof value === 'symbol') { - str += 'NaN'; - } else if (typeof value === 'number') { - str += value; - } else if (value instanceof Array) { - str += 'NaN'; - } else if (typeof value === 'string') { - if (isNaN(value)) { - str += 'NaN'; - } else { - str += Number(value); - } - } else if (typeof value === 'bigint') { - str += value.toString() + 'n'; - } else { - str += 'NaN'; - } - return str; -} - -function switchStringValue(value) -{ - var str = ''; - if (typeof value === 'undefined') { - str += 'undefined'; - } else if (typeof value === 'object') { - if (value === null) { - str += 'null'; - } else { - str += value; - } - } else if (typeof value === 'symbol') { - str += value.toString(); - } else { - str += value; - } - return str; -} - -function printf(formatString, ...valueString) -{ - var formats = helpUtil.dealwithformatstring(formatString); - var arr = []; - arr = formats.split(' '); - var switchString = []; - var valueLength = valueString.length; - var arrLength = arr.length; - var i = 0; - for (; i < valueLength && i < arrLength; i++) { - if (arr[i] === 'o') { - switchString.push(switchLittleObject('\n ', valueString[i], 1)); - } else if (arr[i] === 'O') { - switchString.push(switchBigObject('\n ', valueString[i], 1)); - } else if (arr[i] === 'i') { - switchString.push(switchIntValue(valueString[i])); - } else if (arr[i] === 'j') { - switchString.push(JSON.stringify(valueString[i])); - } else if (arr[i] === 'd') { - switchString.push(switchNumberValue(valueString[i])); - } else if (arr[i] === 's') { - switchString.push(switchStringValue(valueString[i])); - } else if (arr[i] === 'f') { - switchString.push(switchFloatValue(valueString[i])); - } else if (arr[i] === 'c') { - switchString.push(valueString[i].toString()); - } - } - while (i < valueLength) { - switchString.push(valueString[i].toString()); - i++; - } - var helpUtilString = helpUtil.printf(formatString, ...switchString); - return helpUtilString; -} - -function getErrorString(errnum) -{ - var errorString = helpUtil.geterrorstring(errnum); - return errorString; - -} - -function callbackified(original, ...args) - { - const maybeCb = args.pop(); - if (typeof maybeCb !== 'function') { - throw new Error('maybe is not function'); - } - const cb = (...args) => { - Reflect.apply(maybeCb, this, args); - }; - Reflect.apply(original, this, args).then((ret) => cb(null, ret), (rej) => cb(rej)); - } - -function callbackWrapper(original) -{ - if (typeof original !== 'function') { - throw new Error('original is not function'); - } - const descriptors = Object.getOwnPropertyDescriptors(original); - if (typeof descriptors.length.value === 'number') { - descriptors.length.value++; - } - if (typeof descriptors.name.value === 'string') { - descriptors.name.value += 'callbackified'; - } - - function cb(...args) { - callbackified(original, ...args); - } - - Object.defineProperties(cb, descriptors); - return cb; -} - -function promiseWrapper(func) { - return function (...args) { - return new Promise((resolve, reject) => { - let callback = function (err, ...values) { - if (err) { - reject(err); - } else { - resolve(values); - } - }; - func.apply(null, [...args, callback]); - }); - }; -} - -export default { - printf: printf, - getErrorString: getErrorString, - callbackWrapper: callbackWrapper, - promiseWrapper: promiseWrapper, - TextEncoder: TextEncoder, - TextDecoder: TextDecoder, - RationalNumber: RationalNumber, - Base64: Base64, +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +declare function requireInternal(s : string) : any; +const helpUtil = requireInternal('util'); +let TextEncoder = helpUtil.TextEncoder; +let TextDecoder = helpUtil.TextDecoder; +let Base64 = helpUtil.Base64; + +function switchLittleObject(enter : string, obj : any, count : number) +{ + var str = ''; + if (obj === null) { + str += obj; + } else if (obj instanceof Array) { + str += '[ ' + arrayToString(enter, obj, count) + '[length]: ' + obj.length + ' ]'; + } else if (typeof obj === 'function') { + str += '{ [Function: ' + obj.name + ']' + enter + + '[length]: ' + obj.length + ',' + enter + + '[name] :\'' + obj.name + '\',' + enter + + '[prototype]: ' + obj.name + ' { [constructor]: [Circular] } }'; + } else if (typeof obj === 'object') { + str += '{ '; + let i; + let flag = false; + for (i in obj) { + flag = true; + str += switchLittleValue(enter, i, obj, count); + } + if (!flag) { + return obj; + } + str = str.substr(0, str.length - enter.length - 1); + str += ' }'; + } else if (typeof obj === 'string') { + str += '\'' + obj + '\''; + } else { + str += obj; + } + return str; +} + +function switchLittleValue(enter : string, protoName : any, obj : any, count : number) +{ + var str = ''; + if (obj[protoName] === null) { + str += protoName + ': null,' + enter; + } else if (obj[protoName] instanceof Array) { + str += protoName + ':' + enter + + '[ ' + arrayToString(enter + ' ', obj[protoName], count) + '[length]: ' + + obj[protoName].length + ' ],' + enter; + } else if (typeof obj[protoName] === 'object') { + if (obj[protoName] === obj) { + str += protoName + ': [Circular]' + enter; + } else { + str += protoName + ':' + enter; + str += switchLittleObject(enter + ' ', obj[protoName], count + 1) + ',' + enter; + } + } else if (typeof obj[protoName] === 'function') { + var space = enter; + if (obj[protoName].name !== '') { + str += obj[protoName].name + ':' + space; + } + space += ' '; + str += '{ [Function: ' + obj[protoName].name + ']' + space + + '[length]: ' + obj[protoName].length + ',' + space + + '[name] :\'' + obj[protoName].name + '\',' + space + + '[prototype]: ' + obj[protoName].name + + ' { [constructor]: [Circular] } },' + enter; + } else { + if (typeof obj[protoName] === 'string') { + str += protoName + ': \'' + obj[protoName] + '\',' + enter; + } else { + str += protoName + ': ' + obj[protoName] + ',' + enter; + } + } + return str; +} + +function arrayToString(enter : string, arr : any, count : number) +{ + var str = ''; + if (!arr.length) { + return ''; + } + var arrayEnter = ', '; + for (let k in arr) { + if (arr[k] !== null && (typeof arr[k] === 'function' || typeof arr[k] === 'object') && count <= 2) { + arrayEnter += enter; + break; + } + } + for (let i in arr) { + if (typeof arr[i] === 'string') { + str += '\'' + arr[i].toString() + '\'' + arrayEnter; + } else if (typeof arr[i] === 'object') { + str += switchLittleObject(enter + ' ', arr[i], count + 1); + str += arrayEnter; + } else if (typeof arr[i] === 'function') { + var space = enter; + space += ' '; + var end = ''; + if (arr[i].name !== '') { + str += '{ [Function: ' + arr[i].name + ']' + space; + end = arr[i].name + ' { [constructor]: [Circular] } }' + arrayEnter; + } else { + str += '{ [Function]' + space; + end = '{ [constructor]: [Circular] } }' + arrayEnter; + } + str += '[length]: ' + + arr[i].length + ',' + space + + '[name] :\'' + arr[i].name + '\',' + space + + '[prototype]: ' + end; + } else { + str += arr[i] + arrayEnter; + } + } + return str; +} + +function switchBigObject(enter : string, obj : any, count : number) +{ + var str = ''; + if (obj === null) { + str += obj; + } else if (obj instanceof Array) { + str += '[ ' + arrayToBigString(enter, obj, count) + ' ]'; + } else if (typeof obj === 'function') { + str += '{ [Function: ' + obj.name + '] }'; + } else if (typeof obj === 'object') { + str += '{ '; + let i; + let flag = false; + for (i in obj) { + flag = true; + str += switchBigValue(enter, i, obj, count); + } + if (!flag) { + return obj; + } + str = str.substr(0, str.length - enter.length - 1); + str += ' }'; + } else if (typeof obj === 'string') { + str += '\'' + obj + '\''; + } else { + str += obj; + } + return str; +} + +function switchBigValue(enter : string, protoName : any, obj : any, count : number) +{ + var str = ''; + if (obj[protoName] === null) { + str += protoName + ': null,' + enter; + } else if (obj[protoName] instanceof Array) { + str += protoName + ':' + enter + + '[ ' + arrayToBigString(enter + ' ', obj[protoName], count) + ' ],' + enter; + } else if (typeof obj[protoName] === 'object') { + if (obj[protoName] === obj) { + str += protoName + ': [Circular]' + enter; + } else { + str += protoName + ':' + enter; + str += switchBigObject(enter + ' ', obj[protoName], count + 1) + ',' + enter; + } + } else if (typeof obj[protoName] === 'function') { + if (obj[protoName].name !== '') { + str += obj[protoName].name + ': '; + } + str += '[Function: ' + obj[protoName].name + '],' + enter; + } else { + if (typeof obj[protoName] === 'string') { + str += protoName + ': \'' + obj[protoName] + '\',' + enter; + } else { + str += protoName + ': ' + obj[protoName] + ',' + enter; + } + } + return str; +} + +function arrayToBigString(enter : string, arr : any, count : number) +{ + var str = ''; + if (!arr.length) { + return ''; + } + + var arrayEnter = ', '; + for (let i in arr) { + if (arr[i] !== null && (typeof arr[i] === 'object') && count <= 2) { + arrayEnter += enter; + break; + } + } + for (let j in arr) { + if (typeof arr[j] === 'string') { + str += '\'' + arr[j] + '\'' + arrayEnter; + } else if (typeof arr[j] === 'object') { + str += switchBigObject(enter + ' ', arr[j], count + 1); + str += arrayEnter; + } else if (typeof arr[j] === 'function') { + if (arr[j].name !== '') { + str += '[Function: ' + arr[j].name + ']' + arrayEnter; + } else { + str += '[Function]' + arrayEnter; + } + } else { + str += arr[j] + arrayEnter; + } + } + str = str.substr(0, str.length - arrayEnter.length); + return str; +} + +function switchIntValue(value : any) +{ + var str = ''; + if (value === '') { + str += 'NaN'; + } else if (typeof value === 'bigint') { + str += value + 'n'; + } else if (typeof value === 'symbol') { + str += 'NaN'; + } else if (typeof value === 'number') { + str += parseInt(value, 10); // 10:The function uses decimal. + } else if (value instanceof Array) { + if (typeof value[0] === 'number') { + str += parseInt(value[0], 10); // 10:The function uses decimal. + } else if (typeof value[0] === 'string') { + if (isNaN(value[0])) { + str += 'NaN'; + } else { + str += parseInt(value[0], 10); // 10:The function uses decimal. + } + } + } else if (typeof value === 'string') { + if (isNaN(value)) { + str += 'NaN'; + } else { + str += parseInt(value, 10); // 10:The function uses decimal. + } + } else { + str += 'NaN'; + } + return str; +} + +function switchFloatValue(value : any) +{ + var str = ''; + if (value === '') { + str += 'NaN'; + } else if (typeof value === 'symbol') { + str += 'NaN'; + } else if (typeof value === 'number') { + str += value; + } else if (value instanceof Array) { + if (typeof value[0] === 'number') { + str += parseFloat(value); + } else if (typeof value[0] === 'string') { + if (isNaN(value[0])) { + str += 'NaN'; + } else { + str += parseFloat(value[0]); + } + } + } else if (typeof value === 'string') { + if (isNaN(value)) { + str += 'NaN'; + } else { + str += parseFloat(value); + } + } else if (typeof value === 'bigint') { + str += value; + } else { + str += 'NaN'; + } + return str; +} + +function switchNumberValue(value : any) +{ + var str = ''; + if (value === '') { + str += '0'; + } else if (typeof value === 'symbol') { + str += 'NaN'; + } else if (typeof value === 'number') { + str += value; + } else if (value instanceof Array) { + str += 'NaN'; + } else if (typeof value === 'string') { + if (isNaN(value)) { + str += 'NaN'; + } else { + str += Number(value); + } + } else if (typeof value === 'bigint') { + str += value.toString() + 'n'; + } else { + str += 'NaN'; + } + return str; +} + +function switchStringValue(value : any) +{ + var str = ''; + if (typeof value === 'undefined') { + str += 'undefined'; + } else if (typeof value === 'object') { + if (value === null) { + str += 'null'; + } else { + str += value; + } + } else if (typeof value === 'symbol') { + str += value.toString(); + } else { + str += value; + } + return str; +} + +function printf(formatString : any, ...valueString : any) +{ + var formats = helpUtil.dealwithformatstring(formatString); + var arr = []; + arr = formats.split(' '); + var switchString = []; + var valueLength = valueString.length; + var arrLength = arr.length; + var i = 0; + for (; i < valueLength && i < arrLength; i++) { + if (arr[i] === 'o') { + switchString.push(switchLittleObject('\n ', valueString[i], 1)); + } else if (arr[i] === 'O') { + switchString.push(switchBigObject('\n ', valueString[i], 1)); + } else if (arr[i] === 'i') { + switchString.push(switchIntValue(valueString[i])); + } else if (arr[i] === 'j') { + switchString.push(JSON.stringify(valueString[i])); + } else if (arr[i] === 'd') { + switchString.push(switchNumberValue(valueString[i])); + } else if (arr[i] === 's') { + switchString.push(switchStringValue(valueString[i])); + } else if (arr[i] === 'f') { + switchString.push(switchFloatValue(valueString[i])); + } else if (arr[i] === 'c') { + switchString.push(valueString[i].toString()); + } + } + while (i < valueLength) { + switchString.push(valueString[i].toString()); + i++; + } + var helpUtilString = helpUtil.printf(formatString, ...switchString); + return helpUtilString; +} + +function getErrorString(errnum : number) +{ + var errorString = helpUtil.geterrorstring(errnum); + return errorString; +} + +function callbackified(original : any, ...args : any) + { + const maybeCb = args.pop(); + if (typeof maybeCb !== 'function') { + throw new Error('maybe is not function'); + } + const cb = (...args : any) => { + Reflect.apply(maybeCb, this, args); + }; + Reflect.apply(original, this, args).then((ret : any) => cb(null, ret), (rej : any) => cb(rej)); + } + +function callbackWrapper(original : any) +{ + if (typeof original !== 'function') { + throw new Error('original is not function'); + } + const descriptors = Object.getOwnPropertyDescriptors(original); + if (typeof descriptors.length.value === 'number') { + descriptors.length.value++; + } + if (typeof descriptors.name.value === 'string') { + descriptors.name.value += 'callbackified'; + } + + function cb(...args : any) { + callbackified(original, ...args); + } + Object.defineProperties(cb, descriptors); + return cb; +} + +function promiseWrapper(func : any) { + // promiseWrapper + return function (...args : any) { + return new Promise((resolve, reject) => { + let callback = function (err : any, ...values : any) { + if (err) { + reject(err); + } else { + resolve(values); + } + }; + func.apply(null, [...args, callback]); + }); + }; +} + +class LruBuffer +{ + private cache: Map; + private maxSize : number = 64; + private putCount : number = 0; + private createCount : number = 0; + private evictionCount : number = 0; + private hitCount : number = 0; + private missCount : number = 0; + + public constructor(capacity?: number) + { + if(capacity !== undefined) { + if (capacity <= 0) { + throw new Error('data error'); + } + this.maxSize = capacity; + } + this.cache = new Map(); + } + public updateCapacity(newCapacity : number) + { + if (newCapacity <= 0) { + throw new Error('data error'); + } else if (this.cache.size >newCapacity) { + this.changeCapacity(newCapacity); + } + this.maxSize = newCapacity; + } + public get(key : any) + { + if (key === null) { + throw new Error('key not be null'); + } + let value; + if (this.cache.has(key)) { + value = this.cache.get(key); + this.hitCount++; + this.cache.delete(key); + this.cache.set(key, value); + return value; + } + this.missCount++; + let createValue = this.createDefault(key); + if (createValue === undefined) { + return undefined; + } else { + value = this.put(key, createValue); + this.createCount++; + if (value !== null) { + this.put(key, value); + this.afterRemoval(false, key, createValue, value); + return value; + } + return createValue; + } + } + public put(key : any, value : any) + { + if (key === null || value === null) { + throw new Error('key or value not be null'); + } + let former; + this.putCount++; + if (this.cache.has(key)) { + former = this.cache.get(key); + this.cache.delete(key); + this.afterRemoval(false, key, former, value); + } else if (this.cache.size >= this.maxSize) { + this.cache.delete(this.cache.keys().next().value); + this.evictionCount++; + } + this.cache.set(key, value); + return former; + } + public getCreatCount() + { + return this.createCount; + } + public getMissCount() + { + return this.missCount; + } + public getRemovalCount() + { + return this.evictionCount; + } + public getMatchCount() + { + return this.hitCount; + } + public getPutCount() + { + return this.putCount; + } + public capacity() + { + return this.maxSize; + } + public size() + { + return this.cache.size; + } + public clear() + { + this.cache.clear(); + this.afterRemoval(false, this.cache.keys(), this.cache.values(), null); + } + public isEmpty() + { + let temp : boolean = false; + if (this.cache.size === 0) { + temp = true; + } + return temp; + } + public contains(key : any) + { + let flag : boolean = false; + if (this.cache.has(key)) { + flag = true; + let value; + this.hitCount++; + value = this.cache.get(key); + this.cache.delete(key); + this.cache.set(key, value); + return flag; + } + this.missCount++; + return flag; + } + public remove(key : any) + { + if (key === null) { + throw new Error('key not be null'); + } else if (this.cache.has(key)) { + let former; + former = this.cache.get(key); + this.cache.delete(key); + if (former !== null) { + this.afterRemoval(false, key, former, null); + return former; + } + } + return undefined; + } + public toString() + { + let peek : number = 0; + let hitRate : number = 0; + peek = this.hitCount + this.missCount; + if (peek !== 0) { + hitRate = 100 * this.hitCount / peek; + } else { + hitRate = 0; + } + let str : string = ''; + str = 'Lrubuffer[ maxSize = ' + this.maxSize + ', hits = ' + this.hitCount + ', misses = ' + this.missCount + + ', hitRate = ' + hitRate + '% ]'; + return str; + } + public values() + { + let arr = []; + for(let value of this.cache.values()) { + arr.push(value); + } + return arr; + } + public keys() + { + let arr = []; + for(let key of this.cache.keys()) { + arr.push(key); + } + return arr; + } + protected afterRemoval(isEvict : boolean, key : any, value : any, newValue : any) + { + + } + protected createDefault(key : any) + { + return undefined; + } + public entries() + { + let arr = []; + for (let entry of this.cache.entries()) { + arr.push(entry); + } + return arr; + } + public [Symbol.iterator] () + { + let arr = []; + for (let [key, value] of this.cache) { + arr.push([key, value]); + } + return arr; + } + private changeCapacity(newCapacity : number) + { + while(this.cache.size >newCapacity) { + this.cache.delete(this.cache.keys().next().value); + this.evictionCount++; + this.afterRemoval(true, this.cache.keys(), this.cache.values(), null); + } + } +} + +class RationalNumber +{ + private mnum : number = 0; + private mden : number = 0; + public constructor(num : number, den : number) + { + num = den < 0 ? num * (-1) : num; + den = den < 0 ? den * (-1) : den; + if (den == 0) { + if (num > 0) { + this.mnum = 1; + this.mden = 0; + } else if (num < 0) { + this.mnum = -1; + this.mden = 0; + } else { + this.mnum = 0; + this.mden = 0; + } + } else if (num == 0) { + this.mnum = 0; + this.mden = 1; + } else { + let gnum : number = 0; + gnum = this.getCommonDivisor(num, den); + if (gnum != 0) { + this.mnum = num / gnum; + this.mden = den / gnum; + } + } + } + + public createRationalFromString(str : string) + { + if (str == null) { + throw new Error('string invalid!'); + } + if (str == 'NaN') { + return new RationalNumber(0, 0); + } + let colon : number = str.indexOf(':'); + let semicolon : number = str.indexOf('/'); + if ((colon < 0 && semicolon < 0) || (colon > 0 && semicolon > 0)) { + throw new Error('string invalid!'); + } + let index : number = (colon > 0) ? colon : semicolon; + let s1 : string = str.substr(0, index); + let s2 : string = str.substr(index + 1, str.length); + let num1 : number = Number(s1); + let num2 : number = Number(s2); + return new RationalNumber(num1, num2); + } + + public compareTo(other : RationalNumber) + { + if (this.mnum == other.mnum && this.mden == other.mden) { + return 0; + } else if (this.mnum == 0 && this.mden == 0) { + return 1; + } else if ((other.mnum == 0) && (other.mden == 0)) { + return -1; + } else if ((this.mden == 0 && this.mnum > 0) || (other.mden == 0 && other.mnum < 0)) { + return 1; + } else if ((this.mden == 0 && this.mnum < 0) || (other.mden == 0 && other.mnum > 0)) { + return -1; + } + let thisnum : number = this.mnum * other.mden; + let othernum : number = other.mnum * this.mden; + if (thisnum < othernum) { + return -1; + } else if (thisnum > othernum) { + return 1; + } else { + return 0; + } + } + + public equals(obj : object) + { + if (!(obj instanceof RationalNumber)) { + return false; + } + let thisnum : number = this.mnum * obj.mden; + let objnum : number = obj.mnum * this.mden; + if (this.mnum == obj.mnum && this.mden == obj.mden) { + return true; + } else if ((thisnum == objnum) && (this.mnum != 0 && this.mden != 0) && (obj.mnum != 0 && obj.mden != 0)) { + return true; + } else if ((this.mnum == 0 && this.mden != 0) && (obj.mnum == 0 && obj.mden != 0)) { + return true; + } else if ((this.mnum > 0 && this.mden == 0) && (obj.mnum > 0 && obj.mden == 0)) { + return true; + } else if ((this.mnum < 0 && this.mden == 0) && (obj.mnum < 0 && obj.mden == 0)) { + return true; + } else { + return false; + } + } + + public value() + { + if (this.mnum > 0 && this.mden == 0) { + return Number.POSITIVE_INFINITY; + } else if (this.mnum < 0 && this.mden == 0) { + return Number.NEGATIVE_INFINITY; + } else if ((this.mnum == 0) && (this.mden == 0)) { + return Number.NaN; + } else { + return this.mnum / this.mden; + } + } + + public getCommonDivisor(number1 : number, number2 : number) + { + if (number1 == 0 || number2 == 0) { + throw new Error("Parameter cannot be zero!"); + } + let temp : number = 0; + if (number1 < number2) { + temp = number1; + number1 = number2; + number2 = temp; + } + while (number1 % number2 != 0) { + temp = number1 % number2; + number1 = number2; + number2 = temp; + } + return number2; + } + + public getDenominator() + { + return this.mden; + } + + public getNumerator() + { + return this.mnum; + } + + public isFinite() + { + return this.mden != 0; + } + + public isNaN() + { + return this.mnum == 0 && this.mden == 0; + } + + public isZero() + { + return this.mnum == 0 && this.mden != 0; + } + + public toString() + { + let buf : string; + if (this.mnum == 0 && this.mden == 0) { + buf = "NaN"; + } else if (this.mnum > 0 && this.mden == 0) { + buf = "Infinity"; + } else if (this.mnum < 0 && this.mden == 0) { + buf = "-Infinity"; + } else { + buf = String(this.mnum) + '/' + String(this.mden); + } + return buf; + } +} + +interface ScopeComparable { + compareTo(other: ScopeComparable): boolean; +} + +type ScopeType = ScopeComparable; +class Scope { + + private readonly _lowerLimit: ScopeType; + private readonly _upperLimit: ScopeType; + + public constructor(readonly lowerObj: ScopeType, readonly upperObj: ScopeType) { + this.checkNull(lowerObj, 'lower limit not be null'); + this.checkNull(upperObj, 'upper limit not be null'); + + if(lowerObj.compareTo(upperObj)) { + throw new Error('lower limit must be less than or equal to upper limit'); + } + this._lowerLimit = lowerObj; + this._upperLimit = upperObj; + } + + public getLower(): ScopeType { + return this._lowerLimit; + } + + public getUpper(): ScopeType { + return this._upperLimit; + } + + public contains(value: ScopeType): boolean; + public contains(scope: Scope): boolean; + public contains(x: any): boolean { + let resLower: boolean; + let resUpper: boolean; + this.checkNull(x, 'value must not be null'); + if(x instanceof Scope) { + resLower= x._lowerLimit.compareTo(this._lowerLimit); + resUpper= this._upperLimit.compareTo(x._upperLimit); + } else { + resLower= x.compareTo(this._lowerLimit); + resUpper= this._upperLimit.compareTo(x); + } + return resLower && resUpper; + } + + public clamp(value: ScopeType): ScopeType { + this.checkNull(value, 'value must not be null'); + + if (!value.compareTo(this._lowerLimit)) { + return this._lowerLimit; + } else if (value.compareTo(this._upperLimit)) { + return this._upperLimit; + } else { + return value; + } + } + + public intersect(scope: Scope): Scope; + public intersect(lowerObj: ScopeType, upperObj: ScopeType): Scope; + public intersect(x: any, y?: any): Scope { + let reLower: boolean; + let reUpper: boolean; + let mLower: ScopeType; + let mUpper: ScopeType; + if(y) + { + this.checkNull(x, 'lower limit must not be null'); + this.checkNull(y, 'upper limit must not be null'); + reLower = this._lowerLimit.compareTo(x); + reUpper = y.compareTo(this._upperLimit); + if (reLower && reUpper) { + return this; + } else { + mLower = reLower ? this._lowerLimit : x; + mUpper = reUpper ? this._upperLimit : y; + return new Scope(mLower, mUpper); + } + } else { + this.checkNull(x, 'scope must not be null'); + reLower = this._lowerLimit.compareTo(x._lowerLimit); + reUpper = x._upperLimit.compareTo(this._upperLimit); + if (!reLower && !reUpper) { + return x; + } else if (reLower && reUpper) { + return this; + } else { + mLower = reLower ? this._lowerLimit : x._lowerLimit; + mUpper = reUpper ? this._upperLimit : x._upperLimit; + return new Scope(mLower, mUpper); + } + } + } + + public expand(obj: ScopeType): Scope; + public expand(scope: Scope): Scope; + public expand(lowerObj: ScopeType, upperObj: ScopeType): Scope; + public expand(x: any, y?: any): Scope { + let reLower: boolean; + let reUpper: boolean; + let mLower: ScopeType; + let mUpper: ScopeType; + if (!y) { + this.checkNull(x, 'value must not be null'); + if (!(x instanceof Scope)) { + this.checkNull(x, 'value must not be null'); + return this.expand(x, x); + } + + let reLower = x._lowerLimit.compareTo(this._lowerLimit); + let reUpper = this._upperLimit.compareTo(x._upperLimit); + if (reLower && reUpper) { + return this; + } else if (!reLower && !reUpper) { + return x; + } else { + let mLower = reLower ? this._lowerLimit : x._lowerLimit; + let mUpper = reUpper ? this._upperLimit : x._upperLimit; + return new Scope(mLower, mUpper); + } + } else { + this.checkNull(x, 'lower limit must not be null'); + this.checkNull(y, "upper limit must not be null"); + let reLower = x.compareTo(this._lowerLimit); + let reUpper = this._upperLimit.compareTo(y); + if (reLower && reUpper) { + return this; + } + let mLower = reLower ? this._lowerLimit : x; + let mUpper = reUpper ? this._upperLimit : y; + return new Scope(mLower, mUpper); + } + } + + public toString(): string { + let strLower = this._lowerLimit.toString(); + let strUpper = this._upperLimit.toString(); + return `[${strLower}, ${strUpper}]`; + } + + public checkNull(o: ScopeType, str: string): void { + if(o == null) { + throw new Error(str); + } + } +} + +export default { + printf: printf, + getErrorString: getErrorString, + callbackWrapper: callbackWrapper, + promiseWrapper: promiseWrapper, + TextEncoder: TextEncoder, + TextDecoder: TextDecoder, + Base64: Base64, + LruBuffer: LruBuffer, + RationalNumber : RationalNumber, + Scope : Scope, }; \ No newline at end of file diff --git a/util/tsconfig.json b/util/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..66ad148561b08a71630eb07c7484394c2acc7930 --- /dev/null +++ b/util/tsconfig.json @@ -0,0 +1,14 @@ +{ +"compilerOptions": { + "target": "es6", + "module": "es6", + "rootDir": "./src", + //"outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */ + "outDir": "./out", /* Specify an output folder for all emitted files. */ + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "strict": true, + "skipLibCheck": true, + "noImplicitThis": false, + } +}