code
stringlengths 10
343k
| docstring
stringlengths 36
21.9k
| func_name
stringlengths 1
3.35k
| language
stringclasses 1
value | repo
stringlengths 7
58
| path
stringlengths 4
131
| url
stringlengths 44
195
| license
stringclasses 5
values |
---|---|---|---|---|---|---|---|
jasmine.Runner = function(env) {
var self = this;
self.env = env;
self.queue = new jasmine.Queue(env);
self.before_ = [];
self.after_ = [];
self.suites_ = [];
}; | Runner
@constructor
@param {jasmine.Env} env | jasmine.Runner ( env ) | javascript | phonegap/phonegap-start | www/spec/lib/jasmine-1.2.0/jasmine.js | https://github.com/phonegap/phonegap-start/blob/master/www/spec/lib/jasmine-1.2.0/jasmine.js | Apache-2.0 |
jasmine.Spec = function(env, suite, description) {
if (!env) {
throw new Error('jasmine.Env() required');
}
if (!suite) {
throw new Error('jasmine.Suite() required');
}
var spec = this;
spec.id = env.nextSpecId ? env.nextSpecId() : null;
spec.env = env;
spec.suite = suite;
spec.description = description;
spec.queue = new jasmine.Queue(env);
spec.afterCallbacks = [];
spec.spies_ = [];
spec.results_ = new jasmine.NestedResults();
spec.results_.description = description;
spec.matchersClass = null;
}; | Internal representation of a Jasmine specification, or test.
@constructor
@param {jasmine.Env} env
@param {jasmine.Suite} suite
@param {String} description | jasmine.Spec ( env , suite , description ) | javascript | phonegap/phonegap-start | www/spec/lib/jasmine-1.2.0/jasmine.js | https://github.com/phonegap/phonegap-start/blob/master/www/spec/lib/jasmine-1.2.0/jasmine.js | Apache-2.0 |
jasmine.Spec.prototype.log = function() {
return this.results_.log(arguments);
}; | All parameters are pretty-printed and concatenated together, then written to the spec's output.
Be careful not to leave calls to <code>jasmine.log</code> in production code. | jasmine.Spec.prototype.log ( ) | javascript | phonegap/phonegap-start | www/spec/lib/jasmine-1.2.0/jasmine.js | https://github.com/phonegap/phonegap-start/blob/master/www/spec/lib/jasmine-1.2.0/jasmine.js | Apache-2.0 |
jasmine.Spec.prototype.addMatcherResult = function(result) {
this.results_.addResult(result);
}; | @param {jasmine.ExpectationResult} result | jasmine.Spec.prototype.addMatcherResult ( result ) | javascript | phonegap/phonegap-start | www/spec/lib/jasmine-1.2.0/jasmine.js | https://github.com/phonegap/phonegap-start/blob/master/www/spec/lib/jasmine-1.2.0/jasmine.js | Apache-2.0 |
jasmine.Suite = function(env, description, specDefinitions, parentSuite) {
var self = this;
self.id = env.nextSuiteId ? env.nextSuiteId() : null;
self.description = description;
self.queue = new jasmine.Queue(env);
self.parentSuite = parentSuite;
self.env = env;
self.before_ = [];
self.after_ = [];
self.children_ = [];
self.suites_ = [];
self.specs_ = [];
}; | Internal representation of a Jasmine suite.
@constructor
@param {jasmine.Env} env
@param {String} description
@param {Function} specDefinitions
@param {jasmine.Suite} parentSuite | jasmine.Suite ( env , description , specDefinitions , parentSuite ) | javascript | phonegap/phonegap-start | www/spec/lib/jasmine-1.2.0/jasmine.js | https://github.com/phonegap/phonegap-start/blob/master/www/spec/lib/jasmine-1.2.0/jasmine.js | Apache-2.0 |
jasmine.WaitsForBlock = function(env, timeout, latchFunction, message, spec) {
this.timeout = timeout || env.defaultTimeoutInterval;
this.latchFunction = latchFunction;
this.message = message;
this.totalTimeSpentWaitingForLatch = 0;
jasmine.Block.call(this, env, null, spec);
}; | A block which waits for some condition to become true, with timeout.
@constructor
@extends jasmine.Block
@param {jasmine.Env} env The Jasmine environment.
@param {Number} timeout The maximum time in milliseconds to wait for the condition to become true.
@param {Function} latchFunction A function which returns true when the desired condition has been met.
@param {String} message The message to display if the desired condition hasn't been met within the given time period.
@param {jasmine.Spec} spec The Jasmine spec. | jasmine.WaitsForBlock ( env , timeout , latchFunction , message , spec ) | javascript | phonegap/phonegap-start | www/spec/lib/jasmine-1.2.0/jasmine.js | https://github.com/phonegap/phonegap-start/blob/master/www/spec/lib/jasmine-1.2.0/jasmine.js | Apache-2.0 |
formatBytes(bytes, decimals) {
if (bytes === 0) return '0 Bytes'
let k = 1000
let sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
let i = Math.floor(Math.log(bytes) / Math.log(k))
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
} | Format raw bytes into human readable size.
@param {number} bytes - number of bytes.
@returns {string} human readable size. | formatBytes ( bytes , decimals ) | javascript | lirantal/dockly | widgets/images/imageList.widget.js | https://github.com/lirantal/dockly/blob/master/widgets/images/imageList.widget.js | MIT |
getSelectedImage() {
return this.widget.getItem(this.widget.selected).getContent().toString().trim().split(' ').shift()
} | returns a selected container from the containers listbox
@return {string} container id | getSelectedImage ( ) | javascript | lirantal/dockly | widgets/images/imageList.widget.js | https://github.com/lirantal/dockly/blob/master/widgets/images/imageList.widget.js | MIT |
getSelectedService() {
return this.widget.getItem(this.widget.selected).getContent().toString().trim().split(' ').shift()
} | returns a selected service from the services listbox
@return {string} service id | getSelectedService ( ) | javascript | lirantal/dockly | widgets/services/servicesList.widget.js | https://github.com/lirantal/dockly/blob/master/widgets/services/servicesList.widget.js | MIT |
Cli.prototype.cliParse = function () {
return commandLineArgs(this.cliOpts)
} | @method cliParse
@return {object} [description] | Cli.prototype.cliParse ( ) | javascript | lirantal/dockly | src/cli.js | https://github.com/lirantal/dockly/blob/master/src/cli.js | MIT |
app.get("/page", (req, res) => {
// Extract the URL from the query parameters
const url = req.query.url;
// Call the scrap function to scrape the specified page
scrap(url);
// Send a response without any content
res.send();
}); | Endpoint to scrape a single page.
@name GET /page
@function
@memberof app
@param {string} url - The URL of the page to be scraped.
@returns {void} | (anonymous) | javascript | Page-Replica/page-replica | api.js | https://github.com/Page-Replica/page-replica/blob/master/api.js | MIT |
app.get("/sitemap", (req, res) => {
// Create a new instance of Sitemapper
const sitemap = new Sitemapper();
// Fetch the sitemap from the specified URL
sitemap.fetch(req.query.url).then(function ({ sites }) {
// Extract the list of URLs from the fetched sitemap
const urls = sites;
// Set an interval to scrape each URL with a delay of 3000 milliseconds (3 seconds)
const interval = setInterval(() => {
const url = urls.shift();
if (!url) {
// If there are no more URLs, clear the interval
clearInterval(interval);
return;
}
// Call the scrap function to scrape the current URL
scrap(url);
}, 3000);
});
// Send a response without any content
res.send();
}); | Endpoint to scrape pages from a sitemap.
@name GET /sitemap
@function
@memberof app
@param {string} url - The URL of the sitemap to be scraped.
@returns {void} | (anonymous) | javascript | Page-Replica/page-replica | api.js | https://github.com/Page-Replica/page-replica/blob/master/api.js | MIT |
const createFolders = (directory) => {
const folders = directory.split(path.sep);
folders.shift();
let currentPath = CONFIG.cacheFolder;
folders.forEach((folder) => {
currentPath = path.join(currentPath, folder);
if (!fs.existsSync(currentPath)) {
fs.mkdirSync(currentPath);
}
});
}; | Function to create necessary folders based on the provided directory path.
@param {string} directory - The directory path to create folders for. | createFolders | javascript | Page-Replica/page-replica | index.js | https://github.com/Page-Replica/page-replica/blob/master/index.js | MIT |
const scrap = async (pathUrl) => {
try {
// Launch Puppeteer browser
const browser = await puppeteer.launch({
headless: "new",
args: ["--no-sandbox", "--disable-setuid-sandbox"],
});
// Create a new page in the browser
const page = await browser.newPage();
// Navigate to the specified URL and wait until the page is fully loaded
await page.goto(pathUrl, { waitUntil: "networkidle2" });
// Get the outer HTML of the entire document
let html = await page.evaluate(() => document.documentElement.outerHTML);
// Remove JavaScript code from the HTML if configured to do so
if (CONFIG.removeJS) {
html = html.replace(
/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
"",
);
}
// Add base URL to the head if configured to do so
if (CONFIG.addBaseURL) {
html = html.replace(/<head>/gi, `<head><base href="${CONFIG.baseUrl}">`);
}
// Create necessary folders for caching based on the URL
createFolders(pathUrl);
// Generate a path for caching by removing the protocol (http/https)
const path = pathUrl.replace(/(^\w+:|^)\/\//, "");
// Write the HTML content to a file in the cache folder
fs.writeFileSync(`${CONFIG.cacheFolder}/${path}/index.html`, html);
// Close the Puppeteer browser
await browser.close();
} catch (error) {
// Log any errors that occur during the scraping process
console.error(error);
}
};
// Export the scraping function for external use
exports.scrap = scrap; | Main scraping function.
@param {string} pathUrl - The URL to scrape. | scrap | javascript | Page-Replica/page-replica | index.js | https://github.com/Page-Replica/page-replica/blob/master/index.js | MIT |
async function getENV(t,e,n){let i=$.getjson(t,n),s=i?.[e]?.Settings||n?.[e]?.Settings||n?.Default?.Settings,g=i?.[e]?.Configs||n?.[e]?.Configs||n?.Default?.Configs,f=i?.[e]?.Caches||void 0;if("string"==typeof f&&(f=JSON.parse(f)),"undefined"!=typeof $argument){if($argument){let t=Object.fromEntries($argument.split("&").map((t=>t.split("=")))),e={};for(var a in t)o(e,a,t[a]);Object.assign(s,e)}function o(t,e,n){e.split(".").reduce(((t,i,s)=>t[i]=e.split(".").length===++s?n:t[i]||{}),t)}}return{Settings:s,Caches:f,Configs:g}} | Get Environment Variables
@author VirgilClyne
@param {String} t - Persistent Store Key
@param {String} e - Platform Name
@param {Object} n - Default DataBase
@return {Promise<*>} | (anonymous) | javascript | DualSubs/Universal | archive/js/v0.6/DualSubs.VTT.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v0.6/DualSubs.VTT.beta.js | Apache-2.0 |
async function getCache(type, settings, caches = {}) {
$.log(`⚠ ${$.name}, Get Cache`, "");
let Indices = {};
Indices.Index = await getIndex(settings, caches);
if (Indices.Index !== -1) {
for await (var language of settings.Languages) Indices[language] = await getDataIndex(Indices.Index, language)
if (type == "Official") {
// 修正缓存
if (Indices[settings.Languages[0]] !== -1) {
Indices[settings.Languages[1]] = caches[Indices.Index][settings.Languages[1]].findIndex(data => {
if (data.OPTION?.FORCED !== "YES" && data.OPTION["GROUP-ID"] == caches[Indices.Index][settings.Languages[0]][Indices[settings.Languages[0]]].OPTION["GROUP-ID"] && data.OPTION.CHARACTERISTICS == caches[Indices.Index][settings.Languages[0]][Indices[settings.Languages[0]]].OPTION.CHARACTERISTICS) return true;
});
if (Indices[settings.Languages[1]] == -1) {
Indices[settings.Languages[1]] = caches[Indices.Index][settings.Languages[1]].findIndex(data => {
if (data.OPTION?.FORCED !== "YES" && data.OPTION["GROUP-ID"] == caches[Indices.Index][settings.Languages[0]][Indices[settings.Languages[0]]].OPTION["GROUP-ID"]) return true;
});
};
};
};
}
$.log(`🎉 ${$.name}, Get Cache`, `Indices: ${JSON.stringify(Indices)}`, "");
return Indices
/***************** Fuctions *****************/
async function getIndex(settings, caches) {
return caches.findIndex(item => {
let URLs = [item?.URL];
for (var language of settings.Languages) URLs.push(item?.[language]?.map(d => getURIs(d)));
//$.log(`🎉 ${$.name}, 调试信息`, " Get Index", `URLs: ${URLs}`, "");
return URLs.flat(Infinity).some(URL => url.includes(URL || null));
})
};
async function getDataIndex(index, lang) { return caches?.[index]?.[lang]?.findIndex(item => getURIs(item).flat(Infinity).some(URL => url.includes(URL || null))); };
function getURIs(item) { return [item?.URI, item?.VTTs] }
}; | Get Cache
@author VirgilClyne
@param {String} type - type
@param {Object} settings - settings
@param {Object} cache - cache
@return {Promise<*>} | getCache ( type , settings , caches = { } ) | javascript | DualSubs/Universal | archive/js/v0.6/DualSubs.VTT.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v0.6/DualSubs.VTT.beta.js | Apache-2.0 |
async function setCache(index = -1, target = {}, sources = {}, num = 1) {
$.log(`⚠ ${$.name}, Set Cache`, "");
// 刷新播放记录,所以始终置顶
if (index !== -1) delete target[index] // 删除旧记录
target.unshift(sources) // 头部插入缓存
target = target.filter(Boolean).slice(0, num) // 设置缓存数量
//$.log(`🎉 ${$.name}, Set Cache`, `target: ${JSON.stringify(target)}`, "");
return target
}; | Set Cache
@author VirgilClyne
@param {Number} index - index
@param {Object} target - target
@param {Object} sources - sources
@param {Number} num - num
@return {Promise<*>} | setCache ( index = - 1 , target = { } , sources = { } , num = 1 ) | javascript | DualSubs/Universal | archive/js/v0.6/DualSubs.VTT.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v0.6/DualSubs.VTT.beta.js | Apache-2.0 |
async function getWebVTT(request) { return await $.http.get(request).then(response => VTT.parse(response.body)); } | getWebVTT
@author VirgilClyne
@param {object} request - request
@return {Promise<*>} | (anonymous) | javascript | DualSubs/Universal | archive/js/v0.6/DualSubs.VTT.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v0.6/DualSubs.VTT.beta.js | Apache-2.0 |
async function combineText(text1, text2, position) { return (position == "Forward") ? text2 + "\n" + text1 : (position == "Reverse") ? text1 + "\n" + text2 : text2 + "\n" + text1; } | combineText
@author VirgilClyne
@param {String} text1 - text1
@param {String} text2 - text2
@param {String} position - position
@return {Promise<*>} | combineText ( text1 , text2 , position ) | javascript | DualSubs/Universal | archive/js/v0.6/DualSubs.VTT.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v0.6/DualSubs.VTT.beta.js | Apache-2.0 |
async function CombineDualSubs(Sub1 = { headers: {}, CSS: {}, body: [] }, Sub2 = { headers: {}, CSS: {}, body: [] }, Offset = 0, Tolerance = 1000, Options = ["Forward"]) {
$.log(`⚠ ${$.name}, Combine Dual Subtitles`, `Offset:${Offset}, Tolerance:${Tolerance}, Options:${Options}`, "");
//$.log(`🚧 ${$.name}, Combine Dual Subtitles`,`Sub1内容: ${JSON.stringify(Sub1)}`, "");
//$.log(`🚧 ${$.name}, Combine Dual Subtitles`,`Sub2内容: ${JSON.stringify(Sub2)}`, "");
let DualSub = Options.includes("Reverse") ? Sub2 : Sub1
//$.log(`🚧 ${$.name}, Combine Dual Subtitles`,`let DualSub内容: ${JSON.stringify(DualSub)}`, "");
// 有序数列 用不着排序
//FirstSub.body.sort((x, y) => x - y);
//SecondSub.body.sort((x, y) => x - y);
const length1 = Sub1.body.length, length2 = Sub2.body.length;
let index0 = 0, index1 = 0, index2 = 0;
// 双指针法查找两个数组中的相同元素
while (index1 < length1 && index2 < length2) {
const timeStamp1 = Sub1.body[index1].timeStamp, timeStamp2 = Sub2.body[index2].timeStamp + Offset;
const text1 = Sub1.body[index1]?.text ?? "", text2 = Sub2.body[index2]?.text ?? "";
//$.log(`🚧`, `index1/length1: ${index1}/${length1}`, `index2/length2: ${index2}/${length2}`, "");
//$.log(`🚧`, `timeStamp1: ${timeStamp1}`, `timeStamp2: ${timeStamp2}`, "");
//$.log(`🚧`, `text1: ${text1}`, `text2: ${text2}`, "");
if (Math.abs(timeStamp1 - timeStamp2) <= Tolerance) {
index0 = Options.includes("Reverse") ? index2 : index1;
// 多行字幕交替插入
/*
if (Array.isArray(text1) && Array.isArray(text2)) {
let a = Options.includes("Reverse") ? text2 : text1;
let b = Options.includes("Reverse") ? text1 : text2;
let c = [];
let length = a.length > b.length ? a.length : b.length;
for (let j = 0; j < length; j++) {
if (a[j]) c.push(a[j]);
if (b[j]) c.push(b[j]);
}
DualSub.body[index0].text = c;
} else
*/
DualSub.body[index0].text = Options.includes("Reverse") ? `${text2}\n${text1}` : Options.includes("ShowOnly") ? text2 : `${text1}\n${text2}`;
//$.log(`🚧`, `index0: ${index0}`, `text: ${DualSub.body[index0].text}`, "");
//DualSub.body[index0].timeStamp = Options.includes("Reverse") ? timeStamp2 : timeStamp1;
//DualSub.body[index0].index = Options.includes("Reverse") ? index2 : index1;
}
if (timeStamp2 > timeStamp1) index1++
else if (timeStamp2 < timeStamp1) index2++
else { index1++; index2++ }
}
//$.log(`🎉 ${$.name}, Combine Dual Subtitles`, `return DualSub内容: ${JSON.stringify(DualSub)}`, "");
return DualSub;
}; | Combine Dual Subtitles
@author VirgilClyne
@param {Object} Sub1 - Sub1
@param {Object} Sub2 - Sub2
@param {Number} Offset - Offset
@param {Number} Tolerance - Tolerance
@param {Array} options - options = ["Forward", "Reverse", "ShowOnly"]
@return {Promise<*>} | CombineDualSubs ( Sub1 = { headers : { } , CSS : { } , body : [ ] } , Sub2 = { headers : { } , CSS : { } , body : [ ] } , Offset = 0 , Tolerance = 1000 , Options = [ "Forward" ] ) | javascript | DualSubs/Universal | archive/js/v0.6/DualSubs.VTT.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v0.6/DualSubs.VTT.beta.js | Apache-2.0 |
async function chunk(source, length) {
$.log(`⚠ ${$.name}, Chunk Array`, "");
var index = 0, target = [];
while(index < source.length) target.push(source.slice(index, index += length));
//$.log(`🎉 ${$.name}, Chunk Array`, `target: ${JSON.stringify(target)}`, "");
return target;
}; | Chunk Array
@author VirgilClyne
@param {Array} source - source
@param {Number} length - number
@return {Promise<*>} | chunk ( source , length ) | javascript | DualSubs/Universal | archive/js/v0.6/DualSubs.VTT.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v0.6/DualSubs.VTT.beta.js | Apache-2.0 |
async function CombineDualSubs(Format = "vtt", Sub1 = { headers: {}, CSS: {}, body: [], events: [] }, Sub2 = { headers: {}, CSS: {}, body: [], events: [] }, Offset = 0, Tolerance = 1000, Options = ["Forward"]) {
$.log(`⚠ ${$.name}, Combine Dual Subtitles`, `Offset:${Offset}, Tolerance:${Tolerance}, Options:${Options}`, "");
let DualSub = Options.includes("Reverse") ? Sub2 : Sub1
let index0 = 0, index1 = 0, index2 = 0;
if (Format == "vtt") {
const length1 = Sub1.body.length, length2 = Sub2.body.length;
while (index1 < length1 && index2 < length2) {
const timeStamp1 = Sub1.body[index1].timeStamp, timeStamp2 = Sub2.body[index2].timeStamp + Offset;
const text1 = Sub1.body[index1]?.text ?? "", text2 = Sub2.body[index2]?.text ?? "";
if (Math.abs(timeStamp1 - timeStamp2) <= Tolerance) {
index0 = Options.includes("Reverse") ? index2 : index1;
DualSub.body[index0].text = Options.includes("Reverse") ? `${text2}\n${text1}` : Options.includes("ShowOnly") ? text2 : `${text1}\n${text2}`;
}
if (timeStamp2 > timeStamp1) index1++
else if (timeStamp2 < timeStamp1) index2++
else index1++; index2++
}
} else if (Format == "json3") {
const length1 = Sub1.events.length, length2 = Sub2.events.length;
while (index1 < length1 && index2 < length2) {
const timeStamp1 = Sub1.events[index1].tStartMs, timeStamp2 = Sub2.events[index2].tStartMs + Offset;
const text1 = Sub1.events[index1]?.segs[0].utf8 ?? "", text2 = Sub2.events[index2]?.segs[0].utf8 ?? "";
if (Math.abs(timeStamp1 - timeStamp2) <= Tolerance) {
index0 = Options.includes("Reverse") ? index2 : index1;
DualSub.events[index0].segs[0].utf8 = Options.includes("Reverse") ? `${text2}\n${text1}` : `${text1}\n${text2}`;
}
if (timeStamp2 > timeStamp1) index1++
else if (timeStamp2 < timeStamp1) index2++
else index1++; index2++
};
} else if (Format == "svr3") {
}
//$.log(`🎉 ${$.name}, Combine Dual Subtitles`, `return DualSub内容: ${JSON.stringify(DualSub)}`, "");
return DualSub;
}; | Combine Dual Subtitles
@author VirgilClyne
@param {Object} Format - Format
@param {Object} Sub1 - Sub1
@param {Object} Sub2 - Sub2
@param {Number} Offset - Offset
@param {Number} Tolerance - Tolerance
@param {Array} options - options = ["Forward", "Reverse", "ShowOnly"]
@return {Promise<*>} | CombineDualSubs ( Format = "vtt" , Sub1 = { headers : { } , CSS : { } , body : [ ] , events : [ ] } , Sub2 = { headers : { } , CSS : { } , body : [ ] , events : [ ] } , Offset = 0 , Tolerance = 1000 , Options = [ "Forward" ] ) | javascript | DualSubs/Universal | archive/js/v0.6/DualSubs.SUB.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v0.6/DualSubs.SUB.js | Apache-2.0 |
function setENV(name, platform, database) {
$.log(`☑️ ${$.name}, Set Environment Variables`, "");
let { Settings, Caches, Configs } = getENV(name, platform, database);
/***************** Settings *****************/
traverseObject(Settings, (key, value) => {
if (value === "true" || value === "false") value = JSON.parse(value); // 字符串转Boolean
else if (typeof value === "string") {
if (value?.includes(",")) value = value.split(","); // 字符串转数组
else if (!isNaN(value)) value = parseInt(value, 10) // 字符串转数字
};
return value;
});
if (!Array.isArray(Settings?.Types)) Settings.Types = (Settings.Types) ? [Settings.Types] : []; // 只有一个选项时,无逗号分隔
/*
if (Array.isArray(Settings?.Types)) {
if (!Settings?.API?.GoogleCloud?.Auth) Settings.Types = Settings.Types.filter(e => e !== "GoogleCloud"); // 移除不可用类型
if (!Settings?.API?.Azure?.Auth) Settings.Types = Settings.Types.filter(e => e !== "Azure");
if (!Settings?.API?.DeepL?.Auth) Settings.Types = Settings.Types.filter(e => e !== "DeepL");
}
*/
$.log(`✅ ${$.name}, Set Environment Variables`, `Settings: ${typeof Settings}`, `Settings内容: ${JSON.stringify(Settings)}`, "");
/***************** Caches *****************/
//$.log(`✅ ${$.name}, Set Environment Variables`, `Caches: ${typeof Caches}`, `Caches内容: ${JSON.stringify(Caches)}`, "");
if (typeof Caches.Playlists !== "object" || Array.isArray(Caches.Playlists)) Caches.Playlists = {}; // 创建Playlists缓存
Caches.Playlists.Master = new Map(JSON.parse(Caches?.Playlists?.Master || "[]")); // Strings转Array转Map
Caches.Playlists.Subtitle = new Map(JSON.parse(Caches?.Playlists?.Subtitle || "[]")); // Strings转Array转Map
if (typeof Caches?.Subtitles !== "object") Caches.Subtitles = new Map(JSON.parse(Caches?.Subtitles || "[]")); // Strings转Array转Map
/***************** Configs *****************/
return { Settings, Caches, Configs };
function traverseObject(o,c){for(var t in o){var n=o[t];o[t]="object"==typeof n&&null!==n?traverseObject(n,c):c(t,n)}return o}
}; | Set Environment Variables
@author VirgilClyne
@param {String} name - Persistent Store Key
@param {String} platform - Platform Name
@param {Object} database - Default DataBase
@return {Object} { Settings, Caches, Configs } | setENV ( name , platform , database ) | javascript | DualSubs/Universal | archive/js/v0.8/DualSubs.Subtitles.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v0.8/DualSubs.Subtitles.response.beta.js | Apache-2.0 |
function getPlaylistCache(url, cache, languages) {
$.log(`☑️ ${$.name}, getPlaylistCache`, "");
let masterPlaylistURL = "";
let subtitlesPlaylist = {};
let subtitlesPlaylistIndex = 0;
cache?.forEach((Value, Key) => {
languages?.forEach(language => {
let Array = Value?.[language];
if (Array?.some((Object, Index) => {
if (url.includes(Object?.URI || Object?.OPTION?.URI || null)) {
subtitlesPlaylistIndex = Index;
$.log(`🚧 ${$.name}, getPlaylistCache`, `subtitlesPlaylistIndex: ${subtitlesPlaylistIndex}`, "");
return true;
} else return false;
})) {
masterPlaylistURL = Key;
subtitlesPlaylist = Value;
//$.log(`🚧 ${$.name}, getPlaylistCache`, `masterPlaylistURL: ${masterPlaylistURL}`, `subtitlesPlaylist: ${JSON.stringify(subtitlesPlaylist)}`, "");
};
});
});
$.log(`✅ ${$.name}, getPlaylistCache`, `masterPlaylistURL: ${JSON.stringify(masterPlaylistURL)}`, "");
return { masterPlaylistURL, subtitlesPlaylist, subtitlesPlaylistIndex };
}; | Get Playlist Cache
@author VirgilClyne
@param {String} url - Request URL / Master Playlist URL
@param {Map} cache - Playlist Cache
@param {Array} languages - Languages
@return {Promise<Object>} { masterPlaylistURL, subtitlesPlaylist, subtitlesPlaylistIndex } | getPlaylistCache ( url , cache , languages ) | javascript | DualSubs/Universal | archive/js/v0.8/DualSubs.Subtitles.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v0.8/DualSubs.Subtitles.response.beta.js | Apache-2.0 |
function getSubtitlesCache(url, cache, languages) {
$.log(`☑️ ${$.name}, getSubtitlesCache`, "");
let subtitlesPlaylistURL = "";
let subtitles = [];
let subtitlesIndex = 0;
cache?.forEach((Value, Key) => {
if (Value?.some((String, Index) => {
if (url.includes(String || null)) {
subtitlesIndex = Index;
$.log(`🚧 ${$.name}, getSubtitlesCache`, `subtitlesIndex: ${subtitlesIndex}`, "");
return true;
} else return false;
})) {
subtitlesPlaylistURL = Key;
subtitles = Value;
//$.log(`🚧 ${$.name}, getSubtitlesCache, subtitlesPlaylistURL: ${subtitlesPlaylistURL}`, "");
};
});
$.log(`✅ ${$.name}, getSubtitlesCache, subtitlesPlaylistURL: ${subtitlesPlaylistURL}`, "");
return { subtitlesPlaylistURL, subtitles, subtitlesIndex };
}; | Get Subtitles Cache
@author VirgilClyne
@param {String} url - Request URL / Subtitles URL
@param {Map} cache - Subtitles Cache
@param {Array} languages - Languages
@return {Promise<Object>} { subtitlesPlaylistURL, subtitles, subtitlesIndex } | getSubtitlesCache ( url , cache , languages ) | javascript | DualSubs/Universal | archive/js/v0.8/DualSubs.Subtitles.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v0.8/DualSubs.Subtitles.response.beta.js | Apache-2.0 |
function getSubtitlesArray(url, index, playlistsCache, subtitlesCache, languages) {
$.log(`☑️ ${$.name}, getSubtitlesArray`, "");
const subtitlesPlaylistValue = playlistsCache?.get(url) || {};
let subtitlesPlaylistURL0 = subtitlesPlaylistValue?.[languages[0]]?.[index]?.URL || subtitlesPlaylistValue?.[languages[0]]?.[0]?.URL;
let subtitlesPlaylistURL1 = subtitlesPlaylistValue?.[languages[1]]?.[index]?.URL || subtitlesPlaylistValue?.[languages[1]]?.[0]?.URL;
$.log(`🚧 ${$.name}, getSubtitlesArray`, `subtitlesPlaylistURL0: ${subtitlesPlaylistURL0}, subtitlesPlaylistURL1: ${subtitlesPlaylistURL1}`, "");
// 查找字幕文件地址vtt缓存(map)
let subtitlesURIArray0 = subtitlesCache.get(subtitlesPlaylistURL0) || [];
let subtitlesURIArray1 = subtitlesCache.get(subtitlesPlaylistURL1) || [];
//$.log(`🚧 ${$.name}, getSubtitlesArray`, `subtitlesURIArray0: ${JSON.stringify(subtitlesURIArray0)}, subtitlesURIArray1: ${JSON.stringify(subtitlesURIArray1)}`, "");
$.log(`✅ ${$.name}, getSubtitlesArray`, "");
return { subtitlesURIArray0, subtitlesURIArray1 };
}; | Get Subtitles Array
@author VirgilClyne
@param {String} url - Request URL / Master Playlist URL
@param {Number} index - Subtitles Playlist Index
@param {Map} playlistsCache - Playlists Cache
@param {Map} subtitlesCache - Subtitles Cache
@param {Array} languages - Languages
@return {Promise<Object>} { subtitlesURIArray0, subtitlesURIArray1 } | getSubtitlesArray ( url , index , playlistsCache , subtitlesCache , languages ) | javascript | DualSubs/Universal | archive/js/v0.8/DualSubs.Subtitles.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v0.8/DualSubs.Subtitles.response.beta.js | Apache-2.0 |
function setCache(cache, cacheSize = 100) {
$.log(`☑️ ${$.name}, Set Cache, cacheSize: ${cacheSize}`, "");
cache = Array.from(cache || []); // Map转Array
cache = cache.slice(-cacheSize); // 限制缓存大小
$.log(`✅ ${$.name}, Set Cache`, "");
return cache;
}; | Set Cache
@author VirgilClyne
@param {Map} cache - Playlists Cache / Subtitles Cache
@param {Number} cacheSize - Cache Size
@return {Boolean} isSaved | setCache ( cache , cacheSize = 100 ) | javascript | DualSubs/Universal | archive/js/v0.8/DualSubs.Subtitles.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v0.8/DualSubs.Subtitles.response.beta.js | Apache-2.0 |
function constructSubtitlesQueue(request, fileName, VTTs0 = [], VTTs1 = []) {
$.log(`☑️ ${$.name}, Construct Subtitles Queue`, `fileName: ${fileName}`, "");
let requests = [];
$.log(`🚧 ${$.name}, Construct Subtitles Queue, VTTs0.length: ${VTTs0.length}, VTTs1.length: ${VTTs1.length}`, "")
switch (VTTs1.length) {
case 0: // 长度为0,无须计算
break;
case 1: // 长度为1,无须计算
let _request = {
"url": VTTs1[0],
"headers": request.headers
};
requests.push(_request);
break;
case VTTs0.length: { // 长度相等,一一对应,无须计算
//request.url = VTTs1.find(item => item?.includes(fileName)) || VTTs1[0];
let Index1 = VTTs1.findIndex(item => item?.includes(fileName));
$.log(`🚧 ${$.name}, Construct Subtitles Queue`, `Index1: ${Index1}`, "");
let _request = {
"url": VTTs1[Index1],
"headers": request.headers
};
requests.push(_request);
break;
};
default: { // 长度不等,需要计算
$.log(`⚠ ${$.name}, Construct Subtitles Queue, 长度不等,需要计算`, "")
// 查询当前字幕在原字幕队列中的位置
let Index0 = VTTs0.findIndex(item => item?.includes(fileName));
$.log(`🚧 ${$.name}, Construct Subtitles Queue`, `Index0: ${Index0}`, "")
// 计算当前字幕在原字幕队列中的百分比
let Position0 = Index0 / VTTs0.length;
$.log(`🚧 ${$.name}, Construct Subtitles Queue`, `Position0: ${Position0}`, "");
// 根据百分比计算当前字幕在新字幕队列中的位置
//let Index1 = VTTs1.findIndex(item => item.includes(fileName));
let Index1 = Math.round(Position0 * VTTs1.length);
$.log(`🚧 ${$.name}, Construct Subtitles Queue`, `Index1: ${Index1}`, "");
// 获取当前字幕在新字幕队列中的前后4个字幕
nearlyVTTs = VTTs1.slice((Index1 - 2 < 0) ? 0 : Index1 - 2, Index1 + 2);
requests = nearlyVTTs.map(url => {
let _request = {
"url": url,
"headers": request.headers
};
return _request;
});
break;
};
};
//$.log(`🚧 ${$.name}, Construct Subtitles Queue`, `requests: ${JSON.stringify(requests)}`, "");
$.log(`✅ ${$.name}, Construct Subtitles Queue`, "");
return requests;
}; | Construct Subtitles Queue
@author VirgilClyne
@param {String} fileName - Request URL
@param {Array} VTTs0 - First Language Subtitles Array
@param {Array} VTTs1 - Second Language Subtitles Array
@return {Array<*>} Subtitles Requests Queue | constructSubtitlesQueue ( request , fileName , VTTs0 = [ ] , VTTs1 = [ ] ) | javascript | DualSubs/Universal | archive/js/v0.8/DualSubs.Subtitles.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v0.8/DualSubs.Subtitles.response.beta.js | Apache-2.0 |
function inRange(a, min, max) {
return min <= a && a <= max;
} | @param {number} a The number to test.
@param {number} min The minimum value in the range, inclusive.
@param {number} max The maximum value in the range, inclusive.
@return {boolean} True if a >= min and a <= max. | inRange ( a , min , max ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function includes(array, item) {
return array.indexOf(item) !== -1;
} | @param {!Array.<*>} array The array to check.
@param {*} item The item to look for in the array.
@return {boolean} True if the item appears in the array. | includes ( array , item ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function stringToCodePoints(string) {
// https://heycam.github.io/webidl/#dfn-obtain-unicode
// 1. Let S be the DOMString value.
var s = String(string);
// 2. Let n be the length of S.
var n = s.length;
// 3. Initialize i to 0.
var i = 0;
// 4. Initialize U to be an empty sequence of Unicode characters.
var u = [];
// 5. While i < n:
while (i < n) {
// 1. Let c be the code unit in S at index i.
var c = s.charCodeAt(i);
// 2. Depending on the value of c:
// c < 0xD800 or c > 0xDFFF
if (c < 0xD800 || c > 0xDFFF) {
// Append to U the Unicode character with code point c.
u.push(c);
}
// 0xDC00 ≤ c ≤ 0xDFFF
else if (0xDC00 <= c && c <= 0xDFFF) {
// Append to U a U+FFFD REPLACEMENT CHARACTER.
u.push(0xFFFD);
}
// 0xD800 ≤ c ≤ 0xDBFF
else if (0xD800 <= c && c <= 0xDBFF) {
// 1. If i = n−1, then append to U a U+FFFD REPLACEMENT
// CHARACTER.
if (i === n - 1) {
u.push(0xFFFD);
}
// 2. Otherwise, i < n−1:
else {
// 1. Let d be the code unit in S at index i+1.
var d = s.charCodeAt(i + 1);
// 2. If 0xDC00 ≤ d ≤ 0xDFFF, then:
if (0xDC00 <= d && d <= 0xDFFF) {
// 1. Let a be c & 0x3FF.
var a = c & 0x3FF;
// 2. Let b be d & 0x3FF.
var b = d & 0x3FF;
// 3. Append to U the Unicode character with code point
// 2^16+2^10*a+b.
u.push(0x10000 + (a << 10) + b);
// 4. Set i to i+1.
i += 1;
}
// 3. Otherwise, d < 0xDC00 or d > 0xDFFF. Append to U a
// U+FFFD REPLACEMENT CHARACTER.
else {
u.push(0xFFFD);
}
}
}
// 3. Set i to i+1.
i += 1;
}
// 6. Return U.
return u;
} | @param {string} string Input string of UTF-16 code units.
@return {!Array.<number>} Code points. | stringToCodePoints ( string ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function codePointsToString(code_points) {
var s = '';
for (var i = 0; i < code_points.length; ++i) {
var cp = code_points[i];
if (cp <= 0xFFFF) {
s += String.fromCharCode(cp);
} else {
cp -= 0x10000;
s += String.fromCharCode((cp >> 10) + 0xD800,
(cp & 0x3FF) + 0xDC00);
}
}
return s;
} | @param {!Array.<number>} code_points Array of code points.
@return {string} string String of UTF-16 code units. | codePointsToString ( code_points ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function isASCIIByte(a) {
return 0x00 <= a && a <= 0x7F;
} | An ASCII byte is a byte in the range 0x00 to 0x7F, inclusive.
@param {number} a The number to test.
@return {boolean} True if a is in the range 0x00 to 0x7F, inclusive. | isASCIIByte ( a ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function Stream(tokens) {
/** @type {!Array.<number>} */
this.tokens = [].slice.call(tokens);
// Reversed as push/pop is more efficient than shift/unshift.
this.tokens.reverse();
} | A stream represents an ordered sequence of tokens.
@constructor
@param {!(Array.<number>|Uint8Array)} tokens Array of tokens that provide
the stream. | Stream ( tokens ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
endOfStream: function() {
return !this.tokens.length;
}, | @return {boolean} True if end-of-stream has been hit. | endOfStream ( ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
read: function() {
if (!this.tokens.length)
return end_of_stream;
return this.tokens.pop();
}, | When a token is read from a stream, the first token in the
stream must be returned and subsequently removed, and
end-of-stream must be returned otherwise.
@return {number} Get the next token from the stream, or
end_of_stream. | read ( ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
prepend: function(token) {
if (Array.isArray(token)) {
var tokens = /**@type {!Array.<number>}*/(token);
while (tokens.length)
this.tokens.push(tokens.pop());
} else {
this.tokens.push(token);
}
}, | When one or more tokens are prepended to a stream, those tokens
must be inserted, in given order, before the first token in the
stream.
@param {(number|!Array.<number>)} token The token(s) to prepend to the
stream. | prepend ( token ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
push: function(token) {
if (Array.isArray(token)) {
var tokens = /**@type {!Array.<number>}*/(token);
while (tokens.length)
this.tokens.unshift(tokens.shift());
} else {
this.tokens.unshift(token);
}
} | When one or more tokens are pushed to a stream, those tokens
must be inserted, in given order, after the last token in the
stream.
@param {(number|!Array.<number>)} token The tokens(s) to push to the
stream. | push ( token ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function decoderError(fatal, opt_code_point) {
if (fatal)
throw TypeError('Decoder error');
return opt_code_point || 0xFFFD;
} | @param {boolean} fatal If true, decoding errors raise an exception.
@param {number=} opt_code_point Override the standard fallback code point.
@return {number} The code point to insert on a decoding error. | decoderError ( fatal , opt_code_point ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function encoderError(code_point) {
throw TypeError('The code point ' + code_point + ' could not be encoded.');
} | @param {number} code_point The code point that could not be encoded.
@return {number} Always throws, no value is actually returned. | encoderError ( code_point ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function getEncoding(label) {
// 1. Remove any leading and trailing ASCII whitespace from label.
label = String(label).trim().toLowerCase();
// 2. If label is an ASCII case-insensitive match for any of the
// labels listed in the table below, return the corresponding
// encoding, and failure otherwise.
if (Object.prototype.hasOwnProperty.call(label_to_encoding, label)) {
return label_to_encoding[label];
}
return null;
} | @param {string} label The encoding label.
@return {?{name:string,labels:Array.<string>}} | getEncoding ( label ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function indexCodePointFor(pointer, index) {
if (!index) return null;
return index[pointer] || null;
} | @param {number} pointer The |pointer| to search for.
@param {(!Array.<?number>|undefined)} index The |index| to search within.
@return {?number} The code point corresponding to |pointer| in |index|,
or null if |code point| is not in |index|. | indexCodePointFor ( pointer , index ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function indexPointerFor(code_point, index) {
var pointer = index.indexOf(code_point);
return pointer === -1 ? null : pointer;
} | @param {number} code_point The |code point| to search for.
@param {!Array.<?number>} index The |index| to search within.
@return {?number} The first pointer corresponding to |code point| in
|index|, or null if |code point| is not in |index|. | indexPointerFor ( code_point , index ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function index(name) {
if (!('encoding-indexes' in global)) {
throw Error("Indexes missing." +
" Did you forget to include encoding-indexes.js first?");
}
return global['encoding-indexes'][name];
} | @param {string} name Name of the index.
@return {(!Array.<number>|!Array.<Array.<number>>)}
* | index ( name ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function indexGB18030RangesCodePointFor(pointer) {
// 1. If pointer is greater than 39419 and less than 189000, or
// pointer is greater than 1237575, return null.
if ((pointer > 39419 && pointer < 189000) || (pointer > 1237575))
return null;
// 2. If pointer is 7457, return code point U+E7C7.
if (pointer === 7457) return 0xE7C7;
// 3. Let offset be the last pointer in index gb18030 ranges that
// is equal to or less than pointer and let code point offset be
// its corresponding code point.
var offset = 0;
var code_point_offset = 0;
var idx = index('gb18030-ranges');
var i;
for (i = 0; i < idx.length; ++i) {
/** @type {!Array.<number>} */
var entry = idx[i];
if (entry[0] <= pointer) {
offset = entry[0];
code_point_offset = entry[1];
} else {
break;
}
}
// 4. Return a code point whose value is code point offset +
// pointer − offset.
return code_point_offset + pointer - offset;
} | @param {number} pointer The |pointer| to search for in the gb18030 index.
@return {?number} The code point corresponding to |pointer| in |index|,
or null if |code point| is not in the gb18030 index. | indexGB18030RangesCodePointFor ( pointer ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function indexGB18030RangesPointerFor(code_point) {
// 1. If code point is U+E7C7, return pointer 7457.
if (code_point === 0xE7C7) return 7457;
// 2. Let offset be the last code point in index gb18030 ranges
// that is equal to or less than code point and let pointer offset
// be its corresponding pointer.
var offset = 0;
var pointer_offset = 0;
var idx = index('gb18030-ranges');
var i;
for (i = 0; i < idx.length; ++i) {
/** @type {!Array.<number>} */
var entry = idx[i];
if (entry[1] <= code_point) {
offset = entry[1];
pointer_offset = entry[0];
} else {
break;
}
}
// 3. Return a pointer whose value is pointer offset + code point
// − offset.
return pointer_offset + code_point - offset;
} | @param {number} code_point The |code point| to locate in the gb18030 index.
@return {number} The first pointer corresponding to |code point| in the
gb18030 index. | indexGB18030RangesPointerFor ( code_point ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function indexShiftJISPointerFor(code_point) {
// 1. Let index be index jis0208 excluding all entries whose
// pointer is in the range 8272 to 8835, inclusive.
shift_jis_index = shift_jis_index ||
index('jis0208').map(function(code_point, pointer) {
return inRange(pointer, 8272, 8835) ? null : code_point;
});
var index_ = shift_jis_index;
// 2. Return the index pointer for code point in index.
return index_.indexOf(code_point);
} | @param {number} code_point The |code_point| to search for in the Shift_JIS
index.
@return {?number} The code point corresponding to |pointer| in |index|,
or null if |code point| is not in the Shift_JIS index. | indexShiftJISPointerFor ( code_point ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function indexBig5PointerFor(code_point) {
// 1. Let index be index Big5 excluding all entries whose pointer
big5_index_no_hkscs = big5_index_no_hkscs ||
index('big5').map(function(code_point, pointer) {
return (pointer < (0xA1 - 0x81) * 157) ? null : code_point;
});
var index_ = big5_index_no_hkscs;
// 2. If code point is U+2550, U+255E, U+2561, U+256A, U+5341, or
// U+5345, return the last pointer corresponding to code point in
// index.
if (code_point === 0x2550 || code_point === 0x255E ||
code_point === 0x2561 || code_point === 0x256A ||
code_point === 0x5341 || code_point === 0x5345) {
return index_.lastIndexOf(code_point);
}
// 3. Return the index pointer for code point in index.
return indexPointerFor(code_point, index_);
} | @param {number} code_point The |code_point| to search for in the big5
index.
@return {?number} The code point corresponding to |pointer| in |index|,
or null if |code point| is not in the big5 index. | indexBig5PointerFor ( code_point ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function TextDecoder(label, options) {
// Web IDL conventions
if (!(this instanceof TextDecoder))
throw TypeError('Called as a function. Did you forget \'new\'?');
label = label !== undefined ? String(label) : DEFAULT_ENCODING;
options = ToDictionary(options);
// A TextDecoder object has an associated encoding, decoder,
// stream, ignore BOM flag (initially unset), BOM seen flag
// (initially unset), error mode (initially replacement), and do
// not flush flag (initially unset).
/** @private */
this._encoding = null;
/** @private @type {?Decoder} */
this._decoder = null;
/** @private @type {boolean} */
this._ignoreBOM = false;
/** @private @type {boolean} */
this._BOMseen = false;
/** @private @type {string} */
this._error_mode = 'replacement';
/** @private @type {boolean} */
this._do_not_flush = false;
// 1. Let encoding be the result of getting an encoding from
// label.
var encoding = getEncoding(label);
// 2. If encoding is failure or replacement, throw a RangeError.
if (encoding === null || encoding.name === 'replacement')
throw RangeError('Unknown encoding: ' + label);
if (!decoders[encoding.name]) {
throw Error('Decoder not present.' +
' Did you forget to include encoding-indexes.js first?');
}
// 3. Let dec be a new TextDecoder object.
var dec = this;
// 4. Set dec's encoding to encoding.
dec._encoding = encoding;
// 5. If options's fatal member is true, set dec's error mode to
// fatal.
if (Boolean(options['fatal']))
dec._error_mode = 'fatal';
// 6. If options's ignoreBOM member is true, set dec's ignore BOM
// flag.
if (Boolean(options['ignoreBOM']))
dec._ignoreBOM = true;
// For pre-ES5 runtimes:
if (!Object.defineProperty) {
this.encoding = dec._encoding.name.toLowerCase();
this.fatal = dec._error_mode === 'fatal';
this.ignoreBOM = dec._ignoreBOM;
}
// 7. Return dec.
return dec;
} | @constructor
@param {string=} label The label of the encoding;
defaults to 'utf-8'.
@param {Object=} options | TextDecoder ( label , options ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function serializeStream(stream) {
// 1. Let token be the result of reading from stream.
// (Done in-place on array, rather than as a stream)
// 2. If encoding is UTF-8, UTF-16BE, or UTF-16LE, and ignore
// BOM flag and BOM seen flag are unset, run these subsubsteps:
if (includes(['UTF-8', 'UTF-16LE', 'UTF-16BE'], this._encoding.name) &&
!this._ignoreBOM && !this._BOMseen) {
if (stream.length > 0 && stream[0] === 0xFEFF) {
// 1. If token is U+FEFF, set BOM seen flag.
this._BOMseen = true;
stream.shift();
} else if (stream.length > 0) {
// 2. Otherwise, if token is not end-of-stream, set BOM seen
// flag and append token to stream.
this._BOMseen = true;
} else ;
}
// 4. Otherwise, return output.
return codePointsToString(stream);
} | @param {!Array.<number>} stream
@return {string}
@this {TextDecoder} | serializeStream ( stream ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
TextDecoder.prototype.decode = function decode(input, options) {
var bytes;
if (typeof input === 'object' && input instanceof ArrayBuffer) {
bytes = new Uint8Array(input);
} else if (typeof input === 'object' && 'buffer' in input &&
input.buffer instanceof ArrayBuffer) {
bytes = new Uint8Array(input.buffer,
input.byteOffset,
input.byteLength);
} else {
bytes = new Uint8Array(0);
}
options = ToDictionary(options);
// 1. If the do not flush flag is unset, set decoder to a new
// encoding's decoder, set stream to a new stream, and unset the
// BOM seen flag.
if (!this._do_not_flush) {
this._decoder = decoders[this._encoding.name]({
fatal: this._error_mode === 'fatal'});
this._BOMseen = false;
}
// 2. If options's stream is true, set the do not flush flag, and
// unset the do not flush flag otherwise.
this._do_not_flush = Boolean(options['stream']);
// 3. If input is given, push a copy of input to stream.
// TODO: Align with spec algorithm - maintain stream on instance.
var input_stream = new Stream(bytes);
// 4. Let output be a new stream.
var output = [];
/** @type {?(number|!Array.<number>)} */
var result;
// 5. While true:
while (true) {
// 1. Let token be the result of reading from stream.
var token = input_stream.read();
// 2. If token is end-of-stream and the do not flush flag is
// set, return output, serialized.
// TODO: Align with spec algorithm.
if (token === end_of_stream)
break;
// 3. Otherwise, run these subsubsteps:
// 1. Let result be the result of processing token for decoder,
// stream, output, and error mode.
result = this._decoder.handler(input_stream, token);
// 2. If result is finished, return output, serialized.
if (result === finished)
break;
if (result !== null) {
if (Array.isArray(result))
output.push.apply(output, /**@type {!Array.<number>}*/(result));
else
output.push(result);
}
// 3. Otherwise, if result is error, throw a TypeError.
// (Thrown in handler)
// 4. Otherwise, do nothing.
}
// TODO: Align with spec algorithm.
if (!this._do_not_flush) {
do {
result = this._decoder.handler(input_stream, input_stream.read());
if (result === finished)
break;
if (result === null)
continue;
if (Array.isArray(result))
output.push.apply(output, /**@type {!Array.<number>}*/(result));
else
output.push(result);
} while (!input_stream.endOfStream());
this._decoder = null;
}
// A TextDecoder object also has an associated serialize stream
// algorithm...
/**
* @param {!Array.<number>} stream
* @return {string}
* @this {TextDecoder}
*/
function serializeStream(stream) {
// 1. Let token be the result of reading from stream.
// (Done in-place on array, rather than as a stream)
// 2. If encoding is UTF-8, UTF-16BE, or UTF-16LE, and ignore
// BOM flag and BOM seen flag are unset, run these subsubsteps:
if (includes(['UTF-8', 'UTF-16LE', 'UTF-16BE'], this._encoding.name) &&
!this._ignoreBOM && !this._BOMseen) {
if (stream.length > 0 && stream[0] === 0xFEFF) {
// 1. If token is U+FEFF, set BOM seen flag.
this._BOMseen = true;
stream.shift();
} else if (stream.length > 0) {
// 2. Otherwise, if token is not end-of-stream, set BOM seen
// flag and append token to stream.
this._BOMseen = true;
} else ;
}
// 4. Otherwise, return output.
return codePointsToString(stream);
}
return serializeStream.call(this, output);
}; | @param {BufferSource=} input The buffer of bytes to decode.
@param {Object=} options
@return {string} The decoded string. | decode ( input , options ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function TextEncoder(label, options) {
// Web IDL conventions
if (!(this instanceof TextEncoder))
throw TypeError('Called as a function. Did you forget \'new\'?');
options = ToDictionary(options);
// A TextEncoder object has an associated encoding and encoder.
/** @private */
this._encoding = null;
/** @private @type {?Encoder} */
this._encoder = null;
// Non-standard
/** @private @type {boolean} */
this._do_not_flush = false;
/** @private @type {string} */
this._fatal = Boolean(options['fatal']) ? 'fatal' : 'replacement';
// 1. Let enc be a new TextEncoder object.
var enc = this;
// 2. Set enc's encoding to UTF-8's encoder.
if (Boolean(options['NONSTANDARD_allowLegacyEncoding'])) {
// NONSTANDARD behavior.
label = label !== undefined ? String(label) : DEFAULT_ENCODING;
var encoding = getEncoding(label);
if (encoding === null || encoding.name === 'replacement')
throw RangeError('Unknown encoding: ' + label);
if (!encoders[encoding.name]) {
throw Error('Encoder not present.' +
' Did you forget to include encoding-indexes.js first?');
}
enc._encoding = encoding;
} else {
// Standard behavior.
enc._encoding = getEncoding('utf-8');
if (label !== undefined && 'console' in global) {
console.warn('TextEncoder constructor called with encoding label, '
+ 'which is ignored.');
}
}
// For pre-ES5 runtimes:
if (!Object.defineProperty)
this.encoding = enc._encoding.name.toLowerCase();
// 3. Return enc.
return enc;
} | @constructor
@param {string=} label The label of the encoding. NONSTANDARD.
@param {Object=} options NONSTANDARD. | TextEncoder ( label , options ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
TextEncoder.prototype.encode = function encode(opt_string, options) {
opt_string = opt_string === undefined ? '' : String(opt_string);
options = ToDictionary(options);
// NOTE: This option is nonstandard. None of the encodings
// permitted for encoding (i.e. UTF-8, UTF-16) are stateful when
// the input is a USVString so streaming is not necessary.
if (!this._do_not_flush)
this._encoder = encoders[this._encoding.name]({
fatal: this._fatal === 'fatal'});
this._do_not_flush = Boolean(options['stream']);
// 1. Convert input to a stream.
var input = new Stream(stringToCodePoints(opt_string));
// 2. Let output be a new stream
var output = [];
/** @type {?(number|!Array.<number>)} */
var result;
// 3. While true, run these substeps:
while (true) {
// 1. Let token be the result of reading from input.
var token = input.read();
if (token === end_of_stream)
break;
// 2. Let result be the result of processing token for encoder,
// input, output.
result = this._encoder.handler(input, token);
if (result === finished)
break;
if (Array.isArray(result))
output.push.apply(output, /**@type {!Array.<number>}*/(result));
else
output.push(result);
}
// TODO: Align with spec algorithm.
if (!this._do_not_flush) {
while (true) {
result = this._encoder.handler(input, input.read());
if (result === finished)
break;
if (Array.isArray(result))
output.push.apply(output, /**@type {!Array.<number>}*/(result));
else
output.push(result);
}
this._encoder = null;
}
// 3. If result is finished, convert output into a byte sequence,
// and then return a Uint8Array object wrapping an ArrayBuffer
// containing output.
return new Uint8Array(output);
}; | @param {string=} opt_string The string to encode.
@param {Object=} options
@return {!Uint8Array} Encoded bytes, as a Uint8Array. | encode ( opt_string , options ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
this.handler = function(stream, bite) {
// 1. If byte is end-of-stream and utf-8 bytes needed is not 0,
// set utf-8 bytes needed to 0 and return error.
if (bite === end_of_stream && utf8_bytes_needed !== 0) {
utf8_bytes_needed = 0;
return decoderError(fatal);
}
// 2. If byte is end-of-stream, return finished.
if (bite === end_of_stream)
return finished;
// 3. If utf-8 bytes needed is 0, based on byte:
if (utf8_bytes_needed === 0) {
// 0x00 to 0x7F
if (inRange(bite, 0x00, 0x7F)) {
// Return a code point whose value is byte.
return bite;
}
// 0xC2 to 0xDF
else if (inRange(bite, 0xC2, 0xDF)) {
// 1. Set utf-8 bytes needed to 1.
utf8_bytes_needed = 1;
// 2. Set UTF-8 code point to byte & 0x1F.
utf8_code_point = bite & 0x1F;
}
// 0xE0 to 0xEF
else if (inRange(bite, 0xE0, 0xEF)) {
// 1. If byte is 0xE0, set utf-8 lower boundary to 0xA0.
if (bite === 0xE0)
utf8_lower_boundary = 0xA0;
// 2. If byte is 0xED, set utf-8 upper boundary to 0x9F.
if (bite === 0xED)
utf8_upper_boundary = 0x9F;
// 3. Set utf-8 bytes needed to 2.
utf8_bytes_needed = 2;
// 4. Set UTF-8 code point to byte & 0xF.
utf8_code_point = bite & 0xF;
}
// 0xF0 to 0xF4
else if (inRange(bite, 0xF0, 0xF4)) {
// 1. If byte is 0xF0, set utf-8 lower boundary to 0x90.
if (bite === 0xF0)
utf8_lower_boundary = 0x90;
// 2. If byte is 0xF4, set utf-8 upper boundary to 0x8F.
if (bite === 0xF4)
utf8_upper_boundary = 0x8F;
// 3. Set utf-8 bytes needed to 3.
utf8_bytes_needed = 3;
// 4. Set UTF-8 code point to byte & 0x7.
utf8_code_point = bite & 0x7;
}
// Otherwise
else {
// Return error.
return decoderError(fatal);
}
// Return continue.
return null;
}
// 4. If byte is not in the range utf-8 lower boundary to utf-8
// upper boundary, inclusive, run these substeps:
if (!inRange(bite, utf8_lower_boundary, utf8_upper_boundary)) {
// 1. Set utf-8 code point, utf-8 bytes needed, and utf-8
// bytes seen to 0, set utf-8 lower boundary to 0x80, and set
// utf-8 upper boundary to 0xBF.
utf8_code_point = utf8_bytes_needed = utf8_bytes_seen = 0;
utf8_lower_boundary = 0x80;
utf8_upper_boundary = 0xBF;
// 2. Prepend byte to stream.
stream.prepend(bite);
// 3. Return error.
return decoderError(fatal);
}
// 5. Set utf-8 lower boundary to 0x80 and utf-8 upper boundary
// to 0xBF.
utf8_lower_boundary = 0x80;
utf8_upper_boundary = 0xBF;
// 6. Set UTF-8 code point to (UTF-8 code point << 6) | (byte &
// 0x3F)
utf8_code_point = (utf8_code_point << 6) | (bite & 0x3F);
// 7. Increase utf-8 bytes seen by one.
utf8_bytes_seen += 1;
// 8. If utf-8 bytes seen is not equal to utf-8 bytes needed,
// continue.
if (utf8_bytes_seen !== utf8_bytes_needed)
return null;
// 9. Let code point be utf-8 code point.
var code_point = utf8_code_point;
// 10. Set utf-8 code point, utf-8 bytes needed, and utf-8 bytes
// seen to 0.
utf8_code_point = utf8_bytes_needed = utf8_bytes_seen = 0;
// 11. Return a code point whose value is code point.
return code_point;
}; | @param {Stream} stream The stream of bytes being decoded.
@param {number} bite The next byte read from the stream.
@return {?(number|!Array.<number>)} The next code point(s)
decoded, or null if not enough data exists in the input
stream to decode a complete code point. | this.handler ( stream , bite ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function UTF8Decoder(options) {
var fatal = options.fatal;
// utf-8's decoder's has an associated utf-8 code point, utf-8
// bytes seen, and utf-8 bytes needed (all initially 0), a utf-8
// lower boundary (initially 0x80), and a utf-8 upper boundary
// (initially 0xBF).
var /** @type {number} */ utf8_code_point = 0,
/** @type {number} */ utf8_bytes_seen = 0,
/** @type {number} */ utf8_bytes_needed = 0,
/** @type {number} */ utf8_lower_boundary = 0x80,
/** @type {number} */ utf8_upper_boundary = 0xBF;
/**
* @param {Stream} stream The stream of bytes being decoded.
* @param {number} bite The next byte read from the stream.
* @return {?(number|!Array.<number>)} The next code point(s)
* decoded, or null if not enough data exists in the input
* stream to decode a complete code point.
*/
this.handler = function(stream, bite) {
// 1. If byte is end-of-stream and utf-8 bytes needed is not 0,
// set utf-8 bytes needed to 0 and return error.
if (bite === end_of_stream && utf8_bytes_needed !== 0) {
utf8_bytes_needed = 0;
return decoderError(fatal);
}
// 2. If byte is end-of-stream, return finished.
if (bite === end_of_stream)
return finished;
// 3. If utf-8 bytes needed is 0, based on byte:
if (utf8_bytes_needed === 0) {
// 0x00 to 0x7F
if (inRange(bite, 0x00, 0x7F)) {
// Return a code point whose value is byte.
return bite;
}
// 0xC2 to 0xDF
else if (inRange(bite, 0xC2, 0xDF)) {
// 1. Set utf-8 bytes needed to 1.
utf8_bytes_needed = 1;
// 2. Set UTF-8 code point to byte & 0x1F.
utf8_code_point = bite & 0x1F;
}
// 0xE0 to 0xEF
else if (inRange(bite, 0xE0, 0xEF)) {
// 1. If byte is 0xE0, set utf-8 lower boundary to 0xA0.
if (bite === 0xE0)
utf8_lower_boundary = 0xA0;
// 2. If byte is 0xED, set utf-8 upper boundary to 0x9F.
if (bite === 0xED)
utf8_upper_boundary = 0x9F;
// 3. Set utf-8 bytes needed to 2.
utf8_bytes_needed = 2;
// 4. Set UTF-8 code point to byte & 0xF.
utf8_code_point = bite & 0xF;
}
// 0xF0 to 0xF4
else if (inRange(bite, 0xF0, 0xF4)) {
// 1. If byte is 0xF0, set utf-8 lower boundary to 0x90.
if (bite === 0xF0)
utf8_lower_boundary = 0x90;
// 2. If byte is 0xF4, set utf-8 upper boundary to 0x8F.
if (bite === 0xF4)
utf8_upper_boundary = 0x8F;
// 3. Set utf-8 bytes needed to 3.
utf8_bytes_needed = 3;
// 4. Set UTF-8 code point to byte & 0x7.
utf8_code_point = bite & 0x7;
}
// Otherwise
else {
// Return error.
return decoderError(fatal);
}
// Return continue.
return null;
}
// 4. If byte is not in the range utf-8 lower boundary to utf-8
// upper boundary, inclusive, run these substeps:
if (!inRange(bite, utf8_lower_boundary, utf8_upper_boundary)) {
// 1. Set utf-8 code point, utf-8 bytes needed, and utf-8
// bytes seen to 0, set utf-8 lower boundary to 0x80, and set
// utf-8 upper boundary to 0xBF.
utf8_code_point = utf8_bytes_needed = utf8_bytes_seen = 0;
utf8_lower_boundary = 0x80;
utf8_upper_boundary = 0xBF;
// 2. Prepend byte to stream.
stream.prepend(bite);
// 3. Return error.
return decoderError(fatal);
}
// 5. Set utf-8 lower boundary to 0x80 and utf-8 upper boundary
// to 0xBF.
utf8_lower_boundary = 0x80;
utf8_upper_boundary = 0xBF;
// 6. Set UTF-8 code point to (UTF-8 code point << 6) | (byte &
// 0x3F)
utf8_code_point = (utf8_code_point << 6) | (bite & 0x3F);
// 7. Increase utf-8 bytes seen by one.
utf8_bytes_seen += 1;
// 8. If utf-8 bytes seen is not equal to utf-8 bytes needed,
// continue.
if (utf8_bytes_seen !== utf8_bytes_needed)
return null;
// 9. Let code point be utf-8 code point.
var code_point = utf8_code_point;
// 10. Set utf-8 code point, utf-8 bytes needed, and utf-8 bytes
// seen to 0.
utf8_code_point = utf8_bytes_needed = utf8_bytes_seen = 0;
// 11. Return a code point whose value is code point.
return code_point;
};
} | @constructor
@implements {Decoder}
@param {{fatal: boolean}} options | UTF8Decoder ( options ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
this.handler = function(stream, code_point) {
// 1. If code point is end-of-stream, return finished.
if (code_point === end_of_stream)
return finished;
// 2. If code point is an ASCII code point, return a byte whose
// value is code point.
if (isASCIICodePoint(code_point))
return code_point;
// 3. Set count and offset based on the range code point is in:
var count, offset;
// U+0080 to U+07FF, inclusive:
if (inRange(code_point, 0x0080, 0x07FF)) {
// 1 and 0xC0
count = 1;
offset = 0xC0;
}
// U+0800 to U+FFFF, inclusive:
else if (inRange(code_point, 0x0800, 0xFFFF)) {
// 2 and 0xE0
count = 2;
offset = 0xE0;
}
// U+10000 to U+10FFFF, inclusive:
else if (inRange(code_point, 0x10000, 0x10FFFF)) {
// 3 and 0xF0
count = 3;
offset = 0xF0;
}
// 4. Let bytes be a byte sequence whose first byte is (code
// point >> (6 × count)) + offset.
var bytes = [(code_point >> (6 * count)) + offset];
// 5. Run these substeps while count is greater than 0:
while (count > 0) {
// 1. Set temp to code point >> (6 × (count − 1)).
var temp = code_point >> (6 * (count - 1));
// 2. Append to bytes 0x80 | (temp & 0x3F).
bytes.push(0x80 | (temp & 0x3F));
// 3. Decrease count by one.
count -= 1;
}
// 6. Return bytes bytes, in order.
return bytes;
}; | @param {Stream} stream Input stream.
@param {number} code_point Next code point read from the stream.
@return {(number|!Array.<number>)} Byte(s) to emit. | this.handler ( stream , code_point ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function UTF8Encoder(options) {
options.fatal;
/**
* @param {Stream} stream Input stream.
* @param {number} code_point Next code point read from the stream.
* @return {(number|!Array.<number>)} Byte(s) to emit.
*/
this.handler = function(stream, code_point) {
// 1. If code point is end-of-stream, return finished.
if (code_point === end_of_stream)
return finished;
// 2. If code point is an ASCII code point, return a byte whose
// value is code point.
if (isASCIICodePoint(code_point))
return code_point;
// 3. Set count and offset based on the range code point is in:
var count, offset;
// U+0080 to U+07FF, inclusive:
if (inRange(code_point, 0x0080, 0x07FF)) {
// 1 and 0xC0
count = 1;
offset = 0xC0;
}
// U+0800 to U+FFFF, inclusive:
else if (inRange(code_point, 0x0800, 0xFFFF)) {
// 2 and 0xE0
count = 2;
offset = 0xE0;
}
// U+10000 to U+10FFFF, inclusive:
else if (inRange(code_point, 0x10000, 0x10FFFF)) {
// 3 and 0xF0
count = 3;
offset = 0xF0;
}
// 4. Let bytes be a byte sequence whose first byte is (code
// point >> (6 × count)) + offset.
var bytes = [(code_point >> (6 * count)) + offset];
// 5. Run these substeps while count is greater than 0:
while (count > 0) {
// 1. Set temp to code point >> (6 × (count − 1)).
var temp = code_point >> (6 * (count - 1));
// 2. Append to bytes 0x80 | (temp & 0x3F).
bytes.push(0x80 | (temp & 0x3F));
// 3. Decrease count by one.
count -= 1;
}
// 6. Return bytes bytes, in order.
return bytes;
};
} | @constructor
@implements {Encoder}
@param {{fatal: boolean}} options | UTF8Encoder ( options ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function SingleByteDecoder(index, options) {
var fatal = options.fatal;
/**
* @param {Stream} stream The stream of bytes being decoded.
* @param {number} bite The next byte read from the stream.
* @return {?(number|!Array.<number>)} The next code point(s)
* decoded, or null if not enough data exists in the input
* stream to decode a complete code point.
*/
this.handler = function(stream, bite) {
// 1. If byte is end-of-stream, return finished.
if (bite === end_of_stream)
return finished;
// 2. If byte is an ASCII byte, return a code point whose value
// is byte.
if (isASCIIByte(bite))
return bite;
// 3. Let code point be the index code point for byte − 0x80 in
// index single-byte.
var code_point = index[bite - 0x80];
// 4. If code point is null, return error.
if (code_point === null)
return decoderError(fatal);
// 5. Return a code point whose value is code point.
return code_point;
};
} | @constructor
@implements {Decoder}
@param {!Array.<number>} index The encoding index.
@param {{fatal: boolean}} options | SingleByteDecoder ( index , options ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function SingleByteEncoder(index, options) {
options.fatal;
/**
* @param {Stream} stream Input stream.
* @param {number} code_point Next code point read from the stream.
* @return {(number|!Array.<number>)} Byte(s) to emit.
*/
this.handler = function(stream, code_point) {
// 1. If code point is end-of-stream, return finished.
if (code_point === end_of_stream)
return finished;
// 2. If code point is an ASCII code point, return a byte whose
// value is code point.
if (isASCIICodePoint(code_point))
return code_point;
// 3. Let pointer be the index pointer for code point in index
// single-byte.
var pointer = indexPointerFor(code_point, index);
// 4. If pointer is null, return error with code point.
if (pointer === null)
encoderError(code_point);
// 5. Return a byte whose value is pointer + 0x80.
return pointer + 0x80;
};
} | @constructor
@implements {Encoder}
@param {!Array.<?number>} index The encoding index.
@param {{fatal: boolean}} options | SingleByteEncoder ( index , options ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function GB18030Encoder(options, gbk_flag) {
options.fatal;
// gb18030's decoder has an associated gbk flag (initially unset).
/**
* @param {Stream} stream Input stream.
* @param {number} code_point Next code point read from the stream.
* @return {(number|!Array.<number>)} Byte(s) to emit.
*/
this.handler = function(stream, code_point) {
// 1. If code point is end-of-stream, return finished.
if (code_point === end_of_stream)
return finished;
// 2. If code point is an ASCII code point, return a byte whose
// value is code point.
if (isASCIICodePoint(code_point))
return code_point;
// 3. If code point is U+E5E5, return error with code point.
if (code_point === 0xE5E5)
return encoderError(code_point);
// 4. If the gbk flag is set and code point is U+20AC, return
// byte 0x80.
if (gbk_flag && code_point === 0x20AC)
return 0x80;
// 5. Let pointer be the index pointer for code point in index
// gb18030.
var pointer = indexPointerFor(code_point, index('gb18030'));
// 6. If pointer is not null, run these substeps:
if (pointer !== null) {
// 1. Let lead be floor(pointer / 190) + 0x81.
var lead = floor(pointer / 190) + 0x81;
// 2. Let trail be pointer % 190.
var trail = pointer % 190;
// 3. Let offset be 0x40 if trail is less than 0x3F and 0x41 otherwise.
var offset = trail < 0x3F ? 0x40 : 0x41;
// 4. Return two bytes whose values are lead and trail + offset.
return [lead, trail + offset];
}
// 7. If gbk flag is set, return error with code point.
if (gbk_flag)
return encoderError(code_point);
// 8. Set pointer to the index gb18030 ranges pointer for code
// point.
pointer = indexGB18030RangesPointerFor(code_point);
// 9. Let byte1 be floor(pointer / 10 / 126 / 10).
var byte1 = floor(pointer / 10 / 126 / 10);
// 10. Set pointer to pointer − byte1 × 10 × 126 × 10.
pointer = pointer - byte1 * 10 * 126 * 10;
// 11. Let byte2 be floor(pointer / 10 / 126).
var byte2 = floor(pointer / 10 / 126);
// 12. Set pointer to pointer − byte2 × 10 × 126.
pointer = pointer - byte2 * 10 * 126;
// 13. Let byte3 be floor(pointer / 10).
var byte3 = floor(pointer / 10);
// 14. Let byte4 be pointer − byte3 × 10.
var byte4 = pointer - byte3 * 10;
// 15. Return four bytes whose values are byte1 + 0x81, byte2 +
// 0x30, byte3 + 0x81, byte4 + 0x30.
return [byte1 + 0x81,
byte2 + 0x30,
byte3 + 0x81,
byte4 + 0x30];
};
} | @constructor
@implements {Encoder}
@param {{fatal: boolean}} options
@param {boolean=} gbk_flag | GB18030Encoder ( options , gbk_flag ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function convertCodeUnitToBytes(code_unit, utf16be) {
// 1. Let byte1 be code unit >> 8.
var byte1 = code_unit >> 8;
// 2. Let byte2 be code unit & 0x00FF.
var byte2 = code_unit & 0x00FF;
// 3. Then return the bytes in order:
// utf-16be flag is set: byte1, then byte2.
if (utf16be)
return [byte1, byte2];
// utf-16be flag is unset: byte2, then byte1.
return [byte2, byte1];
} | @param {number} code_unit
@param {boolean} utf16be
@return {!Array.<number>} bytes | convertCodeUnitToBytes ( code_unit , utf16be ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function UTF16Decoder(utf16_be, options) {
var fatal = options.fatal;
var /** @type {?number} */ utf16_lead_byte = null,
/** @type {?number} */ utf16_lead_surrogate = null;
/**
* @param {Stream} stream The stream of bytes being decoded.
* @param {number} bite The next byte read from the stream.
* @return {?(number|!Array.<number>)} The next code point(s)
* decoded, or null if not enough data exists in the input
* stream to decode a complete code point.
*/
this.handler = function(stream, bite) {
// 1. If byte is end-of-stream and either utf-16 lead byte or
// utf-16 lead surrogate is not null, set utf-16 lead byte and
// utf-16 lead surrogate to null, and return error.
if (bite === end_of_stream && (utf16_lead_byte !== null ||
utf16_lead_surrogate !== null)) {
return decoderError(fatal);
}
// 2. If byte is end-of-stream and utf-16 lead byte and utf-16
// lead surrogate are null, return finished.
if (bite === end_of_stream && utf16_lead_byte === null &&
utf16_lead_surrogate === null) {
return finished;
}
// 3. If utf-16 lead byte is null, set utf-16 lead byte to byte
// and return continue.
if (utf16_lead_byte === null) {
utf16_lead_byte = bite;
return null;
}
// 4. Let code unit be the result of:
var code_unit;
if (utf16_be) {
// utf-16be decoder flag is set
// (utf-16 lead byte << 8) + byte.
code_unit = (utf16_lead_byte << 8) + bite;
} else {
// utf-16be decoder flag is unset
// (byte << 8) + utf-16 lead byte.
code_unit = (bite << 8) + utf16_lead_byte;
}
// Then set utf-16 lead byte to null.
utf16_lead_byte = null;
// 5. If utf-16 lead surrogate is not null, let lead surrogate
// be utf-16 lead surrogate, set utf-16 lead surrogate to null,
// and then run these substeps:
if (utf16_lead_surrogate !== null) {
var lead_surrogate = utf16_lead_surrogate;
utf16_lead_surrogate = null;
// 1. If code unit is in the range U+DC00 to U+DFFF,
// inclusive, return a code point whose value is 0x10000 +
// ((lead surrogate − 0xD800) << 10) + (code unit − 0xDC00).
if (inRange(code_unit, 0xDC00, 0xDFFF)) {
return 0x10000 + (lead_surrogate - 0xD800) * 0x400 +
(code_unit - 0xDC00);
}
// 2. Prepend the sequence resulting of converting code unit
// to bytes using utf-16be decoder flag to stream and return
// error.
stream.prepend(convertCodeUnitToBytes(code_unit, utf16_be));
return decoderError(fatal);
}
// 6. If code unit is in the range U+D800 to U+DBFF, inclusive,
// set utf-16 lead surrogate to code unit and return continue.
if (inRange(code_unit, 0xD800, 0xDBFF)) {
utf16_lead_surrogate = code_unit;
return null;
}
// 7. If code unit is in the range U+DC00 to U+DFFF, inclusive,
// return error.
if (inRange(code_unit, 0xDC00, 0xDFFF))
return decoderError(fatal);
// 8. Return code point code unit.
return code_unit;
};
} | @constructor
@implements {Decoder}
@param {boolean} utf16_be True if big-endian, false if little-endian.
@param {{fatal: boolean}} options | UTF16Decoder ( utf16_be , options ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function UTF16Encoder(utf16_be, options) {
options.fatal;
/**
* @param {Stream} stream Input stream.
* @param {number} code_point Next code point read from the stream.
* @return {(number|!Array.<number>)} Byte(s) to emit.
*/
this.handler = function(stream, code_point) {
// 1. If code point is end-of-stream, return finished.
if (code_point === end_of_stream)
return finished;
// 2. If code point is in the range U+0000 to U+FFFF, inclusive,
// return the sequence resulting of converting code point to
// bytes using utf-16be encoder flag.
if (inRange(code_point, 0x0000, 0xFFFF))
return convertCodeUnitToBytes(code_point, utf16_be);
// 3. Let lead be ((code point − 0x10000) >> 10) + 0xD800,
// converted to bytes using utf-16be encoder flag.
var lead = convertCodeUnitToBytes(
((code_point - 0x10000) >> 10) + 0xD800, utf16_be);
// 4. Let trail be ((code point − 0x10000) & 0x3FF) + 0xDC00,
// converted to bytes using utf-16be encoder flag.
var trail = convertCodeUnitToBytes(
((code_point - 0x10000) & 0x3FF) + 0xDC00, utf16_be);
// 5. Return a byte sequence of lead followed by trail.
return lead.concat(trail);
};
} | @constructor
@implements {Encoder}
@param {boolean} utf16_be True if big-endian, false if little-endian.
@param {{fatal: boolean}} options | UTF16Encoder ( utf16_be , options ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function typeofJsonValue(value) {
let t = typeof value;
if (t == "object") {
if (Array.isArray(value))
return "array";
if (value === null)
return "null";
}
return t;
} | Get the type of a JSON value.
Distinguishes between array, null and object. | typeofJsonValue ( value ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function isJsonObject(value) {
return value !== null && typeof value == "object" && !Array.isArray(value);
} | Is this a JSON object (instead of an array or null)? | isJsonObject ( value ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function base64decode(base64Str) {
// estimate byte size, not accounting for inner padding and whitespace
let es = base64Str.length * 3 / 4;
// if (es % 3 !== 0)
// throw new Error('invalid base64 string');
if (base64Str[base64Str.length - 2] == '=')
es -= 2;
else if (base64Str[base64Str.length - 1] == '=')
es -= 1;
let bytes = new Uint8Array(es), bytePos = 0, // position in byte array
groupPos = 0, // position in base64 group
b, // current byte
p = 0 // previous byte
;
for (let i = 0; i < base64Str.length; i++) {
b = decTable[base64Str.charCodeAt(i)];
if (b === undefined) {
// noinspection FallThroughInSwitchStatementJS
switch (base64Str[i]) {
case '=':
groupPos = 0; // reset state when padding found
case '\n':
case '\r':
case '\t':
case ' ':
continue; // skip white-space, and padding
default:
throw Error(`invalid base64 string.`);
}
}
switch (groupPos) {
case 0:
p = b;
groupPos = 1;
break;
case 1:
bytes[bytePos++] = p << 2 | (b & 48) >> 4;
p = b;
groupPos = 2;
break;
case 2:
bytes[bytePos++] = (p & 15) << 4 | (b & 60) >> 2;
p = b;
groupPos = 3;
break;
case 3:
bytes[bytePos++] = (p & 3) << 6 | b;
groupPos = 0;
break;
}
}
if (groupPos == 1)
throw Error(`invalid base64 string.`);
return bytes.subarray(0, bytePos);
} | Decodes a base64 string to a byte array.
- ignores white-space, including line breaks and tabs
- allows inner padding (can decode concatenated base64 strings)
- does not require padding
- understands base64url encoding:
"-" instead of "+",
"_" instead of "/",
no padding | base64decode ( base64Str ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function base64encode(bytes) {
let base64 = '', groupPos = 0, // position in base64 group
b, // current byte
p = 0; // carry over from previous byte
for (let i = 0; i < bytes.length; i++) {
b = bytes[i];
switch (groupPos) {
case 0:
base64 += encTable[b >> 2];
p = (b & 3) << 4;
groupPos = 1;
break;
case 1:
base64 += encTable[p | b >> 4];
p = (b & 15) << 2;
groupPos = 2;
break;
case 2:
base64 += encTable[p | b >> 6];
base64 += encTable[b & 63];
groupPos = 0;
break;
}
}
// padding required?
if (groupPos) {
base64 += encTable[p];
base64 += '=';
if (groupPos == 1)
base64 += '=';
}
return base64;
} | Encodes a byte array to a base64 string.
Adds padding at the end.
Does not insert newlines. | base64encode ( bytes ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
UnknownFieldHandler.onRead = (typeName, message, fieldNo, wireType, data) => {
let container = is(message) ? message[UnknownFieldHandler.symbol] : message[UnknownFieldHandler.symbol] = [];
container.push({ no: fieldNo, wireType, data });
}; | Store an unknown field during binary read directly on the message.
This method is compatible with `BinaryReadOptions.readUnknownField`. | UnknownFieldHandler.onRead | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
UnknownFieldHandler.onWrite = (typeName, message, writer) => {
for (let { no, wireType, data } of UnknownFieldHandler.list(message))
writer.tag(no, wireType).raw(data);
}; | Write unknown fields stored for the message to the writer.
This method is compatible with `BinaryWriteOptions.writeUnknownFields`. | UnknownFieldHandler.onWrite | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
UnknownFieldHandler.list = (message, fieldNo) => {
if (is(message)) {
let all = message[UnknownFieldHandler.symbol];
return fieldNo ? all.filter(uf => uf.no == fieldNo) : all;
}
return [];
}; | List unknown fields stored for the message.
Note that there may be multiples fields with the same number. | UnknownFieldHandler.list | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
UnknownFieldHandler.last = (message, fieldNo) => UnknownFieldHandler.list(message, fieldNo).slice(-1)[0]; | Returns the last unknown field by field number. | UnknownFieldHandler.last | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function varint64read() {
let lowBits = 0;
let highBits = 0;
for (let shift = 0; shift < 28; shift += 7) {
let b = this.buf[this.pos++];
lowBits |= (b & 0x7F) << shift;
if ((b & 0x80) == 0) {
this.assertBounds();
return [lowBits, highBits];
}
}
let middleByte = this.buf[this.pos++];
// last four bits of the first 32 bit number
lowBits |= (middleByte & 0x0F) << 28;
// 3 upper bits are part of the next 32 bit number
highBits = (middleByte & 0x70) >> 4;
if ((middleByte & 0x80) == 0) {
this.assertBounds();
return [lowBits, highBits];
}
for (let shift = 3; shift <= 31; shift += 7) {
let b = this.buf[this.pos++];
highBits |= (b & 0x7F) << shift;
if ((b & 0x80) == 0) {
this.assertBounds();
return [lowBits, highBits];
}
}
throw new Error('invalid varint');
} | Read a 64 bit varint as two JS numbers.
Returns tuple:
[0]: low bits
[0]: high bits
Copyright 2008 Google Inc. All rights reserved.
See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L175 | varint64read ( ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function int64fromString(dec) {
// Check for minus sign.
let minus = dec[0] == '-';
if (minus)
dec = dec.slice(1);
// Work 6 decimal digits at a time, acting like we're converting base 1e6
// digits to binary. This is safe to do with floating point math because
// Number.isSafeInteger(ALL_32_BITS * 1e6) == true.
const base = 1e6;
let lowBits = 0;
let highBits = 0;
function add1e6digit(begin, end) {
// Note: Number('') is 0.
const digit1e6 = Number(dec.slice(begin, end));
highBits *= base;
lowBits = lowBits * base + digit1e6;
// Carry bits from lowBits to highBits
if (lowBits >= TWO_PWR_32_DBL$1) {
highBits = highBits + ((lowBits / TWO_PWR_32_DBL$1) | 0);
lowBits = lowBits % TWO_PWR_32_DBL$1;
}
}
add1e6digit(-24, -18);
add1e6digit(-18, -12);
add1e6digit(-12, -6);
add1e6digit(-6);
return [minus, lowBits, highBits];
} | Parse decimal string of 64 bit integer value as two JS numbers.
Returns tuple:
[0]: minus sign?
[1]: low bits
[2]: high bits
Copyright 2008 Google Inc. | int64fromString ( dec ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function int64toString(bitsLow, bitsHigh) {
// Skip the expensive conversion if the number is small enough to use the
// built-in conversions.
if ((bitsHigh >>> 0) <= 0x1FFFFF) {
return '' + (TWO_PWR_32_DBL$1 * bitsHigh + (bitsLow >>> 0));
}
// What this code is doing is essentially converting the input number from
// base-2 to base-1e7, which allows us to represent the 64-bit range with
// only 3 (very large) digits. Those digits are then trivial to convert to
// a base-10 string.
// The magic numbers used here are -
// 2^24 = 16777216 = (1,6777216) in base-1e7.
// 2^48 = 281474976710656 = (2,8147497,6710656) in base-1e7.
// Split 32:32 representation into 16:24:24 representation so our
// intermediate digits don't overflow.
let low = bitsLow & 0xFFFFFF;
let mid = (((bitsLow >>> 24) | (bitsHigh << 8)) >>> 0) & 0xFFFFFF;
let high = (bitsHigh >> 16) & 0xFFFF;
// Assemble our three base-1e7 digits, ignoring carries. The maximum
// value in a digit at this step is representable as a 48-bit integer, which
// can be stored in a 64-bit floating point number.
let digitA = low + (mid * 6777216) + (high * 6710656);
let digitB = mid + (high * 8147497);
let digitC = (high * 2);
// Apply carries from A to B and from B to C.
let base = 10000000;
if (digitA >= base) {
digitB += Math.floor(digitA / base);
digitA %= base;
}
if (digitB >= base) {
digitC += Math.floor(digitB / base);
digitB %= base;
}
// Convert base-1e7 digits to base-10, with optional leading zeroes.
function decimalFrom1e7(digit1e7, needLeadingZeros) {
let partial = digit1e7 ? String(digit1e7) : '';
if (needLeadingZeros) {
return '0000000'.slice(partial.length) + partial;
}
return partial;
}
return decimalFrom1e7(digitC, /*needLeadingZeros=*/ 0) +
decimalFrom1e7(digitB, /*needLeadingZeros=*/ digitC) +
// If the final 1e7 digit didn't need leading zeros, we would have
// returned via the trivial code path at the top.
decimalFrom1e7(digitA, /*needLeadingZeros=*/ 1);
} | Format 64 bit integer value (as two JS numbers) to decimal string.
Copyright 2008 Google Inc. | int64toString ( bitsLow , bitsHigh ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function varint32write(value, bytes) {
if (value >= 0) {
// write value as varint 32
while (value > 0x7f) {
bytes.push((value & 0x7f) | 0x80);
value = value >>> 7;
}
bytes.push(value);
}
else {
for (let i = 0; i < 9; i++) {
bytes.push(value & 127 | 128);
value = value >> 7;
}
bytes.push(1);
}
} | Write a 32 bit varint, signed or unsigned. Same as `varint64write(0, value, bytes)`
Copyright 2008 Google Inc. All rights reserved.
See https://github.com/protocolbuffers/protobuf/blob/1b18833f4f2a2f681f4e4a25cdf3b0a43115ec26/js/binary/encoder.js#L144 | varint32write ( value , bytes ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function varint32read() {
let b = this.buf[this.pos++];
let result = b & 0x7F;
if ((b & 0x80) == 0) {
this.assertBounds();
return result;
}
b = this.buf[this.pos++];
result |= (b & 0x7F) << 7;
if ((b & 0x80) == 0) {
this.assertBounds();
return result;
}
b = this.buf[this.pos++];
result |= (b & 0x7F) << 14;
if ((b & 0x80) == 0) {
this.assertBounds();
return result;
}
b = this.buf[this.pos++];
result |= (b & 0x7F) << 21;
if ((b & 0x80) == 0) {
this.assertBounds();
return result;
}
// Extract only last 4 bits
b = this.buf[this.pos++];
result |= (b & 0x0F) << 28;
for (let readBytes = 5; ((b & 0x80) !== 0) && readBytes < 10; readBytes++)
b = this.buf[this.pos++];
if ((b & 0x80) != 0)
throw new Error('invalid varint');
this.assertBounds();
// Result can have 32 bits, convert it to unsigned
return result >>> 0;
} | Read an unsigned 32 bit varint.
See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L220 | varint32read ( ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
constructor(lo, hi) {
this.lo = lo | 0;
this.hi = hi | 0;
} | Create a new instance with the given bits. | constructor ( lo , hi ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
static from(value) {
if (BI)
// noinspection FallThroughInSwitchStatementJS
switch (typeof value) {
case "string":
if (value == "0")
return this.ZERO;
if (value == "")
throw new Error('string is no integer');
value = BI.C(value);
case "number":
if (value === 0)
return this.ZERO;
value = BI.C(value);
case "bigint":
if (!value)
return this.ZERO;
if (value < BI.UMIN)
throw new Error('signed value for ulong');
if (value > BI.UMAX)
throw new Error('ulong too large');
BI.V.setBigUint64(0, value, true);
return new PbULong(BI.V.getInt32(0, true), BI.V.getInt32(4, true));
}
else
switch (typeof value) {
case "string":
if (value == "0")
return this.ZERO;
value = value.trim();
if (!RE_DECIMAL_STR.test(value))
throw new Error('string is no integer');
let [minus, lo, hi] = int64fromString(value);
if (minus)
throw new Error('signed value for ulong');
return new PbULong(lo, hi);
case "number":
if (value == 0)
return this.ZERO;
if (!Number.isSafeInteger(value))
throw new Error('number is no integer');
if (value < 0)
throw new Error('signed value for ulong');
return new PbULong(value, value / TWO_PWR_32_DBL);
}
throw new Error('unknown value ' + typeof value);
} | Create instance from a `string`, `number` or `bigint`. | from ( value ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
negate() {
let hi = ~this.hi, lo = this.lo;
if (lo)
lo = ~lo + 1;
else
hi += 1;
return new PbLong(lo, hi);
} | Negate two's complement.
Invert all the bits and add one to the result. | negate ( ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function binaryReadOptions(options) {
return options ? Object.assign(Object.assign({}, defaultsRead$1), options) : defaultsRead$1;
} | Make options for reading binary data form partial options. | binaryReadOptions ( options ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
tag() {
let tag = this.uint32(), fieldNo = tag >>> 3, wireType = tag & 7;
if (fieldNo <= 0 || wireType < 0 || wireType > 5)
throw new Error("illegal tag: field no " + fieldNo + " wire type " + wireType);
return [fieldNo, wireType];
} | Reads a tag - field number and wire type. | tag ( ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
skip(wireType) {
let start = this.pos;
// noinspection FallThroughInSwitchStatementJS
switch (wireType) {
case WireType.Varint:
while (this.buf[this.pos++] & 0x80) {
// ignore
}
break;
case WireType.Bit64:
this.pos += 4;
case WireType.Bit32:
this.pos += 4;
break;
case WireType.LengthDelimited:
let len = this.uint32();
this.pos += len;
break;
case WireType.StartGroup:
// From descriptor.proto: Group type is deprecated, not supported in proto3.
// But we must still be able to parse and treat as unknown.
let t;
while ((t = this.tag()[1]) !== WireType.EndGroup) {
this.skip(t);
}
break;
default:
throw new Error("cant skip wire type " + wireType);
}
this.assertBounds();
return this.buf.subarray(start, this.pos);
} | Skip one element on the wire and return the skipped data.
Supports WireType.StartGroup since v2.0.0-alpha.23. | skip ( wireType ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
assertBounds() {
if (this.pos > this.len)
throw new RangeError("premature EOF");
} | Throws error if position in byte array is out of range. | assertBounds ( ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
int32() {
return this.uint32() | 0;
} | Read a `int32` field, a signed 32 bit varint. | int32 ( ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
sint32() {
let zze = this.uint32();
// decode zigzag
return (zze >>> 1) ^ -(zze & 1);
} | Read a `sint32` field, a signed, zigzag-encoded 32-bit varint. | sint32 ( ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
int64() {
return new PbLong(...this.varint64());
} | Read a `int64` field, a signed 64-bit varint. | int64 ( ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
uint64() {
return new PbULong(...this.varint64());
} | Read a `uint64` field, an unsigned 64-bit varint. | uint64 ( ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
sint64() {
let [lo, hi] = this.varint64();
// decode zig zag
let s = -(lo & 1);
lo = ((lo >>> 1 | (hi & 1) << 31) ^ s);
hi = (hi >>> 1 ^ s);
return new PbLong(lo, hi);
} | Read a `sint64` field, a signed, zig-zag-encoded 64-bit varint. | sint64 ( ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
fixed32() {
return this.view.getUint32((this.pos += 4) - 4, true);
} | Read a `fixed32` field, an unsigned, fixed-length 32-bit integer. | fixed32 ( ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
sfixed32() {
return this.view.getInt32((this.pos += 4) - 4, true);
} | Read a `sfixed32` field, a signed, fixed-length 32-bit integer. | sfixed32 ( ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
fixed64() {
return new PbULong(this.sfixed32(), this.sfixed32());
} | Read a `fixed64` field, an unsigned, fixed-length 64 bit integer. | fixed64 ( ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
sfixed64() {
return new PbLong(this.sfixed32(), this.sfixed32());
} | Read a `fixed64` field, a signed, fixed-length 64-bit integer. | sfixed64 ( ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
float() {
return this.view.getFloat32((this.pos += 4) - 4, true);
} | Read a `float` field, 32-bit floating point number. | float ( ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
double() {
return this.view.getFloat64((this.pos += 8) - 8, true);
} | Read a `double` field, a 64-bit floating point number. | double ( ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
bytes() {
let len = this.uint32();
let start = this.pos;
this.pos += len;
this.assertBounds();
return this.buf.subarray(start, start + len);
} | Read a `bytes` field, length-delimited arbitrary data. | bytes ( ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
string() {
return this.textDecoder.decode(this.bytes());
} | Read a `string` field, length-delimited data converted to UTF-8 text. | string ( ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function assert(condition, msg) {
if (!condition) {
throw new Error(msg);
}
} | assert that condition is true or throw error (with message) | assert ( condition , msg ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function binaryWriteOptions(options) {
return options ? Object.assign(Object.assign({}, defaultsWrite$1), options) : defaultsWrite$1;
} | Make options for writing binary data form partial options. | binaryWriteOptions ( options ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
finish() {
this.chunks.push(new Uint8Array(this.buf)); // flush the buffer
let len = 0;
for (let i = 0; i < this.chunks.length; i++)
len += this.chunks[i].length;
let bytes = new Uint8Array(len);
let offset = 0;
for (let i = 0; i < this.chunks.length; i++) {
bytes.set(this.chunks[i], offset);
offset += this.chunks[i].length;
}
this.chunks = [];
return bytes;
} | Return all bytes written and reset this writer. | finish ( ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
fork() {
this.stack.push({ chunks: this.chunks, buf: this.buf });
this.chunks = [];
this.buf = [];
return this;
} | Start a new fork for length-delimited data like a message
or a packed repeated field.
Must be joined later with `join()`. | fork ( ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.