diff --git a/README_zh.md b/README_zh.md old mode 100755 new mode 100644 index 9210368799c511a43d04d2d67a8fafa28d736ae7..237bca466797aeac0844dc30c6d130e23ea1bbdc --- a/README_zh.md +++ b/README_zh.md @@ -1,165 +1,165 @@ -# 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。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) diff --git a/lrubuffer/js_lrubuffer.js b/lrubuffer/js_lrubuffer.js old mode 100755 new mode 100644 index 71a4752da1ba1649253907ff8cbaa8951cce30bf..c595c52b413b2595ad7eb7e32edf13d5cc2aa2d9 --- a/lrubuffer/js_lrubuffer.js +++ b/lrubuffer/js_lrubuffer.js @@ -1,192 +1,192 @@ -/* - * 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, -}; +/* + * 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 old mode 100755 new mode 100644 index eee051c4a9ab9c9f30cead513f9e72cef289ae63..42dbed28df1d85173808bb72e4a44f37ae5f0d0e --- a/lrubuffer/native_module_lrubuffer.cpp +++ b/lrubuffer/native_module_lrubuffer.cpp @@ -1,62 +1,61 @@ -/* - * 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; - } +/* + * 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/scope/native_module_scope.cpp b/scope/native_module_scope.cpp old mode 100755 new mode 100644 index c3eff3e6591f28ae99acd013583552552947c976..ceba63dfb0a055106af1b663b87cf4030e609eb1 --- a/scope/native_module_scope.cpp +++ b/scope/native_module_scope.cpp @@ -1,64 +1,63 @@ -/* - * 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; - } +/* + * 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 old mode 100755 new mode 100644 index c93eec79e4932d70788547ecae6d60e85d03254c..d13812a5ae188322fc656ef2b642a74b2091e10e --- a/scope/scope_js.js +++ b/scope/scope_js.js @@ -1,147 +1,147 @@ -/* - * 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, +/* + * 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/util/js_base64.cpp b/util/js_base64.cpp old mode 100755 new mode 100644 index 475bb727ad6ef0141b25946515f04009f18540ab..8417f1c40eca51609a65b045d9f4e774f7866f5a --- a/util/js_base64.cpp +++ b/util/js_base64.cpp @@ -1,336 +1,336 @@ -/* - * 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_base64.h" -#include -#include -#include "utils/log.h" -#include "securec.h" -#include "napi/native_api.h" -#include "napi/native_node_api.h" - -namespace OHOS::Util { - namespace { - static const size_t TRAGET_TWO = 2; - static const size_t TRAGET_THREE = 3; - static const size_t TRAGET_FOUR = 4; - static const size_t TRAGET_SIX = 6; - static const size_t TRAGET_EIGHT = 8; - 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_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)); - 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); - void *data = nullptr; - napi_value arrayBuffer = nullptr; - size_t bufferSize = outputLen; - NAPI_CALL(env, napi_create_arraybuffer(env, bufferSize, &data, &arrayBuffer)); - if (memcpy_s(data, bufferSize, reinterpret_cast(rets), bufferSize) != 0) { - FreeMemory(rets); - HILOG_ERROR("copy ret to arraybuffer error"); - return nullptr; - } - napi_value result = nullptr; - NAPI_CALL(env, napi_create_typedarray(env, napi_uint8_array, bufferSize, arrayBuffer, 0, &result)); - FreeMemory(rets); - return result; - } - - /* base64 encodeToString */ - napi_value Base64::EncodeToString(napi_value src, napi_value flags) - { - 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)); - 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); - 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) - { - size_t inp = 0; - size_t temp = 0; - size_t bitWise = 0; - unsigned char *ret = nullptr; - unsigned char *bosom = nullptr; - outputLen = (inputLen / TRAGET_THREE) * TRAGET_FOUR; - if ((inputLen % TRAGET_THREE) > 0) { - outputLen += TRAGET_FOUR; - } - if (outputLen > 0) { - ret = new unsigned char[outputLen + 1]; - if (memset_s(ret, outputLen + 1, '\0', outputLen + 1) != 0) { - FreeMemory(ret); - napi_throw_error(env, "-1", "ret path memset_s failed"); - } - } else { - napi_throw_error(env, "-2", "outputLen is error !"); - } - bosom = ret; - 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 && 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]; - } - bosom++; - } - } - *bosom = '\0'; - return ret; - } - - /* base64 decode */ - napi_value Base64::Decode(napi_value src, napi_value flags) - { - 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; - 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); - if (prolen > 0) { - inputString = new char[prolen + 1]; - if (memset_s(inputString, prolen + 1, '\0', prolen + 1) != 0) { - FreeMemory(inputString); - 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); - pret = DecodeAchieve(inputString, prolen, flag); - } else if (type == napi_typedarray_type::napi_uint8_array) { - inputDecode = static_cast(resultData) + byteOffset; - pret = DecodeAchieve(inputDecode, length, flag); - } - void *data = nullptr; - napi_value arrayBuffer = nullptr; - size_t bufferSize = decodeOutLen; - NAPI_CALL(env, napi_create_arraybuffer(env, bufferSize, &data, &arrayBuffer)); - if (memcpy_s(data, bufferSize, reinterpret_cast(pret), bufferSize) != 0) { - FreeMemory(inputString); - FreeMemory(pret); - HILOG_ERROR("copy retDecode to arraybuffer error"); - return nullptr; - } - napi_value result = nullptr; - NAPI_CALL(env, napi_create_typedarray(env, napi_uint8_array, bufferSize, arrayBuffer, 0, &result)); - FreeMemory(inputString); - FreeMemory(pret); - return result; - } - - unsigned char *Base64::DecodeAchieve(const char *input, size_t inputLen, size_t iflag) - { - retLen = (inputLen / TRAGET_FOUR) * TRAGET_THREE; - decodeOutLen = retLen; - size_t equalCount = 0; - unsigned char *bosom = nullptr; - size_t inp = 0; - size_t temp = 0; - size_t bitWise = 0; - if (*(input + inputLen - 1) == '=') { - equalCount++; - } - if (*(input + inputLen - TRAGET_TWO) == '=') { - equalCount++; - } - if (*(input + inputLen - TRAGET_THREE) == '=') { - equalCount++; - } - retLen = DecodeOut(equalCount, retLen); - if (retLen > 0) { - retDecode = new unsigned char[retLen + 1]; - if (memset_s(retDecode, retLen + 1, '\0', retLen + 1) != 0) { - FreeMemory(retDecode); - napi_throw_error(env, "-1", "decode retDecode memset_s failed"); - } - } else { - napi_throw_error(env, "-2", "retLen is error !"); - } - bosom = retDecode; - while (inp < (inputLen - equalCount)) { - temp = 0; - bitWise = 0; - while (temp < TRAGET_FOUR) { - if (inp >= (inputLen - equalCount)) { - break; - } - bitWise = (bitWise << TRAGET_SIX) | (Finds(input[inp], iflag)); - inp++; - temp++; - } - bitWise = bitWise << ((TRAGET_FOUR - temp) * TRAGET_SIX); - for (size_t i = 0; i < TRAGET_THREE; i++) { - if (i == temp) { - break; - } - *bosom = static_cast((bitWise >> ((TRAGET_TWO - i) * TRAGET_EIGHT)) & XFF_FLG); - bosom++; - } - } - *bosom = '\0'; - return retDecode; - } - - size_t Base64::DecodeOut(size_t equalCount, size_t retLen) - { - size_t temp = retLen; - if (equalCount == 1) { - decodeOutLen -= 1; - } - if (equalCount == TRAGET_TWO) { - decodeOutLen -= TRAGET_TWO; - } - switch (equalCount) { - case 0: - temp += TRAGET_FOUR; - break; - case 1: - temp += TRAGET_FOUR; - break; - case TRAGET_TWO: - temp += TRAGET_THREE; - break; - default: - temp += TRAGET_TWO; - break; - } - return temp; - } - - /* Decoding lookup function */ - size_t Base64::Finds(char ch, size_t iflag) - { - 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; - } - } - } - return couts; - } - - /* Memory cleanup function */ - void Base64::FreeMemory(const unsigned char *address) - { - const unsigned char *temp = address; - if (temp != nullptr) { - delete[] temp; - temp = nullptr; - } - } - void Base64::FreeMemory(const char *address) - { - const char *temp = address; - if (temp != nullptr) { - delete[] temp; - temp = nullptr; - } - } +/* + * 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_base64.h" +#include +#include +#include "utils/log.h" +#include "securec.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +namespace OHOS::Util { + namespace { + static const size_t TRAGET_TWO = 2; + static const size_t TRAGET_THREE = 3; + static const size_t TRAGET_FOUR = 4; + static const size_t TRAGET_SIX = 6; + static const size_t TRAGET_EIGHT = 8; + 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_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)); + 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); + void *data = nullptr; + napi_value arrayBuffer = nullptr; + size_t bufferSize = outputLen; + NAPI_CALL(env, napi_create_arraybuffer(env, bufferSize, &data, &arrayBuffer)); + if (memcpy_s(data, bufferSize, reinterpret_cast(rets), bufferSize) != 0) { + FreeMemory(rets); + HILOG_ERROR("copy ret to arraybuffer error"); + return nullptr; + } + napi_value result = nullptr; + NAPI_CALL(env, napi_create_typedarray(env, napi_uint8_array, bufferSize, arrayBuffer, 0, &result)); + FreeMemory(rets); + return result; + } + + /* base64 encodeToString */ + napi_value Base64::EncodeToString(napi_value src, napi_value flags) + { + 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)); + 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); + 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) + { + size_t inp = 0; + size_t temp = 0; + size_t bitWise = 0; + unsigned char *ret = nullptr; + unsigned char *bosom = nullptr; + outputLen = (inputLen / TRAGET_THREE) * TRAGET_FOUR; + if ((inputLen % TRAGET_THREE) > 0) { + outputLen += TRAGET_FOUR; + } + if (outputLen > 0) { + ret = new unsigned char[outputLen + 1]; + if (memset_s(ret, outputLen + 1, '\0', outputLen + 1) != 0) { + FreeMemory(ret); + napi_throw_error(env, "-1", "ret path memset_s failed"); + } + } else { + napi_throw_error(env, "-2", "outputLen is error !"); + } + bosom = ret; + 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 && 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]; + } + bosom++; + } + } + *bosom = '\0'; + return ret; + } + + /* base64 decode */ + napi_value Base64::Decode(napi_value src, napi_value flags) + { + 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; + 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); + if (prolen > 0) { + inputString = new char[prolen + 1]; + if (memset_s(inputString, prolen + 1, '\0', prolen + 1) != 0) { + FreeMemory(inputString); + 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); + pret = DecodeAchieve(inputString, prolen, flag); + } else if (type == napi_typedarray_type::napi_uint8_array) { + inputDecode = static_cast(resultData) + byteOffset; + pret = DecodeAchieve(inputDecode, length, flag); + } + void *data = nullptr; + napi_value arrayBuffer = nullptr; + size_t bufferSize = decodeOutLen; + NAPI_CALL(env, napi_create_arraybuffer(env, bufferSize, &data, &arrayBuffer)); + if (memcpy_s(data, bufferSize, reinterpret_cast(pret), bufferSize) != 0) { + FreeMemory(inputString); + FreeMemory(pret); + HILOG_ERROR("copy retDecode to arraybuffer error"); + return nullptr; + } + napi_value result = nullptr; + NAPI_CALL(env, napi_create_typedarray(env, napi_uint8_array, bufferSize, arrayBuffer, 0, &result)); + FreeMemory(inputString); + FreeMemory(pret); + return result; + } + + unsigned char *Base64::DecodeAchieve(const char *input, size_t inputLen, size_t iflag) + { + retLen = (inputLen / TRAGET_FOUR) * TRAGET_THREE; + decodeOutLen = retLen; + size_t equalCount = 0; + unsigned char *bosom = nullptr; + size_t inp = 0; + size_t temp = 0; + size_t bitWise = 0; + if (*(input + inputLen - 1) == '=') { + equalCount++; + } + if (*(input + inputLen - TRAGET_TWO) == '=') { + equalCount++; + } + if (*(input + inputLen - TRAGET_THREE) == '=') { + equalCount++; + } + retLen = DecodeOut(equalCount, retLen); + if (retLen > 0) { + retDecode = new unsigned char[retLen + 1]; + if (memset_s(retDecode, retLen + 1, '\0', retLen + 1) != 0) { + FreeMemory(retDecode); + napi_throw_error(env, "-1", "decode retDecode memset_s failed"); + } + } else { + napi_throw_error(env, "-2", "retLen is error !"); + } + bosom = retDecode; + while (inp < (inputLen - equalCount)) { + temp = 0; + bitWise = 0; + while (temp < TRAGET_FOUR) { + if (inp >= (inputLen - equalCount)) { + break; + } + bitWise = (bitWise << TRAGET_SIX) | (Finds(input[inp], iflag)); + inp++; + temp++; + } + bitWise = bitWise << ((TRAGET_FOUR - temp) * TRAGET_SIX); + for (size_t i = 0; i < TRAGET_THREE; i++) { + if (i == temp) { + break; + } + *bosom = static_cast((bitWise >> ((TRAGET_TWO - i) * TRAGET_EIGHT)) & XFF_FLG); + bosom++; + } + } + *bosom = '\0'; + return retDecode; + } + + size_t Base64::DecodeOut(size_t equalCount, size_t retLen) + { + size_t temp = retLen; + if (equalCount == 1) { + decodeOutLen -= 1; + } + if (equalCount == TRAGET_TWO) { + decodeOutLen -= TRAGET_TWO; + } + switch (equalCount) { + case 0: + temp += TRAGET_FOUR; + break; + case 1: + temp += TRAGET_FOUR; + break; + case TRAGET_TWO: + temp += TRAGET_THREE; + break; + default: + temp += TRAGET_TWO; + break; + } + return temp; + } + + /* Decoding lookup function */ + size_t Base64::Finds(char ch, size_t iflag) + { + 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; + } + } + } + return couts; + } + + /* Memory cleanup function */ + void Base64::FreeMemory(const unsigned char *address) + { + const unsigned char *temp = address; + if (temp != nullptr) { + delete[] temp; + temp = nullptr; + } + } + void Base64::FreeMemory(const char *address) + { + const char *temp = address; + if (temp != nullptr) { + delete[] temp; + temp = nullptr; + } + } } \ No newline at end of file diff --git a/util/js_base64.h b/util/js_base64.h old mode 100755 new mode 100644 index ff0ce011b2d43e4520b807b6216317cddf3686e2..e3b83920b1d0451b9c13532de2759e6f6436c65a --- a/util/js_base64.h +++ b/util/js_base64.h @@ -1,56 +1,56 @@ -/* - * 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 -#include -#include "napi/native_api.h" -#include "napi/native_node_api.h" - -#ifndef BASE_COMPILERUNTIME_JS_UTIL_MODULE_BASE64_CLASS_H -#define BASE_COMPILERUNTIME_JS_UTIL_MODULE_BASE64_CLASS_H - -namespace OHOS::Util { - 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); - 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); - size_t DecodeOut(size_t equalCount, size_t retLen); - void FreeMemory(const unsigned char *address); - void FreeMemory(const char *address); - size_t retLen = 0; - size_t decodeOutLen = 0; - size_t outputLen = 0; - unsigned char *pret = nullptr; - const unsigned char *inputEncode = nullptr; - const char *inputDecode = nullptr; - unsigned char *retDecode = nullptr; - }; -} +/* + * 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 +#include +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +#ifndef BASE_COMPILERUNTIME_JS_UTIL_MODULE_BASE64_CLASS_H +#define BASE_COMPILERUNTIME_JS_UTIL_MODULE_BASE64_CLASS_H + +namespace OHOS::Util { + 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); + 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); + size_t DecodeOut(size_t equalCount, size_t retLen); + void FreeMemory(const unsigned char *address); + void FreeMemory(const char *address); + size_t retLen = 0; + size_t decodeOutLen = 0; + size_t outputLen = 0; + unsigned char *pret = nullptr; + const unsigned char *inputEncode = nullptr; + const char *inputDecode = nullptr; + unsigned char *retDecode = nullptr; + }; +} #endif \ No newline at end of file diff --git a/util/js_rational.cpp b/util/js_rational.cpp old mode 100755 new mode 100644 index 567c26f32e7ae0e537ad6e957a3e980e0338025a..bb8be7fd0fb8c5d26d544a9e8802327bdaa77e1a --- a/util/js_rational.cpp +++ b/util/js_rational.cpp @@ -1,325 +1,328 @@ -/* - * 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 num, int den) - { - env_ = env; - napi_value result = nullptr; - den < 0 ? num *= -1, den *= -1 : 0; - 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; - } +/* + * 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 old mode 100755 new mode 100644 index 8e6f022940d668b2e0d6d43f633342e688a66f62..57038c72fbe19a48d97d18385c42a9e28781f4b6 --- a/util/js_rational.h +++ b/util/js_rational.h @@ -1,46 +1,46 @@ -/* - * 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; - }; -} +/* + * 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 old mode 100755 new mode 100644 index 4d3c9c6cebd2a528a168bc2eaeb53ee541541096..8f38672f9318202954338916cc9c0d714d36fd5f --- a/util/js_textdecoder.cpp +++ b/util/js_textdecoder.cpp @@ -73,8 +73,8 @@ namespace OHOS::Util { NAPI_CALL(env_, napi_get_typedarray_info(env_, src, &type, &length, &data1, &arrayBuffer, &byteOffset)); const char *source = static_cast(data1); UErrorCode codeFlag = U_ZERO_ERROR; - size_t limit = GetMinByteSize() *length; - size_t len = limit *sizeof(UChar); + size_t limit = GetMinByteSize() * length; + size_t len = limit * sizeof(UChar); UChar *arr = nullptr; if (limit > 0) { arr = new UChar[limit + 1]; diff --git a/util/native_module_util.cpp b/util/native_module_util.cpp old mode 100755 new mode 100644 index ed8e51a04005476ce8e05d54e76e5f1bd7b09c3b..43e566fa67c19e852524762d2c033fa795264c25 --- a/util/native_module_util.cpp +++ b/util/native_module_util.cpp @@ -834,15 +834,4 @@ namespace OHOS::Util { *buflen = _binary_util_js_js_end - _binary_util_js_js_start; } } - // util JS register - 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; - } - } }