[Pkg-javascript-commits] [node-text-encoding] 01/04: Imported Upstream version 0.5.4
Julien Puydt
julien.puydt at laposte.net
Sat Jan 2 10:03:34 UTC 2016
This is an automated email from the git hooks/post-receive script.
jpuydt-guest pushed a commit to branch master
in repository node-text-encoding.
commit 48921c78ee64175de02f89659865eed76030e446
Author: Julien Puydt <julien.puydt at laposte.net>
Date: Sat Jan 2 10:47:17 2016 +0100
Imported Upstream version 0.5.4
---
.gitmodules | 3 +
LICENSE.md | 231 +----
README.md | 13 +-
bower.json | 4 +-
index.js | 15 +-
lib/encoding-indexes.js | 16 -
lib/encoding.js | 847 ++++++++++-------
package.json | 5 +-
test/test-big5.js | 15 +-
test/test-euc-jp.js | 15 +-
test/test-euc-kr.js | 15 +-
test/test-gbk.js | 15 +-
test/test-iso-2022-jp.js | 15 +-
test/test-misc.js | 25 +-
test/test-shift_jis.js | 15 +-
test/test-utf.js | 18 +-
test/test-x-user-defined.js | 18 +-
test/testharness.css | 92 --
test/testharness.js | 2121 -------------------------------------------
test/testharnessreport.js | 380 --------
test/tests.html | 17 +-
21 files changed, 597 insertions(+), 3298 deletions(-)
diff --git a/.gitmodules b/.gitmodules
new file mode 100644
index 0000000..32d1ae5
--- /dev/null
+++ b/.gitmodules
@@ -0,0 +1,3 @@
+[submodule "test/testharness.js"]
+ path = test/testharness.js
+ url = https://github.com/w3c/testharness.js.git
diff --git a/LICENSE.md b/LICENSE.md
index 6d00d2e..5e15316 100644
--- a/LICENSE.md
+++ b/LICENSE.md
@@ -1,202 +1,29 @@
-
- Apache License
- Version 2.0, January 2011
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "[]"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
- Copyright [yyyy] [name of copyright owner]
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
+The encoding indexes, algorithms, and many comments in the code
+derive from the Encoding Standard https://encoding.spec.whatwg.org/
+
+Otherwise...
+
+This is free and unencumbered software released into the public domain.
+
+Anyone is free to copy, modify, publish, use, compile, sell, or
+distribute this software, either in source code form or as a compiled
+binary, for any purpose, commercial or non-commercial, and by any
+means.
+
+In jurisdictions that recognize copyright laws, the author or authors
+of this software dedicate any and all copyright interest in the
+software to the public domain. We make this dedication for the benefit
+of the public at large and to the detriment of our heirs and
+successors. We intend this dedication to be an overt act of
+relinquishment in perpetuity of all present and future rights to this
+software under copyright law.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
+OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
+
+For more information, please refer to <http://unlicense.org/>
diff --git a/README.md b/README.md
index f3e1cc2..9e5acf2 100644
--- a/README.md
+++ b/README.md
@@ -91,13 +91,16 @@ var uint8array = new TextEncoder(
But note that the above won't work if you're using the polyfill in a browser that
natively supports the TextEncoder API natively, since the polyfill won't be used!
-You'd need to fork and modify the polyfill to... not be a polyfill.
+
+You can force the polyfill to be used by using this before the polyfill:
+
+```html
+<script>
+window.TextEncoder = window.TextDecoder = null;
+</script>
+```
To support the legacy encodings (which may be stateful), the TextEncoder `encode()`
method accepts an optional dictionary and `stream` option,
e.g. `encoder.encode(string, {stream: true});` This is not needed for the
stateless UTF encodings since the input is always in complete code points.
-
-The polyfill also allows construction of encoder/decoder objects without the
-`new` keyword. (This non-standard behavior is supported for constructing DOM
-objects in Firefox but not other browsers.)
diff --git a/bower.json b/bower.json
index 63dd654..f595b2a 100644
--- a/bower.json
+++ b/bower.json
@@ -1,6 +1,6 @@
{
"name": "text-encoding",
- "version": "0.5.3",
+ "version": "0.5.4",
"homepage": "https://github.com/inexorabletash/text-encoding",
"authors": [
"Joshua Bell <inexorabletash at gmail.com>"
@@ -13,7 +13,7 @@
"living",
"standards"
],
- "license": "Apache-2.0",
+ "license": "Unlicense",
"ignore": [
"**/.*",
"test",
diff --git a/index.js b/index.js
index 819b19d..cc57d65 100644
--- a/index.js
+++ b/index.js
@@ -1,16 +1,5 @@
-// Copyright 2014 Joshua Bell. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
+// This is free and unencumbered software released into the public domain.
+// See LICENSE.md for more information.
var encoding = require("./lib/encoding.js");
diff --git a/lib/encoding-indexes.js b/lib/encoding-indexes.js
index 122de54..ac4fb8e 100644
--- a/lib/encoding-indexes.js
+++ b/lib/encoding-indexes.js
@@ -1,19 +1,3 @@
-// Copyright 2014 Joshua Bell. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// Indexes from: https://encoding.spec.whatwg.org/indexes.json
-
(function(global) {
'use strict';
global["encoding-indexes"] = {
diff --git a/lib/encoding.js b/lib/encoding.js
index bbdd071..95e7404 100644
--- a/lib/encoding.js
+++ b/lib/encoding.js
@@ -1,16 +1,5 @@
-// Copyright 2014 Joshua Bell. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
+// This is free and unencumbered software released into the public domain.
+// See LICENSE.md for more information.
// If we're in node require encoding-indexes and attach it to the global.
/**
@@ -40,15 +29,26 @@ if (typeof module !== "undefined" && module.exports) {
}
/**
- * @param {number} n The numerator.
- * @param {number} d The denominator.
- * @return {number} The result of the integer division of n by d.
+ * @param {*} item The item to look for in the list.
+ * @param {!Array.<*>} list The list to check.
+ * @return {boolean} True if the item appears in the list.
*/
- function div(n, d) {
- return Math.floor(n / d);
+ function isOneOf(item, list) {
+ return list.indexOf(item) !== -1;
}
/**
+ * @param {*} item The item to look for in the list.
+ * @param {!Array.<*>} list The list to check.
+ * @return {boolean} True if the item does not appear in the list.
+ */
+ function isNoneOf(item, list) {
+ return list.indexOf(item) === -1;
+ }
+
+ var floor = Math.floor;
+
+ /**
* @param {*} o
* @return {Object}
*/
@@ -167,10 +167,26 @@ if (typeof module !== "undefined" && module.exports) {
//
//
- // 3. Terminology
+ // 4. Terminology
//
/**
+ * 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.
+ */
+ function isASCIIByte(a) {
+ return 0x00 <= a && a <= 0x7F;
+ }
+
+ /**
+ * An ASCII code point is a code point in the range U+0000 to
+ * U+007F, inclusive.
+ */
+ var isASCIICodePoint = isASCIIByte;
+
+
+ /**
* End-of-stream is a special token that signifies no more tokens
* are in the stream.
* @const
@@ -180,12 +196,14 @@ if (typeof module !== "undefined" && module.exports) {
* A stream represents an ordered sequence of tokens.
*
* @constructor
- * @param {!(Array.<number>|Uint8Array)} tokens Array of tokens that provide the
- * stream.
+ * @param {!(Array.<number>|Uint8Array)} tokens Array of tokens that provide
+ * the stream.
*/
function Stream(tokens) {
/** @type {!Array.<number>} */
this.tokens = [].slice.call(tokens);
+ // Reversed as push/pop is more efficient than shift/unshift.
+ this.tokens.reverse();
}
Stream.prototype = {
@@ -207,7 +225,7 @@ if (typeof module !== "undefined" && module.exports) {
read: function() {
if (!this.tokens.length)
return end_of_stream;
- return this.tokens.shift();
+ return this.tokens.pop();
},
/**
@@ -215,15 +233,16 @@ if (typeof module !== "undefined" && module.exports) {
* 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.
+ * @param {(number|!Array.<number>)} token The token(s) to prepend to the
+ * stream.
*/
prepend: function(token) {
if (Array.isArray(token)) {
var tokens = /**@type {!Array.<number>}*/(token);
while (tokens.length)
- this.tokens.unshift(tokens.pop());
+ this.tokens.push(tokens.pop());
} else {
- this.tokens.unshift(token);
+ this.tokens.push(token);
}
},
@@ -232,28 +251,35 @@ if (typeof module !== "undefined" && module.exports) {
* must be inserted, in given order, after the last token in the
* stream.
*
- * @param {(number|!Array.<number>)} token The tokens(s) to prepend to the stream.
+ * @param {(number|!Array.<number>)} token The tokens(s) to push to the
+ * stream.
*/
push: function(token) {
if (Array.isArray(token)) {
var tokens = /**@type {!Array.<number>}*/(token);
while (tokens.length)
- this.tokens.push(tokens.shift());
+ this.tokens.unshift(tokens.shift());
} else {
- this.tokens.push(token);
+ this.tokens.unshift(token);
}
}
};
//
- // 4. Encodings
+ // 5. Encodings
//
- // 4.1 Encoders and decoders
+ // 5.1 Encoders and decoders
/** @const */
var finished = -1;
+ /** @const */
+ var error_mode_replacement = false;
+
+ /** @const */
+ var error_mode_fatal = true;
+
/**
* @param {boolean} fatal If true, decoding errors raise an exception.
* @param {number=} opt_code_point Override the standard fallback code point.
@@ -297,7 +323,7 @@ if (typeof module !== "undefined" && module.exports) {
handler: function(stream, code_point) {}
};
- // 4.2 Names and labels
+ // 5.2 Names and labels
// TODO: Define @typedef for Encoding: {name:string,labels:Array.<string>}
// https://github.com/google/closure-compiler/issues/247
@@ -801,7 +827,7 @@ if (typeof module !== "undefined" && module.exports) {
var decoders = {};
//
- // 5. Indexes
+ // 6. Indexes
//
/**
@@ -902,7 +928,8 @@ if (typeof module !== "undefined" && module.exports) {
}
/**
- * @param {number} code_point The |code_point| to search for in the shift_jis index.
+ * @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.
*/
@@ -918,7 +945,8 @@ if (typeof module !== "undefined" && module.exports) {
}
/**
- * @param {number} code_point The |code_point| to search for in the big5 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.
*/
@@ -933,7 +961,7 @@ if (typeof module !== "undefined" && module.exports) {
if (code_point === 0x2550 || code_point === 0x255E ||
code_point === 0x2561 || code_point === 0x256A ||
code_point === 0x5341 || code_point === 0x5345) {
- return index.lastIndexOf(code_point);
+ return index_.lastIndexOf(code_point);
}
// 3. Return the index pointer for code point in index.
@@ -941,240 +969,368 @@ if (typeof module !== "undefined" && module.exports) {
}
//
- // 7. API
+ // 8. API
//
/** @const */ var DEFAULT_ENCODING = 'utf-8';
- // 7.1 Interface TextDecoder
+ // 8.1 Interface TextDecoder
/**
* @constructor
- * @param {string=} encoding The label of the encoding;
+ * @param {string=} label The label of the encoding;
* defaults to 'utf-8'.
* @param {Object=} options
*/
- function TextDecoder(encoding, options) {
- if (!(this instanceof TextDecoder)) {
- return new TextDecoder(encoding, options);
- }
- encoding = encoding !== undefined ? String(encoding) : DEFAULT_ENCODING;
+ 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);
- /** @private */
- this._encoding = getEncoding(encoding);
- if (this._encoding === null || this._encoding.name === 'replacement')
- throw RangeError('Unknown encoding: ' + encoding);
- if (!decoders[this._encoding.name]) {
- throw Error('Decoder not present.' +
- ' Did you forget to include encoding-indexes.js?');
- }
+ // 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._streaming = false;
+ this._ignoreBOM = false;
/** @private @type {boolean} */
this._BOMseen = false;
- /** @private @type {?Decoder} */
- this._decoder = null;
/** @private @type {boolean} */
- this._fatal = Boolean(options['fatal']);
+ this._error_mode = error_mode_replacement;
/** @private @type {boolean} */
- this._ignoreBOM = Boolean(options['ignoreBOM']);
+ this._do_not_flush = false;
- if (Object.defineProperty) {
- Object.defineProperty(this, 'encoding', {value: this._encoding.name});
- Object.defineProperty(this, 'fatal', {value: this._fatal});
- Object.defineProperty(this, 'ignoreBOM', {value: this._ignoreBOM});
- } else {
- this.encoding = this._encoding.name;
- this.fatal = this._fatal;
- this.ignoreBOM = this._ignoreBOM;
+
+ // 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?');
+ }
+
+ // 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 = 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;
+ this.fatal = dec._error_mode;
+ this.ignoreBOM = dec._ignoreBOM;
}
- return this;
+ // 7. Return dec.
+ return dec;
}
- TextDecoder.prototype = {
- /**
- * @param {ArrayBufferView=} input The buffer of bytes to decode.
- * @param {Object=} options
- * @return {string} The decoded string.
- */
- 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);
- }
+ if (Object.defineProperty) {
+ // The encoding attribute's getter must return encoding's name.
+ Object.defineProperty(TextDecoder.prototype, 'encoding', {
+ /** @this {TextDecoder} */
+ get: function() { return this._encoding.name; }
+ });
- options = ToDictionary(options);
+ // The fatal attribute's getter must return true if error mode
+ // is fatal, and false otherwise.
+ Object.defineProperty(TextDecoder.prototype, 'fatal', {
+ /** @this {TextDecoder} */
+ get: function() { return this._error_mode === error_mode_fatal; }
+ });
- if (!this._streaming) {
- this._decoder = decoders[this._encoding.name]({fatal: this._fatal});
- this._BOMseen = false;
- }
- this._streaming = Boolean(options['stream']);
+ // The ignoreBOM attribute's getter must return true if ignore
+ // BOM flag is set, and false otherwise.
+ Object.defineProperty(TextDecoder.prototype, 'ignoreBOM', {
+ /** @this {TextDecoder} */
+ get: function() { return this._ignoreBOM; }
+ });
+ }
+
+ /**
+ * @param {BufferSource=} input The buffer of bytes to decode.
+ * @param {Object=} options
+ * @return {string} The decoded string.
+ */
+ 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});
+ 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;
- var input_stream = new Stream(bytes);
+ // 3. Otherwise, run these subsubsteps:
- var code_points = [];
+ // 1. Let result be the result of processing token for decoder,
+ // stream, output, and error mode.
+ result = this._decoder.handler(input_stream, token);
- /** @type {?(number|!Array.<number>)} */
- var result;
+ // 2. If result is finished, return output, serialized.
+ if (result === finished)
+ break;
- while (!input_stream.endOfStream()) {
+ 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))
- code_points.push.apply(code_points, /**@type {!Array.<number>}*/(result));
+ output.push.apply(output, /**@type {!Array.<number>}*/(result));
else
- code_points.push(result);
- }
- if (!this._streaming) {
- do {
- result = this._decoder.handler(input_stream, input_stream.read());
- if (result === finished)
- break;
- if (result === null)
- continue;
- if (Array.isArray(result))
- code_points.push.apply(code_points, /**@type {!Array.<number>}*/(result));
- else
- code_points.push(result);
- } while (!input_stream.endOfStream());
- this._decoder = null;
- }
+ output.push(result);
+ } while (!input_stream.endOfStream());
+ this._decoder = null;
+ }
- if (code_points.length) {
- // If encoding is one of utf-8, utf-16be, and utf-16le, and
- // ignore BOM flag and BOM seen flag are unset, run these
- // subsubsteps:
- if (['utf-8', 'utf-16le', 'utf-16be'].indexOf(this.encoding) !== -1 &&
- !this._ignoreBOM && !this._BOMseen) {
- // If token is U+FEFF, set BOM seen flag.
- if (code_points[0] === 0xFEFF) {
- this._BOMseen = true;
- code_points.shift();
- } else {
- // Otherwise, if token is not end-of-stream, set BOM seen
- // flag and append token to output.
- this._BOMseen = true;
- }
+ // 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 one of utf-8, utf-16be, and utf-16le, and
+ // ignore BOM flag and BOM seen flag are unset, run these
+ // subsubsteps:
+ if (isOneOf(this.encoding, ['utf-8', 'utf-16le', 'utf-16be']) &&
+ !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 {
+ // 3. Otherwise, if token is not end-of-stream, append token
+ // to output.
+ // (no-op)
}
}
-
- return codePointsToString(code_points);
+ // 4. Otherwise, return output.
+ return codePointsToString(stream);
}
+
+ return serializeStream.call(this, output);
};
- // 7.2 Interface TextEncoder
+ // 8.2 Interface TextEncoder
/**
* @constructor
- * @param {string=} encoding The label of the encoding;
+ * @param {string=} label The label of the encoding;
* defaults to 'utf-8'.
* @param {Object=} options
*/
- function TextEncoder(encoding, options) {
+ function TextEncoder(label, options) {
+ // Web IDL conventions
if (!(this instanceof TextEncoder))
- return new TextEncoder(encoding, options);
- encoding = encoding !== undefined ? String(encoding) : DEFAULT_ENCODING;
+ throw TypeError('Called as a function. Did you forget \'new\'?');
+ label = label !== undefined ? String(label) : DEFAULT_ENCODING;
options = ToDictionary(options);
+
+ // A TextEncoder object has an associated encoding and encoder.
+
/** @private */
- this._encoding = getEncoding(encoding);
- if (this._encoding === null || this._encoding.name === 'replacement')
- throw RangeError('Unknown encoding: ' + encoding);
-
- var allowLegacyEncoding =
- Boolean(options['NONSTANDARD_allowLegacyEncoding']);
- var isLegacyEncoding = (this._encoding.name !== 'utf-8' &&
- this._encoding.name !== 'utf-16le' &&
- this._encoding.name !== 'utf-16be');
- if (this._encoding === null || (isLegacyEncoding && !allowLegacyEncoding))
- throw RangeError('Unknown encoding: ' + encoding);
-
- if (!encoders[this._encoding.name]) {
+ this._encoding = null;
+ /** @private @type {?Encoder} */
+ this._encoder = null;
+
+ // Non-standard
+ /** @private @type {boolean} */
+ this._do_not_flush = false;
+ /** @private @type {boolean} */
+ this._fatal = Boolean(options['fatal']);
+
+ // 1. Let encoding be the result of getting an encoding from utfLabel.
+ var encoding = getEncoding(label);
+
+ // 2. If encoding is failure, or is none of utf-8, utf-16be, and
+ // utf-16le, throw a RangeError.
+ if (encoding === null || encoding.name === 'replacement' ||
+ (isNoneOf(encoding.name, ['utf-8','utf-16le', 'utf-16be']) &&
+ !Boolean(options['NONSTANDARD_allowLegacyEncoding'])))
+ throw RangeError('Unknown encoding: ' + label);
+ if (!encoders[encoding.name]) {
throw Error('Encoder not present.' +
' Did you forget to include encoding-indexes.js?');
}
- /** @private @type {boolean} */
- this._streaming = false;
- /** @private @type {?Encoder} */
- this._encoder = null;
- /** @private @type {{fatal: boolean}} */
- this._options = {fatal: Boolean(options['fatal'])};
+ // 3. Let enc be a new TextEncoder object.
+ var enc = this;
+
+ // 4. Set enc's encoding to encoding.
+ enc._encoding = encoding;
- if (Object.defineProperty)
- Object.defineProperty(this, 'encoding', {value: this._encoding.name});
- else
- this.encoding = this._encoding.name;
+ // 5. Set enc's encoder to a new enc's encoding's encoder.
+ // (Done during encode itself, due to nonstandard streaming support.)
- return this;
+ // For pre-ES5 runtimes:
+ if (!Object.defineProperty)
+ this.encoding = enc._encoding.name;
+
+ // 6. Return enc.
+ return enc;
}
- TextEncoder.prototype = {
- /**
- * @param {string=} opt_string The string to encode.
- * @param {Object=} options
- * @return {Uint8Array} Encoded bytes, as a Uint8Array.
- */
- encode: function encode(opt_string, options) {
- opt_string = opt_string ? 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,
- // so streaming is not necessary.
- if (!this._streaming)
- this._encoder = encoders[this._encoding.name](this._options);
- this._streaming = Boolean(options['stream']);
-
- var bytes = [];
- var input_stream = new Stream(stringToCodePoints(opt_string));
- /** @type {?(number|!Array.<number>)} */
- var result;
- while (!input_stream.endOfStream()) {
- result = this._encoder.handler(input_stream, input_stream.read());
+ if (Object.defineProperty) {
+ // The encoding attribute's getter must return encoding's name.
+ Object.defineProperty(TextEncoder.prototype, 'encoding', {
+ /** @this {TextEncoder} */
+ get: function() { return this._encoding.name; }
+ });
+ }
+
+ /**
+ * @param {string=} opt_string The string to encode.
+ * @param {Object=} options
+ * @return {Uint8Array} Encoded bytes, as a Uint8Array.
+ */
+ TextEncoder.prototype.encode = function encode(opt_string, options) {
+ opt_string = opt_string ? 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});
+ 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))
- bytes.push.apply(bytes, /**@type {!Array.<number>}*/(result));
+ output.push.apply(output, /**@type {!Array.<number>}*/(result));
else
- bytes.push(result);
- }
- if (!this._streaming) {
- while (true) {
- result = this._encoder.handler(input_stream, input_stream.read());
- if (result === finished)
- break;
- if (Array.isArray(result))
- bytes.push.apply(bytes, /**@type {!Array.<number>}*/(result));
- else
- bytes.push(result);
- }
- this._encoder = null;
+ output.push(result);
}
- return new Uint8Array(bytes);
+ 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);
};
//
- // 8. The encoding
+ // 9. The encoding
//
- // 8.1 utf-8
+ // 9.1 utf-8
+ // 9.1.1 utf-8 decoder
/**
* @constructor
* @implements {Decoder}
@@ -1263,15 +1419,15 @@ if (typeof module !== "undefined" && module.exports) {
return decoderError(fatal);
}
- // Then (byte is in the range 0xC2 to 0xF4) set utf-8 code
- // point to utf-8 code point << (6 × utf-8 bytes needed) and
- // return continue.
+ // Then (byte is in the range 0xC2 to 0xF4, inclusive) set
+ // utf-8 code point to utf-8 code point << (6 × utf-8 bytes
+ // needed) and return continue.
utf8_code_point = utf8_code_point << (6 * utf8_bytes_needed);
return null;
}
// 4. If byte is not in the range utf-8 lower boundary to utf-8
- // upper boundary, run these substeps:
+ // 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
@@ -1297,7 +1453,8 @@ if (typeof module !== "undefined" && module.exports) {
// to utf-8 code point + (byte − 0x80) << (6 × (utf-8 bytes
// needed − utf-8 bytes seen)).
utf8_bytes_seen += 1;
- utf8_code_point += (bite - 0x80) << (6 * (utf8_bytes_needed - utf8_bytes_seen));
+ utf8_code_point += (bite - 0x80) << (6 * (utf8_bytes_needed -
+ utf8_bytes_seen));
// 7. If utf-8 bytes seen is not equal to utf-8 bytes needed,
// continue.
@@ -1316,6 +1473,7 @@ if (typeof module !== "undefined" && module.exports) {
};
}
+ // 9.1.2 utf-8 encoder
/**
* @constructor
* @implements {Encoder}
@@ -1340,18 +1498,21 @@ if (typeof module !== "undefined" && module.exports) {
// 3. Set count and offset based on the range code point is in:
var count, offset;
- // U+0080 to U+07FF: 1 and 0xC0
+ // U+0080 to U+07FF, inclusive:
if (inRange(code_point, 0x0080, 0x07FF)) {
+ // 1 and 0xC0
count = 1;
offset = 0xC0;
}
- // U+0800 to U+FFFF: 2 and 0xE0
+ // 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: 3 and 0xF0
+ // U+10000 to U+10FFFF, inclusive:
else if (inRange(code_point, 0x10000, 0x10FFFF)) {
+ // 3 and 0xF0
count = 3;
offset = 0xF0;
}
@@ -1388,10 +1549,10 @@ if (typeof module !== "undefined" && module.exports) {
};
//
- // 9. Legacy single-byte encodings
+ // 10. Legacy single-byte encodings
//
- // 9.1 single-byte decoder
+ // 10.1 single-byte decoder
/**
* @constructor
* @implements {Decoder}
@@ -1412,9 +1573,9 @@ if (typeof module !== "undefined" && module.exports) {
if (bite === end_of_stream)
return finished;
- // 2. If byte is in the range 0x00 to 0x7F, return a code point
- // whose value is byte.
- if (inRange(bite, 0x00, 0x7F))
+ // 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
@@ -1430,7 +1591,7 @@ if (typeof module !== "undefined" && module.exports) {
};
}
- // 9.2 single-byte encoder
+ // 10.2 single-byte encoder
/**
* @constructor
* @implements {Encoder}
@@ -1449,9 +1610,9 @@ if (typeof module !== "undefined" && module.exports) {
if (code_point === end_of_stream)
return finished;
- // 2. If code point is in the range U+0000 to U+007F, return a
- // byte whose value is code point.
- if (inRange(code_point, 0x0000, 0x007F))
+ // 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
@@ -1489,28 +1650,28 @@ if (typeof module !== "undefined" && module.exports) {
}());
//
- // 10. Legacy multi-byte Chinese (simplified) encodings
+ // 11. Legacy multi-byte Chinese (simplified) encodings
//
- // 10.1 gbk
+ // 11.1 gbk
- // 10.1.1 gbk decoder
+ // 11.1.1 gbk decoder
// gbk's decoder is gb18030's decoder.
/** @param {{fatal: boolean}} options */
decoders['gbk'] = function(options) {
return new GB18030Decoder(options);
};
- // 10.1.2 gbk encoder
+ // 11.1.2 gbk encoder
// gbk's encoder is gb18030's encoder with its gbk flag set.
/** @param {{fatal: boolean}} options */
encoders['gbk'] = function(options) {
return new GB18030Encoder(options, true);
};
- // 10.2 gb18030
+ // 11.2 gb18030
- // 10.2.1 gb18030 decoder
+ // 11.2.1 gb18030 decoder
/**
* @constructor
* @implements {Decoder}
@@ -1541,7 +1702,8 @@ if (typeof module !== "undefined" && module.exports) {
// second, or gb18030 third is not 0x00, set gb18030 first,
// gb18030 second, and gb18030 third to 0x00, and return error.
if (bite === end_of_stream &&
- (gb18030_first !== 0x00 || gb18030_second !== 0x00 || gb18030_third !== 0x00)) {
+ (gb18030_first !== 0x00 || gb18030_second !== 0x00 ||
+ gb18030_third !== 0x00)) {
gb18030_first = 0x00;
gb18030_second = 0x00;
gb18030_third = 0x00;
@@ -1631,9 +1793,9 @@ if (typeof module !== "undefined" && module.exports) {
code_point = pointer === null ? null :
indexCodePointFor(pointer, index('gb18030'));
- // 6. If code point is null and byte is in the range 0x00 to
- // 0x7F, prepend byte to stream.
- if (code_point === null && inRange(bite, 0x00, 0x7F))
+ // 6. If code point is null and byte is an ASCII byte, prepend
+ // byte to stream.
+ if (code_point === null && isASCIIByte(bite))
stream.prepend(bite);
// 7. If code point is null, return error.
@@ -1644,9 +1806,9 @@ if (typeof module !== "undefined" && module.exports) {
return code_point;
}
- // 6. If byte is in the range 0x00 to 0x7F, return a code point
- // whose value is byte.
- if (inRange(bite, 0x00, 0x7F))
+ // 6. If byte is an ASCII byte, return a code point whose value
+ // is byte.
+ if (isASCIIByte(bite))
return bite;
// 7. If byte is 0x80, return code point U+20AC.
@@ -1665,7 +1827,7 @@ if (typeof module !== "undefined" && module.exports) {
};
}
- // 10.2.2 gb18030 encoder
+ // 11.2.2 gb18030 encoder
/**
* @constructor
* @implements {Encoder}
@@ -1685,11 +1847,10 @@ if (typeof module !== "undefined" && module.exports) {
if (code_point === end_of_stream)
return finished;
- // 2. If code point is in the range U+0000 to U+007F, return a
- // byte whose value is code point.
- if (inRange(code_point, 0x0000, 0x007F)) {
+ // 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 the gbk flag is set and code point is U+20AC, return
// byte 0x80.
@@ -1703,8 +1864,8 @@ if (typeof module !== "undefined" && module.exports) {
// 5. If pointer is not null, run these substeps:
if (pointer !== null) {
- // 1. Let lead be pointer / 190 + 0x81.
- var lead = div(pointer, 190) + 0x81;
+ // 1. Let lead be floor(pointer / 190) + 0x81.
+ var lead = floor(pointer / 190) + 0x81;
// 2. Let trail be pointer % 190.
var trail = pointer % 190;
@@ -1724,20 +1885,20 @@ if (typeof module !== "undefined" && module.exports) {
// point.
pointer = indexGB18030RangesPointerFor(code_point);
- // 8. Let byte1 be pointer / 10 / 126 / 10.
- var byte1 = div(div(div(pointer, 10), 126), 10);
+ // 8. Let byte1 be floor(pointer / 10 / 126 / 10).
+ var byte1 = floor(pointer / 10 / 126 / 10);
// 9. Set pointer to pointer − byte1 × 10 × 126 × 10.
pointer = pointer - byte1 * 10 * 126 * 10;
- // 10. Let byte2 be pointer / 10 / 126.
- var byte2 = div(div(pointer, 10), 126);
+ // 10. Let byte2 be floor(pointer / 10 / 126).
+ var byte2 = floor(pointer / 10 / 126);
// 11. Set pointer to pointer − byte2 × 10 × 126.
pointer = pointer - byte2 * 10 * 126;
- // 12. Let byte3 be pointer / 10.
- var byte3 = div(pointer, 10);
+ // 12. Let byte3 be floor(pointer / 10).
+ var byte3 = floor(pointer / 10);
// 13. Let byte4 be pointer − byte3 × 10.
var byte4 = pointer - byte3 * 10;
@@ -1762,11 +1923,12 @@ if (typeof module !== "undefined" && module.exports) {
//
- // 11. Legacy multi-byte Chinese (traditional) encodings
+ // 12. Legacy multi-byte Chinese (traditional) encodings
//
- // 11.1 big5
+ // 12.1 big5
+ // 12.1.1 big5 decoder
/**
* @constructor
* @implements {Decoder}
@@ -1835,9 +1997,9 @@ if (typeof module !== "undefined" && module.exports) {
var code_point = (pointer === null) ? null :
indexCodePointFor(pointer, index('big5'));
- // 5. If code point is null and byte is in the range 0x00 to
- // 0x7F, prepend byte to stream.
- if (code_point === null && inRange(bite, 0x00, 0x7F))
+ // 5. If code point is null and byte is an ASCII byte, prepend
+ // byte to stream.
+ if (code_point === null && isASCIIByte(bite))
stream.prepend(bite);
// 6. If code point is null, return error.
@@ -1848,9 +2010,9 @@ if (typeof module !== "undefined" && module.exports) {
return code_point;
}
- // 4. If byte is in the range 0x00 to 0x7F, return a code point
- // whose value is byte.
- if (inRange(bite, 0x00, 0x7F))
+ // 4. If byte is an ASCII byte, return a code point whose value
+ // is byte.
+ if (isASCIIByte(bite))
return bite;
// 5. If byte is in the range 0x81 to 0xFE, set big5 lead to
@@ -1865,6 +2027,7 @@ if (typeof module !== "undefined" && module.exports) {
};
}
+ // 12.1.2 big5 encoder
/**
* @constructor
* @implements {Encoder}
@@ -1882,20 +2045,20 @@ if (typeof module !== "undefined" && module.exports) {
if (code_point === end_of_stream)
return finished;
- // 2. If code point is in the range U+0000 to U+007F, return a
- // byte whose value is code point.
- if (inRange(code_point, 0x0000, 0x007F))
+ // 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 big5 pointer for code point.
- var pointer = indexBig5PointerFor(code_point, index('big5'));
+ var pointer = indexBig5PointerFor(code_point);
// 4. If pointer is null, return error with code point.
if (pointer === null)
return encoderError(code_point);
- // 5. Let lead be pointer / 157 + 0x81.
- var lead = div(pointer, 157) + 0x81;
+ // 5. Let lead be floor(pointer / 157) + 0x81.
+ var lead = floor(pointer / 157) + 0x81;
// 6. If lead is less than 0xA1, return error with code point.
if (lead < 0xA1)
@@ -1924,11 +2087,12 @@ if (typeof module !== "undefined" && module.exports) {
//
- // 12. Legacy multi-byte Japanese encodings
+ // 13. Legacy multi-byte Japanese encodings
//
- // 12.1 euc-jp
+ // 13.1 euc-jp
+ // 13.1.1 euc-jp decoder
/**
* @constructor
* @implements {Decoder}
@@ -2014,9 +2178,9 @@ if (typeof module !== "undefined" && module.exports) {
return code_point;
}
- // 6. If byte is in the range 0x00 to 0x7F, return a code point
- // whose value is byte.
- if (inRange(bite, 0x00, 0x7F))
+ // 6. If byte is an ASCII byte, return a code point whose value
+ // is byte.
+ if (isASCIIByte(bite))
return bite;
// 7. If byte is 0x8E, 0x8F, or in the range 0xA1 to 0xFE, set
@@ -2031,6 +2195,7 @@ if (typeof module !== "undefined" && module.exports) {
};
}
+ // 13.1.2 euc-jp encoder
/**
* @constructor
* @implements {Encoder}
@@ -2048,9 +2213,9 @@ if (typeof module !== "undefined" && module.exports) {
if (code_point === end_of_stream)
return finished;
- // 2. If code point is in the range U+0000 to U+007F, return a
- // byte whose value is code point.
- if (inRange(code_point, 0x0000, 0x007F))
+ // 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+00A5, return byte 0x5C.
@@ -2066,8 +2231,8 @@ if (typeof module !== "undefined" && module.exports) {
if (inRange(code_point, 0xFF61, 0xFF9F))
return [0x8E, code_point - 0xFF61 + 0xA1];
- // 6. If code point is U+2022, set it to U+FF0D.
- if (code_point === 0x2022)
+ // 6. If code point is U+2212, set it to U+FF0D.
+ if (code_point === 0x2212)
code_point = 0xFF0D;
// 7. Let pointer be the index pointer for code point in index
@@ -2078,8 +2243,8 @@ if (typeof module !== "undefined" && module.exports) {
if (pointer === null)
return encoderError(code_point);
- // 9. Let lead be pointer / 94 + 0xA1.
- var lead = div(pointer, 94) + 0xA1;
+ // 9. Let lead be floor(pointer / 94) + 0xA1.
+ var lead = floor(pointer / 94) + 0xA1;
// 10. Let trail be pointer % 94 + 0xA1.
var trail = pointer % 94 + 0xA1;
@@ -2098,8 +2263,9 @@ if (typeof module !== "undefined" && module.exports) {
return new EUCJPDecoder(options);
};
- // 12.2 iso-2022-jp
+ // 13.2 iso-2022-jp
+ // 13.2.1 iso-2022-jp decoder
/**
* @constructor
* @implements {Decoder}
@@ -2301,7 +2467,8 @@ if (typeof module !== "undefined" && module.exports) {
// 2. Let pointer be (iso-2022-jp lead − 0x21) × 94 + byte − 0x21.
var pointer = (iso2022jp_lead - 0x21) * 94 + bite - 0x21;
- // 3. Let code point be the index code point for pointer in index jis0208.
+ // 3. Let code point be the index code point for pointer in
+ // index jis0208.
var code_point = indexCodePointFor(pointer, index('jis0208'));
// 4. If code point is null, return error.
@@ -2407,6 +2574,7 @@ if (typeof module !== "undefined" && module.exports) {
};
}
+ // 13.2.2 iso-2022-jp encoder
/**
* @constructor
* @implements {Encoder}
@@ -2445,23 +2613,23 @@ if (typeof module !== "undefined" && module.exports) {
if (code_point === end_of_stream && iso2022jp_state === states.ASCII)
return finished;
- // 3. If iso-2022-jp encoder state is ASCII and code point is in
- // the range U+0000 to U+007F, return a byte whose value is code
- // point.
+ // 3. If iso-2022-jp encoder state is ASCII and code point is an
+ // ASCII code point, return a byte whose value is code point.
if (iso2022jp_state === states.ASCII &&
- inRange(code_point, 0x0000, 0x007F))
+ isASCIICodePoint(code_point))
return code_point;
- // 4. If iso-2022-jp encoder state is Roman and code point is in
- // the range U+0000 to U+007F, excluding U+005C and U+007E, or
- // is U+00A5 or U+203E, run these substeps:
+ // 4. If iso-2022-jp encoder state is Roman and code point is an
+ // ASCII code point, excluding U+005C and U+007E, or is U+00A5
+ // or U+203E, run these substeps:
if (iso2022jp_state === states.Roman &&
- inRange(code_point, 0x0000, 0x007F) &&
- code_point !== 0x005C && code_point !== 0x007E) {
+ (isASCIICodePoint(code_point) &&
+ code_point !== 0x005C && code_point !== 0x007E) ||
+ (code_point == 0x00A5 || code_point == 0x203E)) {
- // 1. If code point is in the range U+0000 to U+007F, return a
- // byte whose value is code point.
- if (inRange(code_point, 0x0000, 0x007F))
+ // 1. If code point is an ASCII code point, return a byte
+ // whose value is code point.
+ if (isASCIICodePoint(code_point))
return code_point;
// 2. If code point is U+00A5, return byte 0x5C.
@@ -2473,11 +2641,11 @@ if (typeof module !== "undefined" && module.exports) {
return 0x7E;
}
- // 5. If code point is in the range U+0000 to U+007F, and
- // iso-2022-jp encoder state is not ASCII, prepend code point to
- // stream, set iso-2022-jp encoder state to ASCII, and return
- // three bytes 0x1B 0x28 0x42.
- if (inRange(code_point, 0x0000, 0x007F) &&
+ // 5. If code point is an ASCII code point, and iso-2022-jp
+ // encoder state is not ASCII, prepend code point to stream, set
+ // iso-2022-jp encoder state to ASCII, and return three bytes
+ // 0x1B 0x28 0x42.
+ if (isASCIICodePoint(code_point) &&
iso2022jp_state !== states.ASCII) {
stream.prepend(code_point);
iso2022jp_state = states.ASCII;
@@ -2495,8 +2663,8 @@ if (typeof module !== "undefined" && module.exports) {
return [0x1B, 0x28, 0x4A];
}
- // 7. If code point is U+2022, set it to U+FF0D.
- if (code_point === 0x2022)
+ // 7. If code point is U+2212, set it to U+FF0D.
+ if (code_point === 0x2212)
code_point = 0xFF0D;
// 8. Let pointer be the index pointer for code point in index
@@ -2516,8 +2684,8 @@ if (typeof module !== "undefined" && module.exports) {
return [0x1B, 0x24, 0x42];
}
- // 11. Let lead be pointer / 94 + 0x21.
- var lead = div(pointer, 94) + 0x21;
+ // 11. Let lead be floor(pointer / 94) + 0x21.
+ var lead = floor(pointer / 94) + 0x21;
// 12. Let trail be pointer % 94 + 0x21.
var trail = pointer % 94 + 0x21;
@@ -2536,8 +2704,9 @@ if (typeof module !== "undefined" && module.exports) {
return new ISO2022JPDecoder(options);
};
- // 12.3 shift_jis
+ // 13.3 shift_jis
+ // 13.3.1 shift_jis decoder
/**
* @constructor
* @implements {Decoder}
@@ -2601,9 +2770,9 @@ if (typeof module !== "undefined" && module.exports) {
inRange(pointer, 8836, 10528))
return 0xE000 + pointer - 8836;
- // 6. If code point is null and byte is in the range 0x00 to
- // 0x7F, prepend byte to stream.
- if (code_point === null && inRange(bite, 0x00, 0x7F))
+ // 6. If code point is null and byte is an ASCII byte, prepend
+ // byte to stream.
+ if (code_point === null && isASCIIByte(bite))
stream.prepend(bite);
// 7. If code point is null, return error.
@@ -2614,9 +2783,9 @@ if (typeof module !== "undefined" && module.exports) {
return code_point;
}
- // 4. If byte is in the range 0x00 to 0x80, return a code point
+ // 4. If byte is an ASCII byte or 0x80, return a code point
// whose value is byte.
- if (inRange(bite, 0x00, 0x80))
+ if (isASCIIByte(bite) || bite === 0x80)
return bite;
// 5. If byte is in the range 0xA1 to 0xDF, return a code point
@@ -2636,6 +2805,7 @@ if (typeof module !== "undefined" && module.exports) {
};
}
+ // 13.3.2 shift_jis encoder
/**
* @constructor
* @implements {Encoder}
@@ -2653,9 +2823,9 @@ if (typeof module !== "undefined" && module.exports) {
if (code_point === end_of_stream)
return finished;
- // 2. If code point is in the range U+0000 to U+0080, return a
+ // 2. If code point is an ASCII code point or U+0080, return a
// byte whose value is code point.
- if (inRange(code_point, 0x0000, 0x0080))
+ if (isASCIICodePoint(code_point) || code_point === 0x0080)
return code_point;
// 3. If code point is U+00A5, return byte 0x5C.
@@ -2671,8 +2841,8 @@ if (typeof module !== "undefined" && module.exports) {
if (inRange(code_point, 0xFF61, 0xFF9F))
return code_point - 0xFF61 + 0xA1;
- // 6. If code point is U+2022, set it to U+FF0D.
- if (code_point === 0x2022)
+ // 6. If code point is U+2212, set it to U+FF0D.
+ if (code_point === 0x2212)
code_point = 0xFF0D;
// 7. Let pointer be the index shift_jis pointer for code point.
@@ -2682,8 +2852,8 @@ if (typeof module !== "undefined" && module.exports) {
if (pointer === null)
return encoderError(code_point);
- // 9. Let lead be pointer / 188.
- var lead = div(pointer, 188);
+ // 9. Let lead be floor(pointer / 188).
+ var lead = floor(pointer / 188);
// 10. Let lead offset be 0x81, if lead is less than 0x1F, and
// 0xC1 otherwise.
@@ -2712,11 +2882,12 @@ if (typeof module !== "undefined" && module.exports) {
};
//
- // 13. Legacy multi-byte Korean encodings
+ // 14. Legacy multi-byte Korean encodings
//
- // 13.1 euc-kr
+ // 14.1 euc-kr
+ // 14.1.1 euc-kr decoder
/**
* @constructor
* @implements {Decoder}
@@ -2762,11 +2933,12 @@ if (typeof module !== "undefined" && module.exports) {
// 2. Let code point be null, if pointer is null, and the
// index code point for pointer in index euc-kr otherwise.
- var code_point = (pointer === null) ? null : indexCodePointFor(pointer, index('euc-kr'));
+ var code_point = (pointer === null)
+ ? null : indexCodePointFor(pointer, index('euc-kr'));
- // 3. If code point is null and byte is in the range 0x00 to
- // 0x7F, prepend byte to stream.
- if (pointer === null && inRange(bite, 0x00, 0x7F))
+ // 3. If code point is null and byte is an ASCII byte, prepend
+ // byte to stream.
+ if (pointer === null && isASCIIByte(bite))
stream.prepend(bite);
// 4. If code point is null, return error.
@@ -2777,9 +2949,9 @@ if (typeof module !== "undefined" && module.exports) {
return code_point;
}
- // 4. If byte is in the range 0x00 to 0x7F, return a code point
- // whose value is byte.
- if (inRange(bite, 0x00, 0x7F))
+ // 4. If byte is an ASCII byte, return a code point whose value
+ // is byte.
+ if (isASCIIByte(bite))
return bite;
// 5. If byte is in the range 0x81 to 0xFE, set euc-kr lead to
@@ -2794,6 +2966,7 @@ if (typeof module !== "undefined" && module.exports) {
};
}
+ // 14.1.2 euc-kr encoder
/**
* @constructor
* @implements {Encoder}
@@ -2811,9 +2984,9 @@ if (typeof module !== "undefined" && module.exports) {
if (code_point === end_of_stream)
return finished;
- // 2. If code point is in the range U+0000 to U+007F, return a
- // byte whose value is code point.
- if (inRange(code_point, 0x0000, 0x007F))
+ // 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
@@ -2824,8 +2997,8 @@ if (typeof module !== "undefined" && module.exports) {
if (pointer === null)
return encoderError(code_point);
- // 5. Let lead be pointer / 190 + 0x81.
- var lead = div(pointer, 190) + 0x81;
+ // 5. Let lead be floor(pointer / 190) + 0x81.
+ var lead = floor(pointer / 190) + 0x81;
// 6. Let trail be pointer % 190 + 0x41.
var trail = (pointer % 190) + 0x41;
@@ -2846,14 +3019,14 @@ if (typeof module !== "undefined" && module.exports) {
//
- // 14. Legacy miscellaneous encodings
+ // 15. Legacy miscellaneous encodings
//
- // 14.1 replacement
+ // 15.1 replacement
// Not needed - API throws RangeError
- // 14.2 utf-16
+ // 15.2 Common infrastructure for utf-16be and utf-16le
/**
* @param {number} code_unit
@@ -2875,6 +3048,7 @@ if (typeof module !== "undefined" && module.exports) {
return [byte2, byte1];
}
+ // 15.2.1 shared utf-16 decoder
/**
* @constructor
* @implements {Decoder}
@@ -2968,6 +3142,7 @@ if (typeof module !== "undefined" && module.exports) {
};
}
+ // 15.2.2 shared utf-16 encoder
/**
* @constructor
* @implements {Encoder}
@@ -3007,28 +3182,33 @@ if (typeof module !== "undefined" && module.exports) {
};
}
- // 14.3 utf-16be
+ // 15.3 utf-16be
+ // 15.3.1 utf-16be decoder
/** @param {{fatal: boolean}} options */
encoders['utf-16be'] = function(options) {
return new UTF16Encoder(true, options);
};
+ // 15.3.2 utf-16be encoder
/** @param {{fatal: boolean}} options */
decoders['utf-16be'] = function(options) {
return new UTF16Decoder(true, options);
};
- // 14.4 utf-16le
+ // 15.4 utf-16le
+ // 15.4.1 utf-16le decoder
/** @param {{fatal: boolean}} options */
encoders['utf-16le'] = function(options) {
return new UTF16Encoder(false, options);
};
+ // 15.4.2 utf-16le encoder
/** @param {{fatal: boolean}} options */
decoders['utf-16le'] = function(options) {
return new UTF16Decoder(false, options);
};
- // 14.5 x-user-defined
+ // 15.5 x-user-defined
+ // 15.5.1 x-user-defined decoder
/**
* @constructor
* @implements {Decoder}
@@ -3048,9 +3228,9 @@ if (typeof module !== "undefined" && module.exports) {
if (bite === end_of_stream)
return finished;
- // 2. If byte is in the range 0x00 to 0x7F, return a code point
- // whose value is byte.
- if (inRange(bite, 0x00, 0x7F))
+ // 2. If byte is an ASCII byte, return a code point whose value
+ // is byte.
+ if (isASCIIByte(bite))
return bite;
// 3. Return a code point whose value is 0xF780 + byte − 0x80.
@@ -3058,6 +3238,7 @@ if (typeof module !== "undefined" && module.exports) {
};
}
+ // 15.5.2 x-user-defined encoder
/**
* @constructor
* @implements {Encoder}
@@ -3075,9 +3256,9 @@ if (typeof module !== "undefined" && module.exports) {
if (code_point === end_of_stream)
return finished;
- // 2. If code point is in the range U+0000 to U+007F, return a
- // byte whose value is code point.
- if (inRange(code_point, 0x0000, 0x007F))
+ // 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 in the range U+F780 to U+F7FF, return a
@@ -3099,8 +3280,16 @@ if (typeof module !== "undefined" && module.exports) {
return new XUserDefinedDecoder(options);
};
- if (!('TextEncoder' in global))
+ if (!global['TextEncoder'])
global['TextEncoder'] = TextEncoder;
- if (!('TextDecoder' in global))
+ if (!global['TextDecoder'])
global['TextDecoder'] = TextDecoder;
+
+ if (typeof module !== "undefined" && module.exports) {
+ module.exports = {
+ TextEncoder: global['TextEncoder'],
+ TextDecoder: global['TextDecoder'],
+ EncodingIndexes: global["encoding-indexes"]
+ };
+ }
}(this));
diff --git a/package.json b/package.json
index add3a6f..3bae282 100644
--- a/package.json
+++ b/package.json
@@ -4,7 +4,7 @@
"contributors": [
"Rick Eyre <rick.eyre at outlook.com>"
],
- "version": "0.5.3",
+ "version": "0.5.4",
"description": "Polyfill for the Encoding Living Standard's API.",
"main": "index.js",
"files": [
@@ -24,5 +24,6 @@
"bugs": {
"url": "https://github.com/inexorabletash/text-encoding/issues"
},
- "homepage": "https://github.com/inexorabletash/text-encoding"
+ "homepage": "https://github.com/inexorabletash/text-encoding",
+ "license": "Unlicense"
}
diff --git a/test/test-big5.js b/test/test-big5.js
index 8197c05..51d3c52 100644
--- a/test/test-big5.js
+++ b/test/test-big5.js
@@ -1,16 +1,5 @@
-// Copyright 2014 Joshua Bell. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
+// This is free and unencumbered software released into the public domain.
+// See LICENSE.md for more information.
test(
function () {
diff --git a/test/test-euc-jp.js b/test/test-euc-jp.js
index 3822a28..f88a8e9 100644
--- a/test/test-euc-jp.js
+++ b/test/test-euc-jp.js
@@ -1,16 +1,5 @@
-// Copyright 2014 Joshua Bell. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
+// This is free and unencumbered software released into the public domain.
+// See LICENSE.md for more information.
test(
function () {
diff --git a/test/test-euc-kr.js b/test/test-euc-kr.js
index 7751946..cfe8a68 100644
--- a/test/test-euc-kr.js
+++ b/test/test-euc-kr.js
@@ -1,16 +1,5 @@
-// Copyright 2014 Joshua Bell. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
+// This is free and unencumbered software released into the public domain.
+// See LICENSE.md for more information.
test(
function () {
diff --git a/test/test-gbk.js b/test/test-gbk.js
index 0b09214..44ae675 100644
--- a/test/test-gbk.js
+++ b/test/test-gbk.js
@@ -1,16 +1,5 @@
-// Copyright 2014 Joshua Bell. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
+// This is free and unencumbered software released into the public domain.
+// See LICENSE.md for more information.
test(
function () {
diff --git a/test/test-iso-2022-jp.js b/test/test-iso-2022-jp.js
index a84221c..ca8861d 100644
--- a/test/test-iso-2022-jp.js
+++ b/test/test-iso-2022-jp.js
@@ -1,16 +1,5 @@
-// Copyright 2014 Joshua Bell. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
+// This is free and unencumbered software released into the public domain.
+// See LICENSE.md for more information.
test(
function () {
diff --git a/test/test-misc.js b/test/test-misc.js
index d161be2..c5ababa 100644
--- a/test/test-misc.js
+++ b/test/test-misc.js
@@ -1,19 +1,5 @@
-// Copyright 2014 Joshua Bell. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// NOTE: Requires testharness.js
-// http://www.w3.org/2008/webapps/wiki/Harness
+// This is free and unencumbered software released into the public domain.
+// See LICENSE.md for more information.
var UTF_ENCODINGS = ['utf-8', 'utf-16le', 'utf-16be'];
@@ -319,3 +305,10 @@ test(function() {
function() { new TextEncoder(null); },
'Null should coerce to "null" and be invalid encoding name.');
}, 'Invalid parameters');
+
+test(function() {
+ assert_array_equals(
+ [249,249,249,233,249,235,249,234,164,81,164,202],
+ new TextEncoder('big5', {NONSTANDARD_allowLegacyEncoding: true})
+ .encode('\u2550\u255E\u2561\u256A\u5341\u5345'));
+}, 'NONSTANDARD - regression tests');
diff --git a/test/test-shift_jis.js b/test/test-shift_jis.js
index a01e49e..010bc64 100644
--- a/test/test-shift_jis.js
+++ b/test/test-shift_jis.js
@@ -1,16 +1,5 @@
-// Copyright 2014 Joshua Bell. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
+// This is free and unencumbered software released into the public domain.
+// See LICENSE.md for more information.
test(
function () {
diff --git a/test/test-utf.js b/test/test-utf.js
index 57b5c3f..786c945 100644
--- a/test/test-utf.js
+++ b/test/test-utf.js
@@ -1,19 +1,5 @@
-// Copyright 2014 Joshua Bell. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// NOTE: Requires testharness.js
-// http://www.w3.org/2008/webapps/wiki/Harness
+// This is free and unencumbered software released into the public domain.
+// See LICENSE.md for more information.
// Extension to testharness.js API which avoids logging enormous strings
// on a coding failure.
diff --git a/test/test-x-user-defined.js b/test/test-x-user-defined.js
index 108005c..401511a 100644
--- a/test/test-x-user-defined.js
+++ b/test/test-x-user-defined.js
@@ -1,19 +1,5 @@
-// Copyright 2014 Joshua Bell. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// NOTE: Requires testharness.js
-// http://www.w3.org/2008/webapps/wiki/Harness
+// This is free and unencumbered software released into the public domain.
+// See LICENSE.md for more information.
test(
function() {
diff --git a/test/testharness.css b/test/testharness.css
deleted file mode 100644
index 365084f..0000000
--- a/test/testharness.css
+++ /dev/null
@@ -1,92 +0,0 @@
-html {
- font-family:DejaVu Sans, Bitstream Vera Sans, Arial, Sans;
-}
-
-#log .warning,
-#log .warning a {
- color: black;
- background: yellow;
-}
-
-#log .error,
-#log .error a {
- color: white;
- background: red;
-}
-
-#log pre {
- border: 1px solid black;
- padding: 1em;
-}
-
-section#summary {
- margin-bottom:1em;
-}
-
-table#results {
- border-collapse:collapse;
- table-layout:fixed;
- width:100%;
-}
-
-table#results th:first-child,
-table#results td:first-child {
- width:4em;
-}
-
-table#results th:last-child,
-table#results td:last-child {
- width:50%;
-}
-
-table#results.assertions th:last-child,
-table#results.assertions td:last-child {
- width:35%;
-}
-
-table#results th {
- padding:0;
- padding-bottom:0.5em;
- border-bottom:medium solid black;
-}
-
-table#results td {
- padding:1em;
- padding-bottom:0.5em;
- border-bottom:thin solid black;
-}
-
-tr.pass > td:first-child {
- color:green;
-}
-
-tr.fail > td:first-child {
- color:red;
-}
-
-tr.timeout > td:first-child {
- color:red;
-}
-
-tr.notrun > td:first-child {
- color:blue;
-}
-
-.pass > td:first-child, .fail > td:first-child, .timeout > td:first-child, .notrun > td:first-child {
- font-variant:small-caps;
-}
-
-table#results span {
- display:block;
-}
-
-table#results span.expected {
- font-family:DejaVu Sans Mono, Bitstream Vera Sans Mono, Monospace;
- white-space:pre;
-}
-
-table#results span.actual {
- font-family:DejaVu Sans Mono, Bitstream Vera Sans Mono, Monospace;
- white-space:pre;
-}
-
diff --git a/test/testharness.js b/test/testharness.js
deleted file mode 100644
index 4b2a147..0000000
--- a/test/testharness.js
+++ /dev/null
@@ -1,2121 +0,0 @@
-/*
-Distributed under both the W3C Test Suite License [1] and the W3C
-3-clause BSD License [2]. To contribute to a W3C Test Suite, see the
-policies and contribution forms [3].
-
-[1] http://www.w3.org/Consortium/Legal/2008/04-testsuite-license
-[2] http://www.w3.org/Consortium/Legal/2008/03-bsd-license
-[3] http://www.w3.org/2004/10/27-testcases
-*/
-
-/*
- * == Introduction ==
- *
- * This file provides a framework for writing testcases. It is intended to
- * provide a convenient API for making common assertions, and to work both
- * for testing synchronous and asynchronous DOM features in a way that
- * promotes clear, robust, tests.
- *
- * == Basic Usage ==
- *
- * To use this file, import the script and the testharnessreport script into
- * the test document:
- * <script src="/resources/testharness.js"></script>
- * <script src="/resources/testharnessreport.js"></script>
- *
- * Within each file one may define one or more tests. Each test is atomic
- * in the sense that a single test has a single result (pass/fail/timeout).
- * Within each test one may have a number of asserts. The test fails at the
- * first failing assert, and the remainder of the test is (typically) not run.
- *
- * If the file containing the tests is a HTML file with an element of id "log"
- * this will be populated with a table containing the test results after all
- * the tests have run.
- *
- * NOTE: By default tests must be created before the load event fires. For ways
- * to create tests after the load event, see "Determining when all tests
- * are complete", below
- *
- * == Synchronous Tests ==
- *
- * To create a synchronous test use the test() function:
- *
- * test(test_function, name, properties)
- *
- * test_function is a function that contains the code to test. For example a
- * trivial passing test would be:
- *
- * test(function() {assert_true(true)}, "assert_true with true")
- *
- * The function passed in is run in the test() call.
- *
- * properties is an object that overrides default test properties. The
- * recognised properties are:
- * timeout - the test timeout in ms
- *
- * e.g.
- * test(test_function, "Sample test", {timeout:1000})
- *
- * would run test_function with a timeout of 1s.
- *
- * Additionally, test-specific metadata can be passed in the properties. These
- * are used when the individual test has different metadata from that stored
- * in the <head>.
- * The recognized metadata properties are:
- *
- * help - The url of the part of the specification being tested
- *
- * assert - A human readable description of what the test is attempting
- * to prove
- *
- * author - Name and contact information for the author of the test in the
- * format: "Name <email_addr>" or "Name https://contact/url"
- *
- * == Asynchronous Tests ==
- *
- * Testing asynchronous features is somewhat more complex since the result of
- * a test may depend on one or more events or other callbacks. The API provided
- * for testing these features is indended to be rather low-level but hopefully
- * applicable to many situations.
- *
- * To create a test, one starts by getting a Test object using async_test:
- *
- * async_test(name, properties)
- *
- * e.g.
- * var t = async_test("Simple async test")
- *
- * Assertions can be added to the test by calling the step method of the test
- * object with a function containing the test assertions:
- *
- * t.step(function() {assert_true(true)});
- *
- * When all the steps are complete, the done() method must be called:
- *
- * t.done();
- *
- * The properties argument is identical to that for test().
- *
- * In many cases it is convenient to run a step in response to an event or a
- * callback. A convenient method of doing this is through the step_func method
- * which returns a function that, when called runs a test step. For example
- *
- * object.some_event = t.step_func(function(e) {assert_true(e.a)});
- *
- * == Making assertions ==
- *
- * Functions for making assertions start assert_
- * The best way to get a list is to look in this file for functions names
- * matching that pattern. The general signature is
- *
- * assert_something(actual, expected, description)
- *
- * although not all assertions precisely match this pattern e.g. assert_true
- * only takes actual and description as arguments.
- *
- * The description parameter is used to present more useful error messages when
- * a test fails
- *
- * NOTE: All asserts must be located in a test() or a step of an async_test().
- * asserts outside these places won't be detected correctly by the harness
- * and may cause a file to stop testing.
- *
- * == Setup ==
- *
- * Sometimes tests require non-trivial setup that may fail. For this purpose
- * there is a setup() function, that may be called with one or two arguments.
- * The two argument version is:
- *
- * setup(func, properties)
- *
- * The one argument versions may omit either argument.
- * func is a function to be run synchronously. setup() becomes a no-op once
- * any tests have returned results. Properties are global properties of the test
- * harness. Currently recognised properties are:
- *
- * timeout - The time in ms after which the harness should stop waiting for
- * tests to complete (this is different to the per-test timeout
- * because async tests do not start their timer until .step is called)
- *
- * explicit_done - Wait for an explicit call to done() before declaring all
- * tests complete (see below)
- *
- * output_document - The document to which results should be logged. By default
- * this is the current document but could be an ancestor
- * document in some cases e.g. a SVG test loaded in an HTML
- * wrapper
- *
- * explicit_timeout - disable file timeout; only stop waiting for results
- * when the timeout() function is called (typically for
- * use when integrating with some existing test framework
- * that has its own timeout mechanism).
- *
- * == Determining when all tests are complete ==
- *
- * By default the test harness will assume there are no more results to come
- * when:
- * 1) There are no Test objects that have been created but not completed
- * 2) The load event on the document has fired
- *
- * This behaviour can be overridden by setting the explicit_done property to
- * true in a call to setup(). If explicit_done is true, the test harness will
- * not assume it is done until the global done() function is called. Once done()
- * is called, the two conditions above apply like normal.
- *
- * == Generating tests ==
- *
- * NOTE: this functionality may be removed
- *
- * There are scenarios in which is is desirable to create a large number of
- * (synchronous) tests that are internally similar but vary in the parameters
- * used. To make this easier, the generate_tests function allows a single
- * function to be called with each set of parameters in a list:
- *
- * generate_tests(test_function, parameter_lists, properties)
- *
- * For example:
- *
- * generate_tests(assert_equals, [
- * ["Sum one and one", 1+1, 2],
- * ["Sum one and zero", 1+0, 1]
- * ])
- *
- * Is equivalent to:
- *
- * test(function() {assert_equals(1+1, 2)}, "Sum one and one")
- * test(function() {assert_equals(1+0, 1)}, "Sum one and zero")
- *
- * Note that the first item in each parameter list corresponds to the name of
- * the test.
- *
- * The properties argument is identical to that for test(). This may be a
- * single object (used for all generated tests) or an array.
- *
- * == Callback API ==
- *
- * The framework provides callbacks corresponding to 3 events:
- *
- * start - happens when the first Test is created
- * result - happens when a test result is recieved
- * complete - happens when all results are recieved
- *
- * The page defining the tests may add callbacks for these events by calling
- * the following methods:
- *
- * add_start_callback(callback) - callback called with no arguments
- * add_result_callback(callback) - callback called with a test argument
- * add_completion_callback(callback) - callback called with an array of tests
- * and an status object
- *
- * tests have the following properties:
- * status: A status code. This can be compared to the PASS, FAIL, TIMEOUT and
- * NOTRUN properties on the test object
- * message: A message indicating the reason for failure. In the future this
- * will always be a string
- *
- * The status object gives the overall status of the harness. It has the
- * following properties:
- * status: Can be compared to the OK, ERROR and TIMEOUT properties
- * message: An error message set when the status is ERROR
- *
- * == External API ==
- *
- * In order to collect the results of multiple pages containing tests, the test
- * harness will, when loaded in a nested browsing context, attempt to call
- * certain functions in each ancestor and opener browsing context:
- *
- * start - start_callback
- * result - result_callback
- * complete - completion_callback
- *
- * These are given the same arguments as the corresponding internal callbacks
- * described above.
- *
- * == External API through cross-document messaging ==
- *
- * Where supported, the test harness will also send messages using
- * cross-document messaging to each ancestor and opener browsing context. Since
- * it uses the wildcard keyword (*), cross-origin communication is enabled and
- * script on different origins can collect the results.
- *
- * This API follows similar conventions as those described above only slightly
- * modified to accommodate message event API. Each message is sent by the harness
- * is passed a single vanilla object, available as the `data` property of the
- * event object. These objects are structures as follows:
- *
- * start - { type: "start" }
- * result - { type: "result", test: Test }
- * complete - { type: "complete", tests: [Test, ...], status: TestsStatus }
- *
- * == List of assertions ==
- *
- * assert_true(actual, description)
- * asserts that /actual/ is strictly true
- *
- * assert_false(actual, description)
- * asserts that /actual/ is strictly false
- *
- * assert_equals(actual, expected, description)
- * asserts that /actual/ is the same value as /expected/
- *
- * assert_not_equals(actual, expected, description)
- * asserts that /actual/ is a different value to /expected/. Yes, this means
- * that "expected" is a misnomer
- *
- * assert_in_array(actual, expected, description)
- * asserts that /expected/ is an Array, and /actual/ is equal to one of the
- * members -- expected.indexOf(actual) != -1
- *
- * assert_array_equals(actual, expected, description)
- * asserts that /actual/ and /expected/ have the same length and the value of
- * each indexed property in /actual/ is the strictly equal to the corresponding
- * property value in /expected/
- *
- * assert_approx_equals(actual, expected, epsilon, description)
- * asserts that /actual/ is a number within +/- /epsilon/ of /expected/
- *
- * assert_regexp_match(actual, expected, description)
- * asserts that /actual/ matches the regexp /expected/
- *
- * assert_class_string(object, class_name, description)
- * asserts that the class string of /object/ as returned in
- * Object.prototype.toString is equal to /class_name/.
- *
- * assert_own_property(object, property_name, description)
- * assert that object has own property property_name
- *
- * assert_inherits(object, property_name, description)
- * assert that object does not have an own property named property_name
- * but that property_name is present in the prototype chain for object
- *
- * assert_idl_attribute(object, attribute_name, description)
- * assert that an object that is an instance of some interface has the
- * attribute attribute_name following the conditions specified by WebIDL
- *
- * assert_readonly(object, property_name, description)
- * assert that property property_name on object is readonly
- *
- * assert_throws(code, func, description)
- * code - the expected exception:
- * o string: the thrown exception must be a DOMException with the given
- * name, e.g., "TimeoutError" (for compatibility with existing
- * tests, a constant is also supported, e.g., "TIMEOUT_ERR")
- * o object: the thrown exception must have a property called "name" that
- * matches code.name
- * o null: allow any exception (in general, one of the options above
- * should be used)
- * func - a function that should throw
- *
- * assert_unreached(description)
- * asserts if called. Used to ensure that some codepath is *not* taken e.g.
- * an event does not fire.
- *
- * assert_any(assert_func, actual, expected_array, extra_arg_1, ... extra_arg_N)
- * asserts that one assert_func(actual, expected_array_N, extra_arg1, ..., extra_arg_N)
- * is true for some expected_array_N in expected_array. This only works for assert_func
- * with signature assert_func(actual, expected, args_1, ..., args_N). Note that tests
- * with multiple allowed pass conditions are bad practice unless the spec specifically
- * allows multiple behaviours. Test authors should not use this method simply to hide
- * UA bugs.
- *
- * assert_exists(object, property_name, description)
- * *** deprecated ***
- * asserts that object has an own property property_name
- *
- * assert_not_exists(object, property_name, description)
- * *** deprecated ***
- * assert that object does not have own property property_name
- */
-
-(function ()
-{
- var debug = false;
- // default timeout is 5 seconds, test can override if needed
- var settings = {
- output:true,
- timeout:5000,
- test_timeout:2000
- };
-
- var xhtml_ns = "http://www.w3.org/1999/xhtml";
-
- // script_prefix is used by Output.prototype.show_results() to figure out
- // where to get testharness.css from. It's enclosed in an extra closure to
- // not pollute the library's namespace with variables like "src".
- var script_prefix = null;
- (function ()
- {
- var scripts = document.getElementsByTagName("script");
- for (var i = 0; i < scripts.length; i++)
- {
- if (scripts[i].src)
- {
- var src = scripts[i].src;
- }
- else if (scripts[i].href)
- {
- //SVG case
- var src = scripts[i].href.baseVal;
- }
- if (src && src.slice(src.length - "testharness.js".length) === "testharness.js")
- {
- script_prefix = src.slice(0, src.length - "testharness.js".length);
- break;
- }
- }
- })();
-
- /*
- * API functions
- */
-
- var name_counter = 0;
- function next_default_name()
- {
- //Don't use document.title to work around an Opera bug in XHTML documents
- var prefix = document.getElementsByTagName("title").length > 0 ?
- document.getElementsByTagName("title")[0].firstChild.data :
- "Untitled";
- var suffix = name_counter > 0 ? " " + name_counter : "";
- name_counter++;
- return prefix + suffix;
- }
-
- function test(func, name, properties)
- {
- var test_name = name ? name : next_default_name();
- properties = properties ? properties : {};
- var test_obj = new Test(test_name, properties);
- test_obj.step(func);
- if (test_obj.status === test_obj.NOTRUN) {
- test_obj.done();
- }
- }
-
- function async_test(name, properties)
- {
- var test_name = name ? name : next_default_name();
- properties = properties ? properties : {};
- var test_obj = new Test(test_name, properties);
- return test_obj;
- }
-
- function setup(func_or_properties, maybe_properties)
- {
- var func = null;
- var properties = {};
- if (arguments.length === 2) {
- func = func_or_properties;
- properties = maybe_properties;
- } else if (func_or_properties instanceof Function){
- func = func_or_properties;
- } else {
- properties = func_or_properties;
- }
- tests.setup(func, properties);
- output.setup(properties);
- }
-
- function done() {
- tests.end_wait();
- }
-
- function generate_tests(func, args, properties) {
- forEach(args, function(x, i)
- {
- var name = x[0];
- test(function()
- {
- func.apply(this, x.slice(1));
- },
- name,
- Array.isArray(properties) ? properties[i] : properties);
- });
- }
-
- function on_event(object, event, callback)
- {
- object.addEventListener(event, callback, false);
- }
-
- expose(test, 'test');
- expose(async_test, 'async_test');
- expose(generate_tests, 'generate_tests');
- expose(setup, 'setup');
- expose(done, 'done');
- expose(on_event, 'on_event');
-
- /*
- * Return a string truncated to the given length, with ... added at the end
- * if it was longer.
- */
- function truncate(s, len)
- {
- if (s.length > len) {
- return s.substring(0, len - 3) + "...";
- }
- return s;
- }
-
- /*
- * Convert a value to a nice, human-readable string
- */
- function format_value(val)
- {
- if (Array.isArray(val))
- {
- return "[" + val.map(format_value).join(", ") + "]";
- }
-
- switch (typeof val)
- {
- case "string":
- val = val.replace("\\", "\\\\");
- for (var i = 0; i < 32; i++)
- {
- var replace = "\\";
- switch (i) {
- case 0: replace += "0"; break;
- case 1: replace += "x01"; break;
- case 2: replace += "x02"; break;
- case 3: replace += "x03"; break;
- case 4: replace += "x04"; break;
- case 5: replace += "x05"; break;
- case 6: replace += "x06"; break;
- case 7: replace += "x07"; break;
- case 8: replace += "b"; break;
- case 9: replace += "t"; break;
- case 10: replace += "n"; break;
- case 11: replace += "v"; break;
- case 12: replace += "f"; break;
- case 13: replace += "r"; break;
- case 14: replace += "x0e"; break;
- case 15: replace += "x0f"; break;
- case 16: replace += "x10"; break;
- case 17: replace += "x11"; break;
- case 18: replace += "x12"; break;
- case 19: replace += "x13"; break;
- case 20: replace += "x14"; break;
- case 21: replace += "x15"; break;
- case 22: replace += "x16"; break;
- case 23: replace += "x17"; break;
- case 24: replace += "x18"; break;
- case 25: replace += "x19"; break;
- case 26: replace += "x1a"; break;
- case 27: replace += "x1b"; break;
- case 28: replace += "x1c"; break;
- case 29: replace += "x1d"; break;
- case 30: replace += "x1e"; break;
- case 31: replace += "x1f"; break;
- }
- val = val.replace(RegExp(String.fromCharCode(i), "g"), replace);
- }
- return '"' + val.replace(/"/g, '\\"') + '"';
- case "boolean":
- case "undefined":
- return String(val);
- case "number":
- // In JavaScript, -0 === 0 and String(-0) == "0", so we have to
- // special-case.
- if (val === -0 && 1/val === -Infinity)
- {
- return "-0";
- }
- return String(val);
- case "object":
- if (val === null)
- {
- return "null";
- }
-
- // Special-case Node objects, since those come up a lot in my tests. I
- // ignore namespaces. I use duck-typing instead of instanceof, because
- // instanceof doesn't work if the node is from another window (like an
- // iframe's contentWindow):
- // https://www.w3.org/Bugs/Public/show_bug.cgi?id=12295
- if ("nodeType" in val
- && "nodeName" in val
- && "nodeValue" in val
- && "childNodes" in val)
- {
- switch (val.nodeType)
- {
- case Node.ELEMENT_NODE:
- var ret = "<" + val.tagName.toLowerCase();
- for (var i = 0; i < val.attributes.length; i++)
- {
- ret += " " + val.attributes[i].name + '="' + val.attributes[i].value + '"';
- }
- ret += ">" + val.innerHTML + "</" + val.tagName.toLowerCase() + ">";
- return "Element node " + truncate(ret, 60);
- case Node.TEXT_NODE:
- return 'Text node "' + truncate(val.data, 60) + '"';
- case Node.PROCESSING_INSTRUCTION_NODE:
- return "ProcessingInstruction node with target " + format_value(truncate(val.target, 60)) + " and data " + format_value(truncate(val.data, 60));
- case Node.COMMENT_NODE:
- return "Comment node <!--" + truncate(val.data, 60) + "-->";
- case Node.DOCUMENT_NODE:
- return "Document node with " + val.childNodes.length + (val.childNodes.length == 1 ? " child" : " children");
- case Node.DOCUMENT_TYPE_NODE:
- return "DocumentType node";
- case Node.DOCUMENT_FRAGMENT_NODE:
- return "DocumentFragment node with " + val.childNodes.length + (val.childNodes.length == 1 ? " child" : " children");
- default:
- return "Node object of unknown type";
- }
- }
-
- // Fall through to default
- default:
- return typeof val + ' "' + truncate(String(val), 60) + '"';
- }
- }
- expose(format_value, "format_value");
-
- /*
- * Assertions
- */
-
- function assert_true(actual, description)
- {
- assert(actual === true, "assert_true", description,
- "expected true got ${actual}", {actual:actual});
- };
- expose(assert_true, "assert_true");
-
- function assert_false(actual, description)
- {
- assert(actual === false, "assert_false", description,
- "expected false got ${actual}", {actual:actual});
- };
- expose(assert_false, "assert_false");
-
- function same_value(x, y) {
- if (y !== y)
- {
- //NaN case
- return x !== x;
- }
- else if (x === 0 && y === 0) {
- //Distinguish +0 and -0
- return 1/x === 1/y;
- }
- else
- {
- //typical case
- return x === y;
- }
- }
-
- function assert_equals(actual, expected, description)
- {
- /*
- * Test if two primitives are equal or two objects
- * are the same object
- */
- if (typeof actual != typeof expected)
- {
- assert(false, "assert_equals", description,
- "expected (" + typeof expected + ") ${expected} but got (" + typeof actual + ") ${actual}",
- {expected:expected, actual:actual});
- return;
- }
- assert(same_value(actual, expected), "assert_equals", description,
- "expected ${expected} but got ${actual}",
- {expected:expected, actual:actual});
- };
- expose(assert_equals, "assert_equals");
-
- function assert_not_equals(actual, expected, description)
- {
- /*
- * Test if two primitives are unequal or two objects
- * are different objects
- */
- assert(!same_value(actual, expected), "assert_not_equals", description,
- "got disallowed value ${actual}",
- {actual:actual});
- };
- expose(assert_not_equals, "assert_not_equals");
-
- function assert_in_array(actual, expected, description)
- {
- assert(expected.indexOf(actual) != -1, "assert_in_array", description,
- "value ${actual} not in array ${expected}",
- {actual:actual, expected:expected});
- }
- expose(assert_in_array, "assert_in_array");
-
- function assert_object_equals(actual, expected, description)
- {
- //This needs to be improved a great deal
- function check_equal(actual, expected, stack)
- {
- stack.push(actual);
-
- var p;
- for (p in actual)
- {
- assert(expected.hasOwnProperty(p), "assert_object_equals", description,
- "unexpected property ${p}", {p:p});
-
- if (typeof actual[p] === "object" && actual[p] !== null)
- {
- if (stack.indexOf(actual[p]) === -1)
- {
- check_equal(actual[p], expected[p], stack);
- }
- }
- else
- {
- assert(actual[p] === expected[p], "assert_object_equals", description,
- "property ${p} expected ${expected} got ${actual}",
- {p:p, expected:expected, actual:actual});
- }
- }
- for (p in expected)
- {
- assert(actual.hasOwnProperty(p),
- "assert_object_equals", description,
- "expected property ${p} missing", {p:p});
- }
- stack.pop();
- }
- check_equal(actual, expected, []);
- };
- expose(assert_object_equals, "assert_object_equals");
-
- function assert_array_equals(actual, expected, description)
- {
- assert(actual.length === expected.length,
- "assert_array_equals", description,
- "lengths differ, expected ${expected} got ${actual}",
- {expected:expected.length, actual:actual.length});
-
- for (var i=0; i < actual.length; i++)
- {
- assert(actual.hasOwnProperty(i) === expected.hasOwnProperty(i),
- "assert_array_equals", description,
- "property ${i}, property expected to be $expected but was $actual",
- {i:i, expected:expected.hasOwnProperty(i) ? "present" : "missing",
- actual:actual.hasOwnProperty(i) ? "present" : "missing"});
- assert(expected[i] === actual[i],
- "assert_array_equals", description,
- "property ${i}, expected ${expected} but got ${actual}",
- {i:i, expected:expected[i], actual:actual[i]});
- }
- }
- expose(assert_array_equals, "assert_array_equals");
-
- function assert_approx_equals(actual, expected, epsilon, description)
- {
- /*
- * Test if two primitive numbers are equal withing +/- epsilon
- */
- assert(typeof actual === "number",
- "assert_approx_equals", description,
- "expected a number but got a ${type_actual}",
- {type_actual:typeof actual});
-
- assert(Math.abs(actual - expected) <= epsilon,
- "assert_approx_equals", description,
- "expected ${expected} +/- ${epsilon} but got ${actual}",
- {expected:expected, actual:actual, epsilon:epsilon});
- };
- expose(assert_approx_equals, "assert_approx_equals");
-
- function assert_regexp_match(actual, expected, description) {
- /*
- * Test if a string (actual) matches a regexp (expected)
- */
- assert(expected.test(actual),
- "assert_regexp_match", description,
- "expected ${expected} but got ${actual}",
- {expected:expected, actual:actual});
- }
- expose(assert_regexp_match, "assert_regexp_match");
-
- function assert_class_string(object, class_string, description) {
- assert_equals({}.toString.call(object), "[object " + class_string + "]",
- description);
- }
- expose(assert_class_string, "assert_class_string");
-
-
- function _assert_own_property(name) {
- return function(object, property_name, description)
- {
- assert(object.hasOwnProperty(property_name),
- name, description,
- "expected property ${p} missing", {p:property_name});
- };
- }
- expose(_assert_own_property("assert_exists"), "assert_exists");
- expose(_assert_own_property("assert_own_property"), "assert_own_property");
-
- function assert_not_exists(object, property_name, description)
- {
- assert(!object.hasOwnProperty(property_name),
- "assert_not_exists", description,
- "unexpected property ${p} found", {p:property_name});
- };
- expose(assert_not_exists, "assert_not_exists");
-
- function _assert_inherits(name) {
- return function (object, property_name, description)
- {
- assert(typeof object === "object",
- name, description,
- "provided value is not an object");
-
- assert("hasOwnProperty" in object,
- name, description,
- "provided value is an object but has no hasOwnProperty method");
-
- assert(!object.hasOwnProperty(property_name),
- name, description,
- "property ${p} found on object expected in prototype chain",
- {p:property_name});
-
- assert(property_name in object,
- name, description,
- "property ${p} not found in prototype chain",
- {p:property_name});
- };
- }
- expose(_assert_inherits("assert_inherits"), "assert_inherits");
- expose(_assert_inherits("assert_idl_attribute"), "assert_idl_attribute");
-
- function assert_readonly(object, property_name, description)
- {
- var initial_value = object[property_name];
- try {
- //Note that this can have side effects in the case where
- //the property has PutForwards
- object[property_name] = initial_value + "a"; //XXX use some other value here?
- assert(object[property_name] === initial_value,
- "assert_readonly", description,
- "changing property ${p} succeeded",
- {p:property_name});
- }
- finally
- {
- object[property_name] = initial_value;
- }
- };
- expose(assert_readonly, "assert_readonly");
-
- function assert_throws(code, func, description)
- {
- try
- {
- func.call(this);
- assert(false, "assert_throws", description,
- "${func} did not throw", {func:func});
- }
- catch(e)
- {
- if (e instanceof AssertionError) {
- throw(e);
- }
- if (code === null)
- {
- return;
- }
- if (typeof code === "object")
- {
- assert(typeof e == "object" && "name" in e && e.name == code.name,
- "assert_throws", description,
- "${func} threw ${actual} (${actual_name}) expected ${expected} (${expected_name})",
- {func:func, actual:e, actual_name:e.name,
- expected:code,
- expected_name:code.name});
- return;
- }
-
- var code_name_map = {
- INDEX_SIZE_ERR: 'IndexSizeError',
- HIERARCHY_REQUEST_ERR: 'HierarchyRequestError',
- WRONG_DOCUMENT_ERR: 'WrongDocumentError',
- INVALID_CHARACTER_ERR: 'InvalidCharacterError',
- NO_MODIFICATION_ALLOWED_ERR: 'NoModificationAllowedError',
- NOT_FOUND_ERR: 'NotFoundError',
- NOT_SUPPORTED_ERR: 'NotSupportedError',
- INVALID_STATE_ERR: 'InvalidStateError',
- SYNTAX_ERR: 'SyntaxError',
- INVALID_MODIFICATION_ERR: 'InvalidModificationError',
- NAMESPACE_ERR: 'NamespaceError',
- INVALID_ACCESS_ERR: 'InvalidAccessError',
- TYPE_MISMATCH_ERR: 'TypeMismatchError',
- SECURITY_ERR: 'SecurityError',
- NETWORK_ERR: 'NetworkError',
- ABORT_ERR: 'AbortError',
- URL_MISMATCH_ERR: 'URLMismatchError',
- QUOTA_EXCEEDED_ERR: 'QuotaExceededError',
- TIMEOUT_ERR: 'TimeoutError',
- INVALID_NODE_TYPE_ERR: 'InvalidNodeTypeError',
- DATA_CLONE_ERR: 'DataCloneError',
- };
-
- var name = code in code_name_map ? code_name_map[code] : code;
-
- var name_code_map = {
- IndexSizeError: 1,
- HierarchyRequestError: 3,
- WrongDocumentError: 4,
- InvalidCharacterError: 5,
- NoModificationAllowedError: 7,
- NotFoundError: 8,
- NotSupportedError: 9,
- InvalidStateError: 11,
- SyntaxError: 12,
- InvalidModificationError: 13,
- NamespaceError: 14,
- InvalidAccessError: 15,
- TypeMismatchError: 17,
- SecurityError: 18,
- NetworkError: 19,
- AbortError: 20,
- URLMismatchError: 21,
- QuotaExceededError: 22,
- TimeoutError: 23,
- InvalidNodeTypeError: 24,
- DataCloneError: 25,
-
- UnknownError: 0,
- ConstraintError: 0,
- DataError: 0,
- TransactionInactiveError: 0,
- ReadOnlyError: 0,
- VersionError: 0,
- };
-
- if (!(name in name_code_map))
- {
- throw new AssertionError('Test bug: unrecognized DOMException code "' + code + '" passed to assert_throws()');
- }
-
- var required_props = { code: name_code_map[name] };
-
- if (required_props.code === 0
- || ("name" in e && e.name !== e.name.toUpperCase() && e.name !== "DOMException"))
- {
- // New style exception: also test the name property.
- required_props.name = name;
- }
-
- //We'd like to test that e instanceof the appropriate interface,
- //but we can't, because we don't know what window it was created
- //in. It might be an instanceof the appropriate interface on some
- //unknown other window. TODO: Work around this somehow?
-
- assert(typeof e == "object",
- "assert_throws", description,
- "${func} threw ${e} with type ${type}, not an object",
- {func:func, e:e, type:typeof e});
-
- for (var prop in required_props)
- {
- assert(typeof e == "object" && prop in e && e[prop] == required_props[prop],
- "assert_throws", description,
- "${func} threw ${e} that is not a DOMException " + code + ": property ${prop} is equal to ${actual}, expected ${expected}",
- {func:func, e:e, prop:prop, actual:e[prop], expected:required_props[prop]});
- }
- }
- }
- expose(assert_throws, "assert_throws");
-
- function assert_unreached(description) {
- assert(false, "assert_unreached", description,
- "Reached unreachable code");
- }
- expose(assert_unreached, "assert_unreached");
-
- function assert_any(assert_func, actual, expected_array)
- {
- var args = [].slice.call(arguments, 3)
- var errors = []
- var passed = false;
- forEach(expected_array,
- function(expected)
- {
- try {
- assert_func.apply(this, [actual, expected].concat(args))
- passed = true;
- } catch(e) {
- errors.push(e.message);
- }
- });
- if (!passed) {
- throw new AssertionError(errors.join("\n\n"));
- }
- }
- expose(assert_any, "assert_any");
-
- function Test(name, properties)
- {
- this.name = name;
- this.status = this.NOTRUN;
- this.timeout_id = null;
- this.is_done = false;
-
- this.properties = properties;
- this.timeout_length = properties.timeout ? properties.timeout : settings.test_timeout;
-
- this.message = null;
-
- var this_obj = this;
- this.steps = [];
-
- tests.push(this);
- }
-
- Test.statuses = {
- PASS:0,
- FAIL:1,
- TIMEOUT:2,
- NOTRUN:3
- };
-
- Test.prototype = merge({}, Test.statuses);
-
- Test.prototype.structured_clone = function()
- {
- if(!this._structured_clone)
- {
- var msg = this.message;
- msg = msg ? String(msg) : msg;
- this._structured_clone = merge({
- name:String(this.name),
- status:this.status,
- message:msg
- }, Test.statuses);
- }
- return this._structured_clone;
- };
-
- Test.prototype.step = function(func, this_obj)
- {
- //In case the test has already failed
- if (this.status !== this.NOTRUN)
- {
- return;
- }
-
- tests.started = true;
-
- if (this.timeout_id === null) {
- this.set_timeout();
- }
-
- this.steps.push(func);
-
- if (arguments.length === 1)
- {
- this_obj = this;
- }
-
- try
- {
- func.apply(this_obj, Array.prototype.slice.call(arguments, 2));
- }
- catch(e)
- {
- //This can happen if something called synchronously invoked another
- //step
- if (this.status !== this.NOTRUN)
- {
- return;
- }
- this.status = this.FAIL;
- this.message = (typeof e === "object" && e !== null) ? e.message : e;
- if (typeof e.stack != "undefined" && typeof e.message == "string") {
- //Try to make it more informative for some exceptions, at least
- //in Gecko and WebKit. This results in a stack dump instead of
- //just errors like "Cannot read property 'parentNode' of null"
- //or "root is null". Makes it a lot longer, of course.
- this.message += "(stack: " + e.stack + ")";
- }
- this.done();
- if (debug && e.constructor !== AssertionError) {
- throw e;
- }
- }
- };
-
- Test.prototype.step_func = function(func, this_obj)
- {
- var test_this = this;
-
- if (arguments.length === 1)
- {
- this_obj = test_this;
- }
-
- return function()
- {
- test_this.step.apply(test_this, [func, this_obj].concat(
- Array.prototype.slice.call(arguments)));
- };
- };
-
- Test.prototype.step_func_done = function(func, this_obj)
- {
- var test_this = this;
-
- if (arguments.length === 1)
- {
- this_obj = test_this;
- }
-
- return function()
- {
- test_this.step.apply(test_this, [func, this_obj].concat(
- Array.prototype.slice.call(arguments)));
- test_this.done();
- };
- };
-
- Test.prototype.set_timeout = function()
- {
- var this_obj = this;
- this.timeout_id = setTimeout(function()
- {
- this_obj.timeout();
- }, this.timeout_length);
- };
-
- Test.prototype.timeout = function()
- {
- this.status = this.TIMEOUT;
- this.timeout_id = null;
- this.message = "Test timed out";
- this.done();
- };
-
- Test.prototype.done = function()
- {
- if (this.is_done) {
- return;
- }
- clearTimeout(this.timeout_id);
- if (this.status === this.NOTRUN)
- {
- this.status = this.PASS;
- }
- this.is_done = true;
- tests.result(this);
- };
-
-
- /*
- * Harness
- */
-
- function TestsStatus()
- {
- this.status = null;
- this.message = null;
- }
-
- TestsStatus.statuses = {
- OK:0,
- ERROR:1,
- TIMEOUT:2
- };
-
- TestsStatus.prototype = merge({}, TestsStatus.statuses);
-
- TestsStatus.prototype.structured_clone = function()
- {
- if(!this._structured_clone)
- {
- var msg = this.message;
- msg = msg ? String(msg) : msg;
- this._structured_clone = merge({
- status:this.status,
- message:msg
- }, TestsStatus.statuses);
- }
- return this._structured_clone;
- };
-
- function Tests()
- {
- this.tests = [];
- this.num_pending = 0;
-
- this.phases = {
- INITIAL:0,
- SETUP:1,
- HAVE_TESTS:2,
- HAVE_RESULTS:3,
- COMPLETE:4
- };
- this.phase = this.phases.INITIAL;
-
- this.properties = {};
-
- //All tests can't be done until the load event fires
- this.all_loaded = false;
- this.wait_for_finish = false;
- this.processing_callbacks = false;
-
- this.timeout_length = settings.timeout;
- this.timeout_id = null;
-
- this.start_callbacks = [];
- this.test_done_callbacks = [];
- this.all_done_callbacks = [];
-
- this.status = new TestsStatus();
-
- var this_obj = this;
-
- on_event(window, "load",
- function()
- {
- this_obj.all_loaded = true;
- if (this_obj.all_done())
- {
- this_obj.complete();
- }
- });
-
- this.set_timeout();
- }
-
- Tests.prototype.setup = function(func, properties)
- {
- if (this.phase >= this.phases.HAVE_RESULTS)
- {
- return;
- }
- if (this.phase < this.phases.SETUP)
- {
- this.phase = this.phases.SETUP;
- }
-
- for (var p in properties)
- {
- if (properties.hasOwnProperty(p))
- {
- this.properties[p] = properties[p];
- }
- }
-
- if (properties.timeout)
- {
- this.timeout_length = properties.timeout;
- }
- if (properties.explicit_done)
- {
- this.wait_for_finish = true;
- }
- if (properties.explicit_timeout) {
- this.timeout_length = null;
- }
-
- if (func)
- {
- try
- {
- func();
- } catch(e)
- {
- this.status.status = this.status.ERROR;
- this.status.message = e;
- };
- }
- this.set_timeout();
- };
-
- Tests.prototype.set_timeout = function()
- {
- var this_obj = this;
- clearTimeout(this.timeout_id);
- if (this.timeout_length !== null)
- {
- this.timeout_id = setTimeout(function() {
- this_obj.timeout();
- }, this.timeout_length);
- }
- };
-
- Tests.prototype.timeout = function() {
- this.status.status = this.status.TIMEOUT;
- this.complete();
- };
-
- Tests.prototype.end_wait = function()
- {
- this.wait_for_finish = false;
- if (this.all_done()) {
- this.complete();
- }
- };
-
- Tests.prototype.push = function(test)
- {
- if (this.phase < this.phases.HAVE_TESTS) {
- this.start();
- }
- this.num_pending++;
- this.tests.push(test);
- };
-
- Tests.prototype.all_done = function() {
- return (this.all_loaded && this.num_pending === 0 &&
- !this.wait_for_finish && !this.processing_callbacks);
- };
-
- Tests.prototype.start = function() {
- this.phase = this.phases.HAVE_TESTS;
- this.notify_start();
- };
-
- Tests.prototype.notify_start = function() {
- var this_obj = this;
- forEach (this.start_callbacks,
- function(callback)
- {
- callback(this_obj.properties);
- });
- forEach_windows(
- function(w, is_same_origin)
- {
- if(is_same_origin && w.start_callback)
- {
- try
- {
- w.start_callback(this_obj.properties);
- }
- catch(e)
- {
- if (debug)
- {
- throw(e);
- }
- }
- }
- if (supports_post_message(w))
- {
- w.postMessage({
- type: "start",
- properties: this_obj.properties
- }, "*");
- }
- });
- };
-
- Tests.prototype.result = function(test)
- {
- if (this.phase > this.phases.HAVE_RESULTS)
- {
- return;
- }
- this.phase = this.phases.HAVE_RESULTS;
- this.num_pending--;
- this.notify_result(test);
- };
-
- Tests.prototype.notify_result = function(test) {
- var this_obj = this;
- this.processing_callbacks = true;
- forEach(this.test_done_callbacks,
- function(callback)
- {
- callback(test, this_obj);
- });
-
- forEach_windows(
- function(w, is_same_origin)
- {
- if(is_same_origin && w.result_callback)
- {
- try
- {
- w.result_callback(test);
- }
- catch(e)
- {
- if(debug) {
- throw e;
- }
- }
- }
- if (supports_post_message(w))
- {
- w.postMessage({
- type: "result",
- test: test.structured_clone()
- }, "*");
- }
- });
- this.processing_callbacks = false;
- if (this_obj.all_done())
- {
- this_obj.complete();
- }
- };
-
- Tests.prototype.complete = function() {
- if (this.phase === this.phases.COMPLETE) {
- return;
- }
- this.phase = this.phases.COMPLETE;
- var this_obj = this;
- this.tests.forEach(
- function(x)
- {
- if(x.status === x.NOTRUN)
- {
- this_obj.notify_result(x);
- }
- }
- );
- this.notify_complete();
- };
-
- Tests.prototype.notify_complete = function()
- {
- clearTimeout(this.timeout_id);
- var this_obj = this;
- var tests = map(this_obj.tests,
- function(test)
- {
- return test.structured_clone();
- });
- if (this.status.status === null)
- {
- this.status.status = this.status.OK;
- }
-
- forEach (this.all_done_callbacks,
- function(callback)
- {
- callback(this_obj.tests, this_obj.status);
- });
-
- forEach_windows(
- function(w, is_same_origin)
- {
- if(is_same_origin && w.completion_callback)
- {
- try
- {
- w.completion_callback(this_obj.tests, this_obj.status);
- }
- catch(e)
- {
- if (debug)
- {
- throw e;
- }
- }
- }
- if (supports_post_message(w))
- {
- w.postMessage({
- type: "complete",
- tests: tests,
- status: this_obj.status.structured_clone()
- }, "*");
- }
- });
- };
-
- var tests = new Tests();
-
- function timeout() {
- if (tests.timeout_length === null)
- {
- tests.timeout();
- }
- }
- expose(timeout, 'timeout');
-
- function add_start_callback(callback) {
- tests.start_callbacks.push(callback);
- }
-
- function add_result_callback(callback)
- {
- tests.test_done_callbacks.push(callback);
- }
-
- function add_completion_callback(callback)
- {
- tests.all_done_callbacks.push(callback);
- }
-
- expose(add_start_callback, 'add_start_callback');
- expose(add_result_callback, 'add_result_callback');
- expose(add_completion_callback, 'add_completion_callback');
-
- /*
- * Output listener
- */
-
- function Output() {
- this.output_document = null;
- this.output_node = null;
- this.done_count = 0;
- this.enabled = settings.output;
- this.phase = this.INITIAL;
- }
-
- Output.prototype.INITIAL = 0;
- Output.prototype.STARTED = 1;
- Output.prototype.HAVE_RESULTS = 2;
- Output.prototype.COMPLETE = 3;
-
- Output.prototype.setup = function(properties) {
- if (this.phase > this.INITIAL) {
- return;
- }
-
- //If output is disabled in testharnessreport.js the test shouldn't be
- //able to override that
- this.enabled = this.enabled && (properties.hasOwnProperty("output") ?
- properties.output : settings.output);
- };
-
- Output.prototype.init = function(properties)
- {
- if (this.phase >= this.STARTED) {
- return;
- }
- if (properties.output_document) {
- this.output_document = properties.output_document;
- } else {
- this.output_document = document;
- }
- this.phase = this.STARTED;
- };
-
- Output.prototype.resolve_log = function()
- {
- var output_document;
- if (typeof this.output_document === "function")
- {
- output_document = this.output_document.apply(undefined);
- } else
- {
- output_document = this.output_document;
- }
- if (!output_document)
- {
- return;
- }
- var node = output_document.getElementById("log");
- if (node)
- {
- this.output_document = output_document;
- this.output_node = node;
- }
- };
-
- Output.prototype.show_status = function(test)
- {
- if (this.phase < this.STARTED)
- {
- this.init();
- }
- if (!this.enabled)
- {
- return;
- }
- if (this.phase < this.HAVE_RESULTS)
- {
- this.resolve_log();
- this.phase = this.HAVE_RESULTS;
- }
- this.done_count++;
- if (this.output_node)
- {
- if (this.done_count < 100
- || (this.done_count < 1000 && this.done_count % 100 == 0)
- || this.done_count % 1000 == 0) {
- this.output_node.textContent = "Running, "
- + this.done_count + " complete, "
- + tests.num_pending + " remain";
- }
- }
- };
-
- Output.prototype.show_results = function (tests, harness_status)
- {
- if (this.phase >= this.COMPLETE) {
- return;
- }
- if (!this.enabled)
- {
- return;
- }
- if (!this.output_node) {
- this.resolve_log();
- }
- this.phase = this.COMPLETE;
-
- var log = this.output_node;
- if (!log)
- {
- return;
- }
- var output_document = this.output_document;
-
- while (log.lastChild)
- {
- log.removeChild(log.lastChild);
- }
-
- if (script_prefix != null) {
- var stylesheet = output_document.createElementNS(xhtml_ns, "link");
- stylesheet.setAttribute("rel", "stylesheet");
- stylesheet.setAttribute("href", script_prefix + "testharness.css");
- var heads = output_document.getElementsByTagName("head");
- if (heads.length) {
- heads[0].appendChild(stylesheet);
- }
- }
-
- var status_text = {};
- status_text[Test.prototype.PASS] = "Pass";
- status_text[Test.prototype.FAIL] = "Fail";
- status_text[Test.prototype.TIMEOUT] = "Timeout";
- status_text[Test.prototype.NOTRUN] = "Not Run";
-
- var status_number = {};
- forEach(tests, function(test) {
- var status = status_text[test.status];
- if (status_number.hasOwnProperty(status))
- {
- status_number[status] += 1;
- } else {
- status_number[status] = 1;
- }
- });
-
- function status_class(status)
- {
- return status.replace(/\s/g, '').toLowerCase();
- }
-
- var summary_template = ["section", {"id":"summary"},
- ["h2", {}, "Summary"],
- ["p", {}, "Found ${num_tests} tests"],
- function(vars) {
- var rv = [["div", {}]];
- var i=0;
- while (status_text.hasOwnProperty(i)) {
- if (status_number.hasOwnProperty(status_text[i])) {
- var status = status_text[i];
- rv[0].push(["div", {"class":status_class(status)},
- ["label", {},
- ["input", {type:"checkbox", checked:"checked"}],
- status_number[status] + " " + status]]);
- }
- i++;
- }
- return rv;
- }];
-
- log.appendChild(render(summary_template, {num_tests:tests.length}, output_document));
-
- forEach(output_document.querySelectorAll("section#summary label"),
- function(element)
- {
- on_event(element, "click",
- function(e)
- {
- if (output_document.getElementById("results") === null)
- {
- e.preventDefault();
- return;
- }
- var result_class = element.parentNode.getAttribute("class");
- var style_element = output_document.querySelector("style#hide-" + result_class);
- var input_element = element.querySelector("input");
- if (!style_element && !input_element.checked) {
- style_element = output_document.createElementNS(xhtml_ns, "style");
- style_element.id = "hide-" + result_class;
- style_element.textContent = "table#results > tbody > tr."+result_class+"{display:none}";
- output_document.body.appendChild(style_element);
- } else if (style_element && input_element.checked) {
- style_element.parentNode.removeChild(style_element);
- }
- });
- });
-
- // This use of innerHTML plus manual escaping is not recommended in
- // general, but is necessary here for performance. Using textContent
- // on each individual <td> adds tens of seconds of execution time for
- // large test suites (tens of thousands of tests).
- function escape_html(s)
- {
- return s.replace(/\&/g, "&")
- .replace(/</g, "<")
- .replace(/"/g, """)
- .replace(/'/g, "'");
- }
-
- function has_assertions()
- {
- for (var i = 0; i < tests.length; i++) {
- if (tests[i].properties.hasOwnProperty("assert")) {
- return true;
- }
- }
- return false;
- }
-
- function get_assertion(test)
- {
- if (test.properties.hasOwnProperty("assert")) {
- if (Array.isArray(test.properties.assert)) {
- return test.properties.assert.join(' ');
- }
- return test.properties.assert;
- }
- return '';
- }
-
- log.appendChild(document.createElementNS(xhtml_ns, "section"));
- var assertions = has_assertions();
- var html = "<h2>Details</h2><table id='results' " + (assertions ? "class='assertions'" : "" ) + ">"
- + "<thead><tr><th>Result</th><th>Test Name</th>"
- + (assertions ? "<th>Assertion</th>" : "")
- + "<th>Message</th></tr></thead>"
- + "<tbody>";
- for (var i = 0; i < tests.length; i++) {
- html += '<tr class="'
- + escape_html(status_class(status_text[tests[i].status]))
- + '"><td>'
- + escape_html(status_text[tests[i].status])
- + "</td><td>"
- + escape_html(tests[i].name)
- + "</td><td>"
- + (assertions ? escape_html(get_assertion(tests[i])) + "</td><td>" : "")
- + escape_html(tests[i].message ? tests[i].message : " ")
- + "</td></tr>";
- }
- html += "</tbody></table>";
- try {
- log.lastChild.innerHTML = html;
- } catch (e) {
- log.appendChild(document.createElementNS(xhtml_ns, "p"))
- .textContent = "Setting innerHTML for the log threw an exception.";
- log.appendChild(document.createElementNS(xhtml_ns, "pre"))
- .textContent = html;
- }
- };
-
- var output = new Output();
- add_start_callback(function (properties) {output.init(properties);});
- add_result_callback(function (test) {output.show_status(tests);});
- add_completion_callback(function (tests, harness_status) {output.show_results(tests, harness_status);});
-
- /*
- * Template code
- *
- * A template is just a javascript structure. An element is represented as:
- *
- * [tag_name, {attr_name:attr_value}, child1, child2]
- *
- * the children can either be strings (which act like text nodes), other templates or
- * functions (see below)
- *
- * A text node is represented as
- *
- * ["{text}", value]
- *
- * String values have a simple substitution syntax; ${foo} represents a variable foo.
- *
- * It is possible to embed logic in templates by using a function in a place where a
- * node would usually go. The function must either return part of a template or null.
- *
- * In cases where a set of nodes are required as output rather than a single node
- * with children it is possible to just use a list
- * [node1, node2, node3]
- *
- * Usage:
- *
- * render(template, substitutions) - take a template and an object mapping
- * variable names to parameters and return either a DOM node or a list of DOM nodes
- *
- * substitute(template, substitutions) - take a template and variable mapping object,
- * make the variable substitutions and return the substituted template
- *
- */
-
- function is_single_node(template)
- {
- return typeof template[0] === "string";
- }
-
- function substitute(template, substitutions)
- {
- if (typeof template === "function") {
- var replacement = template(substitutions);
- if (replacement)
- {
- var rv = substitute(replacement, substitutions);
- return rv;
- }
- else
- {
- return null;
- }
- }
- else if (is_single_node(template))
- {
- return substitute_single(template, substitutions);
- }
- else
- {
- return filter(map(template, function(x) {
- return substitute(x, substitutions);
- }), function(x) {return x !== null;});
- }
- }
-
- function substitute_single(template, substitutions)
- {
- var substitution_re = /\${([^ }]*)}/g;
-
- function do_substitution(input) {
- var components = input.split(substitution_re);
- var rv = [];
- for (var i=0; i<components.length; i+=2)
- {
- rv.push(components[i]);
- if (components[i+1])
- {
- rv.push(String(substitutions[components[i+1]]));
- }
- }
- return rv;
- }
-
- var rv = [];
- rv.push(do_substitution(String(template[0])).join(""));
-
- if (template[0] === "{text}") {
- substitute_children(template.slice(1), rv);
- } else {
- substitute_attrs(template[1], rv);
- substitute_children(template.slice(2), rv);
- }
-
- function substitute_attrs(attrs, rv)
- {
- rv[1] = {};
- for (var name in template[1])
- {
- if (attrs.hasOwnProperty(name))
- {
- var new_name = do_substitution(name).join("");
- var new_value = do_substitution(attrs[name]).join("");
- rv[1][new_name] = new_value;
- };
- }
- }
-
- function substitute_children(children, rv)
- {
- for (var i=0; i<children.length; i++)
- {
- if (children[i] instanceof Object) {
- var replacement = substitute(children[i], substitutions);
- if (replacement !== null)
- {
- if (is_single_node(replacement))
- {
- rv.push(replacement);
- }
- else
- {
- extend(rv, replacement);
- }
- }
- }
- else
- {
- extend(rv, do_substitution(String(children[i])));
- }
- }
- return rv;
- }
-
- return rv;
- }
-
- function make_dom_single(template, doc)
- {
- var output_document = doc || document;
- if (template[0] === "{text}")
- {
- var element = output_document.createTextNode("");
- for (var i=1; i<template.length; i++)
- {
- element.data += template[i];
- }
- }
- else
- {
- var element = output_document.createElementNS(xhtml_ns, template[0]);
- for (var name in template[1]) {
- if (template[1].hasOwnProperty(name))
- {
- element.setAttribute(name, template[1][name]);
- }
- }
- for (var i=2; i<template.length; i++)
- {
- if (template[i] instanceof Object)
- {
- var sub_element = make_dom(template[i]);
- element.appendChild(sub_element);
- }
- else
- {
- var text_node = output_document.createTextNode(template[i]);
- element.appendChild(text_node);
- }
- }
- }
-
- return element;
- }
-
-
-
- function make_dom(template, substitutions, output_document)
- {
- if (is_single_node(template))
- {
- return make_dom_single(template, output_document);
- }
- else
- {
- return map(template, function(x) {
- return make_dom_single(x, output_document);
- });
- }
- }
-
- function render(template, substitutions, output_document)
- {
- return make_dom(substitute(template, substitutions), output_document);
- }
-
- /*
- * Utility funcions
- */
- function assert(expected_true, function_name, description, error, substitutions)
- {
- if (expected_true !== true)
- {
- throw new AssertionError(make_message(function_name, description,
- error, substitutions));
- }
- }
-
- function AssertionError(message)
- {
- this.message = message;
- }
-
- function make_message(function_name, description, error, substitutions)
- {
- for (var p in substitutions) {
- if (substitutions.hasOwnProperty(p)) {
- substitutions[p] = format_value(substitutions[p]);
- }
- }
- var node_form = substitute(["{text}", "${function_name}: ${description}" + error],
- merge({function_name:function_name,
- description:(description?description + " ":"")},
- substitutions));
- return node_form.slice(1).join("");
- }
-
- function filter(array, callable, thisObj) {
- var rv = [];
- for (var i=0; i<array.length; i++)
- {
- if (array.hasOwnProperty(i))
- {
- var pass = callable.call(thisObj, array[i], i, array);
- if (pass) {
- rv.push(array[i]);
- }
- }
- }
- return rv;
- }
-
- function map(array, callable, thisObj)
- {
- var rv = [];
- rv.length = array.length;
- for (var i=0; i<array.length; i++)
- {
- if (array.hasOwnProperty(i))
- {
- rv[i] = callable.call(thisObj, array[i], i, array);
- }
- }
- return rv;
- }
-
- function extend(array, items)
- {
- Array.prototype.push.apply(array, items);
- }
-
- function forEach (array, callback, thisObj)
- {
- for (var i=0; i<array.length; i++)
- {
- if (array.hasOwnProperty(i))
- {
- callback.call(thisObj, array[i], i, array);
- }
- }
- }
-
- function merge(a,b)
- {
- var rv = {};
- var p;
- for (p in a)
- {
- rv[p] = a[p];
- }
- for (p in b) {
- rv[p] = b[p];
- }
- return rv;
- }
-
- function expose(object, name)
- {
- var components = name.split(".");
- var target = window;
- for (var i=0; i<components.length - 1; i++)
- {
- if (!(components[i] in target))
- {
- target[components[i]] = {};
- }
- target = target[components[i]];
- }
- target[components[components.length - 1]] = object;
- }
-
- function forEach_windows(callback) {
- // Iterate of the the windows [self ... top, opener]. The callback is passed
- // two objects, the first one is the windows object itself, the second one
- // is a boolean indicating whether or not its on the same origin as the
- // current window.
- var cache = forEach_windows.result_cache;
- if (!cache) {
- cache = [[self, true]];
- var w = self;
- var i = 0;
- var so;
- var origins = location.ancestorOrigins;
- while (w != w.parent)
- {
- w = w.parent;
- // In WebKit, calls to parent windows' properties that aren't on the same
- // origin cause an error message to be displayed in the error console but
- // don't throw an exception. This is a deviation from the current HTML5
- // spec. See: https://bugs.webkit.org/show_bug.cgi?id=43504
- // The problem with WebKit's behavior is that it pollutes the error console
- // with error messages that can't be caught.
- //
- // This issue can be mitigated by relying on the (for now) proprietary
- // `location.ancestorOrigins` property which returns an ordered list of
- // the origins of enclosing windows. See:
- // https://trac.webkit.org/changeset/113945.
- if(origins) {
- so = (location.origin == origins[i]);
- }
- else
- {
- so = is_same_origin(w);
- }
- cache.push([w, so]);
- i++;
- }
- w = window.opener;
- if(w)
- {
- // window.opener isn't included in the `location.ancestorOrigins` prop.
- // We'll just have to deal with a simple check and an error msg on WebKit
- // browsers in this case.
- cache.push([w, is_same_origin(w)]);
- }
- forEach_windows.result_cache = cache;
- }
-
- forEach(cache,
- function(a)
- {
- callback.apply(null, a);
- });
- }
-
- function is_same_origin(w) {
- try {
- 'random_prop' in w;
- return true;
- } catch(e) {
- return false;
- }
- }
-
- function supports_post_message(w)
- {
- var supports;
- var type;
- // Given IE implements postMessage across nested iframes but not across
- // windows or tabs, you can't infer cross-origin communication from the presence
- // of postMessage on the current window object only.
- //
- // Touching the postMessage prop on a window can throw if the window is
- // not from the same origin AND post message is not supported in that
- // browser. So just doing an existence test here won't do, you also need
- // to wrap it in a try..cacth block.
- try
- {
- type = typeof w.postMessage;
- if (type === "function")
- {
- supports = true;
- }
- // IE8 supports postMessage, but implements it as a host object which
- // returns "object" as its `typeof`.
- else if (type === "object")
- {
- supports = true;
- }
- // This is the case where postMessage isn't supported AND accessing a
- // window property across origins does NOT throw (e.g. old Safari browser).
- else
- {
- supports = false;
- }
- }
- catch(e) {
- // This is the case where postMessage isn't supported AND accessing a
- // window property across origins throws (e.g. old Firefox browser).
- supports = false;
- }
- return supports;
- }
-})();
-// vim: set expandtab shiftwidth=4 tabstop=4:
diff --git a/test/testharnessreport.js b/test/testharnessreport.js
deleted file mode 100644
index fa73347..0000000
--- a/test/testharnessreport.js
+++ /dev/null
@@ -1,380 +0,0 @@
-/*
- * This file is intended for vendors to implement
- * code needed to integrate testharness.js tests with their own test systems.
- *
- * The default implementation extracts metadata from the tests and validates
- * it against the cached version that should be present in the test source
- * file. If the cache is not found or is out of sync, source code suitable for
- * caching the metadata is optionally generated.
- *
- * The cached metadata is present for extraction by test processing tools that
- * are unable to execute javascript.
- *
- * Metadata is attached to tests via the properties parameter in the test
- * constructor. See testharness.js for details.
- *
- * Typically test system integration will attach callbacks when each test has
- * run, using add_result_callback(callback(test)), or when the whole test file
- * has completed, using
- * add_completion_callback(callback(tests, harness_status)).
- *
- * For more documentation about the callback functions and the
- * parameters they are called with see testharness.js
- */
-
-
-
-var metadata_generator = {
-
- currentMetadata: {},
- cachedMetadata: false,
- metadataProperties: ['help', 'assert', 'author'],
-
- error: function(message) {
- var messageElement = document.createElement('p');
- messageElement.setAttribute('class', 'error');
- this.appendText(messageElement, message);
-
- var summary = document.getElementById('summary');
- if (summary) {
- summary.parentNode.insertBefore(messageElement, summary);
- }
- else {
- document.body.appendChild(messageElement);
- }
- },
-
- /**
- * Ensure property value has contact information
- */
- validateContact: function(test, propertyName) {
- var result = true;
- var value = test.properties[propertyName];
- var values = Array.isArray(value) ? value : [value];
- for (var index = 0; index < values.length; index++) {
- value = values[index];
- var re = /(\S+)(\s*)<(.*)>(.*)/;
- if (! re.test(value)) {
- re = /(\S+)(\s+)(http[s]?:\/\/)(.*)/
- if (! re.test(value)) {
- this.error('Metadata property "' + propertyName +
- '" for test: "' + test.name +
- '" must have name and contact information ' +
- '("name <email>" or "name http(s)://")');
- result = false;
- }
- }
- }
- return result;
- },
-
- /**
- * Extract metadata from test object
- */
- extractFromTest: function(test) {
- var testMetadata = {};
- // filter out metadata from other properties in test
- for (var metaIndex = 0; metaIndex < this.metadataProperties.length;
- metaIndex++) {
- var meta = this.metadataProperties[metaIndex];
- if (test.properties.hasOwnProperty(meta)) {
- if ('author' == meta) {
- this.validateContact(test, meta);
- }
- testMetadata[meta] = test.properties[meta];
- }
- }
- return testMetadata;
- },
-
- /**
- * Compare cached metadata to extracted metadata
- */
- validateCache: function() {
- for (var testName in this.currentMetadata) {
- if (! this.cachedMetadata.hasOwnProperty(testName)) {
- return false;
- }
- var testMetadata = this.currentMetadata[testName];
- var cachedTestMetadata = this.cachedMetadata[testName];
- delete this.cachedMetadata[testName];
-
- for (var metaIndex = 0; metaIndex < this.metadataProperties.length;
- metaIndex++) {
- var meta = this.metadataProperties[metaIndex];
- if (cachedTestMetadata.hasOwnProperty(meta) &&
- testMetadata.hasOwnProperty(meta)) {
- if (Array.isArray(cachedTestMetadata[meta])) {
- if (! Array.isArray(testMetadata[meta])) {
- return false;
- }
- if (cachedTestMetadata[meta].length ==
- testMetadata[meta].length) {
- for (var index = 0;
- index < cachedTestMetadata[meta].length;
- index++) {
- if (cachedTestMetadata[meta][index] !=
- testMetadata[meta][index]) {
- return false;
- }
- }
- }
- else {
- return false;
- }
- }
- else {
- if (Array.isArray(testMetadata[meta])) {
- return false;
- }
- if (cachedTestMetadata[meta] != testMetadata[meta]) {
- return false;
- }
- }
- }
- else if (cachedTestMetadata.hasOwnProperty(meta) ||
- testMetadata.hasOwnProperty(meta)) {
- return false;
- }
- }
- }
- for (var testName in this.cachedMetadata) {
- return false;
- }
- return true;
- },
-
- appendText: function(elemement, text) {
- elemement.appendChild(document.createTextNode(text));
- },
-
- jsonifyArray: function(arrayValue, indent) {
- var output = '[';
-
- if (1 == arrayValue.length) {
- output += JSON.stringify(arrayValue[0]);
- }
- else {
- for (var index = 0; index < arrayValue.length; index++) {
- if (0 < index) {
- output += ',\n ' + indent;
- }
- output += JSON.stringify(arrayValue[index]);
- }
- }
- output += ']';
- return output;
- },
-
- jsonifyObject: function(objectValue, indent) {
- var output = '{';
-
- var count = 0;
- for (var property in objectValue) {
- ++count;
- if (Array.isArray(objectValue[property]) ||
- ('object' == typeof(value))) {
- ++count;
- }
- }
- if (1 == count) {
- for (var property in objectValue) {
- output += ' "' + property + '": '
- + JSON.stringify(objectValue[property])
- + ' ';
- }
- }
- else {
- var first = true;
- for (var property in objectValue) {
- if (! first) {
- output += ',';
- }
- first = false;
- output += '\n ' + indent + '"' + property + '": ';
- var value = objectValue[property];
- if (Array.isArray(value)) {
- output += this.jsonifyArray(value, indent +
- ' '.substr(0, 5 + property.length));
- }
- else if ('object' == typeof(value)) {
- output += this.jsonifyObject(value, indent + ' ');
- }
- else {
- output += JSON.stringify(value);
- }
- }
- if (1 < output.length) {
- output += '\n' + indent;
- }
- }
- output += '}';
- return output;
- },
-
- /**
- * Generate javascript source code for captured metadata
- * Metadata is in pretty-printed JSON format
- */
- generateSource: function() {
- var source =
- '<script id="metadata_cache">/*\n' +
- this.jsonifyObject(this.currentMetadata, '') + '\n' +
- '*/</script>\n';
- return source;
- },
-
- /**
- * Add element containing metadata source code
- */
- addSourceElement: function(event) {
- var sourceWrapper = document.createElement('div');
- sourceWrapper.setAttribute('id', 'metadata_source');
-
- var instructions = document.createElement('p');
- if (this.cachedMetadata) {
- this.appendText(instructions,
- 'Replace the existing <script id="metadata_cache"> element ' +
- 'in the test\'s <head> with the following:');
- }
- else {
- this.appendText(instructions,
- 'Copy the following into the <head> element of the test ' +
- 'or the test\'s metadata sidecar file:');
- }
- sourceWrapper.appendChild(instructions);
-
- var sourceElement = document.createElement('pre');
- this.appendText(sourceElement, this.generateSource());
-
- sourceWrapper.appendChild(sourceElement);
-
- var messageElement = document.getElementById('metadata_issue');
- messageElement.parentNode.insertBefore(sourceWrapper,
- messageElement.nextSibling);
- messageElement.parentNode.removeChild(messageElement);
-
- (event.preventDefault) ? event.preventDefault() :
- event.returnValue = false;
- },
-
- /**
- * Extract the metadata cache from the cache element if present
- */
- getCachedMetadata: function() {
- var cacheElement = document.getElementById('metadata_cache');
-
- if (cacheElement) {
- var cacheText = cacheElement.firstChild.nodeValue;
- var openBrace = cacheText.indexOf('{');
- var closeBrace = cacheText.lastIndexOf('}');
- if ((-1 < openBrace) && (-1 < closeBrace)) {
- cacheText = cacheText.slice(openBrace, closeBrace + 1);
- try {
- this.cachedMetadata = JSON.parse(cacheText);
- }
- catch (exc) {
- this.cachedMetadata = 'Invalid JSON in Cached metadata. ';
- }
- }
- else {
- this.cachedMetadata = 'Metadata not found in cache element. ';
- }
- }
- },
-
- /**
- * Main entry point, extract metadata from tests, compare to cached version
- * if present.
- * If cache not present or differs from extrated metadata, generate an error
- */
- process: function(tests, harness_status) {
- for (var index = 0; index < tests.length; index++) {
- var test = tests[index];
- if (this.currentMetadata.hasOwnProperty(test.name)) {
- this.error('Duplicate test name: ' + test.name);
- }
- else {
- this.currentMetadata[test.name] = this.extractFromTest(test);
- }
- }
-
- this.getCachedMetadata();
-
- var message = null;
- var messageClass = 'warning';
- var showSource = false;
-
- if (0 == tests.length) {
- if (this.cachedMetadata) {
- message = 'Cached metadata present but no tests. ';
- }
- }
- else if (1 == tests.length) {
- if (this.cachedMetadata) {
- message = 'Single test files should not have cached metadata. ';
- }
- else {
- var testMetadata = this.currentMetadata[tests[0].name];
- var hasMetadata = false;
- for (var meta in testMetadata) {
- hasMetadata |= testMetadata.hasOwnProperty(meta);
- }
- if (hasMetadata) {
- message = 'Single tests should not have metadata. ' +
- 'Move metadata to <head>. ';
- }
- }
- }
- else {
- if (this.cachedMetadata) {
- messageClass = 'error';
- if ('string' == typeof(this.cachedMetadata)) {
- message = this.cachedMetadata;
- showSource = true;
- }
- else if (! this.validateCache()) {
- message = 'Cached metadata out of sync. ';
- showSource = true;
- }
- }
- }
-
- if (message) {
- var messageElement = document.createElement('p');
- messageElement.setAttribute('id', 'metadata_issue');
- messageElement.setAttribute('class', messageClass);
- this.appendText(messageElement, message);
-
- if (showSource) {
- var link = document.createElement('a');
- this.appendText(link, 'Click for source code.');
- link.setAttribute('href', '#');
- link.setAttribute('onclick',
- 'metadata_generator.addSourceElement(event)');
- messageElement.appendChild(link);
- }
-
- var summary = document.getElementById('summary');
- if (summary) {
- summary.parentNode.insertBefore(messageElement, summary);
- }
- else {
- var log = document.getElementById('log');
- if (log) {
- log.appendChild(messageElement);
- }
- }
- }
- },
-
- setup: function() {
- add_completion_callback(
- function (tests, harness_status) {
- metadata_generator.process(tests, harness_status)
- });
- }
-}
-
-metadata_generator.setup();
-// vim: set expandtab shiftwidth=4 tabstop=4:
diff --git a/test/tests.html b/test/tests.html
index 526351c..e964ecb 100644
--- a/test/tests.html
+++ b/test/tests.html
@@ -1,16 +1,15 @@
<!DOCTYPE HTML>
-<html>
-<head>
<title>Encoding API Tests</title>
-<link rel="stylesheet" href="testharness.css">
-</head>
-<body>
+<link rel="stylesheet" href="testharness.js/testharness.css">
<h1>Encoding API Tests</h1>
-<div id="log"></div>
-<script src="testharness.js"></script>
-<script src="testharnessreport.js"></script>
+<script src="testharness.js/testharness.js"></script>
+<script src="testharness.js/testharnessreport.js"></script>
<script>
setup({explicit_timeout: true});
+
+// Hide native implementation so polyfill will be used
+self.TextEncoder = null;
+self.TextDecoder = null;
</script>
<script src="../lib/encoding-indexes.js"></script>
@@ -27,5 +26,3 @@ setup({explicit_timeout: true});
<script src="test-shift_jis.js"></script>
<script src="test-euc-kr.js"></script>
<script src="test-x-user-defined.js"></script>
-</body>
-</html>
--
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-javascript/node-text-encoding.git
More information about the Pkg-javascript-commits
mailing list