[
  {
    "path": ".gitignore",
    "content": "/target\n**/*.rs.bk\nCargo.lock\nbin/\npkg/\nwasm-pack.log\n.vscode/\n"
  },
  {
    "path": "Cargo.toml",
    "content": "[package]\nname = \"blurhash-wasm\"\nversion = \"0.2.0\"\nauthors = [\"fpapado <fgpapado@gmail.com>\"]\nedition = \"2018\"\n\ndescription = \"A Rust and WASM implementation of the blurhash algorithm\"\nrepository = \"https://github.com/fpapado/blurhash-rust-wasm\"\nlicense = \"MIT\"\n\n[lib]\ncrate-type = [\"cdylib\", \"rlib\"]\n\n[features]\ndefault = [\"console_error_panic_hook\"]\n\n[dependencies]\nwasm-bindgen = \"0.2\"\njs-sys = \"0.3\"\nthiserror = \"1\"\n\n# The `console_error_panic_hook` crate provides better debugging of panics by\n# logging them with `console.error`. This is great for development, but requires\n# all the `std::fmt` and `std::panicking` infrastructure, so isn't great for\n# code size when deploying.\nconsole_error_panic_hook = { version = \"0.1.1\", optional = true }\n\n# `wee_alloc` is a tiny allocator for wasm that is only ~1K in code size\n# compared to the default allocator's ~10K. It is slower than the default\n# allocator, however.\n#\n# Unfortunately, `wee_alloc` requires nightly Rust when targeting wasm for now.\nwee_alloc = { version = \"0.4.2\", optional = true }\n\n[dev-dependencies]\nwasm-bindgen-test = \"0.2\"\nimage = \"0.22.0\"\n\n[profile.release]\n# Tell `rustc` to optimize for small code size.\n# When measuring, this didn't really change size much (it actually increased!).\n# For that reason, we've left it out for now.\n# opt-level = 's'\nlto = true\n"
  },
  {
    "path": "LICENSE.md",
    "content": "MIT License\n\nCopyright (c) 2019 Fotis Papadogeorgopoulos\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# blurhash-wasm\n\nA Rust implementation of the [blurhash algorithm](https://github.com/woltapp/blurhash).\n\nIt is compiled to WebAssembly (WASM), and [available on npm as `blurhash-wasm`](https://npmjs.com/blurhash-wasm).\n\nBlurHash is an algorithm written by [Dag Ågren](https://github.com/DagAgren) and folks at [Wolt (woltapp/blurhash)](https://github.com/woltapp/blurhash). BlurHash is \"a compact representation of a placeholder for an image.\" It enables you to store that representation in your database. It can then be transferred together with the initial data, in order to decode and show it, before the main image request has finished (or even started).\n\n[Online Demo](https://blurhash-wasm.netlify.com).\n\n## Usage in JS\n\n### Installation\n\nYou will need a package manager, either npm ([comes with node](https://nodejs.org/en/download/)) or [yarn](https://yarnpkg.com/lang/en/docs/install/).\n\nYou will also need a bundler, [webpack](https://webpack.js.org/) or [Rollup](https://rollupjs.org/guide/en/), configured for your project.\n\nThen, in a terminal:\n\n```shell\nnpm install blurhash-wasm\n# Or, yarn add blurhash-wasm\n```\n\nThe [demo app source](/demo) has a complete example of using `blurhash-wasm`.\n\n### decode\n\n```js\nimport * as blurhash from \"blurhash-wasm\";\n\n// You can use this to construct canvas-compatible resources\ntry {\n  const pixels = blurhash.decode(\"LKO2?U%2Tw=w]~RBVZRi};RPxuwH\", 40, 30);\n} catch (error) {\n  console.log(error);\n}\n```\n\n### encode\n\nImplented, aim to be published in 0.3.0\n\n## Usage in Rust\n\n### Installation\n\nYou will need [Rust and Cargo](https://doc.rust-lang.org/cargo/getting-started/installation.html).\n\nAdd the version you want to `Cargo.toml`:\n\n```\n[dependencies]\nblurhash-wasm = \"0.1.0\"\n```\n\n### decode\n\n```rust\nuse blurhash_wasm;\n\n// Result<Vec<u8>, blurhash::Error>\nlet res = blurhash::decode(\"LKO2?U%2Tw=w]~RBVZRi};RPxuwH\", 40, 30);\n```\n\n### encode\n\nImplented, aim to be published in 0.3.0\n\n## About the setup\n\n[**Based on the rust wasm-pack template**][template-docs]\n\nThis template is designed for compiling Rust libraries into WebAssembly and\npublishing the resulting package to NPM.\n\nBe sure to check out [other `wasm-pack` tutorials online][tutorials] for other\ntemplates and usages of `wasm-pack`.\n\n[tutorials]: https://rustwasm.github.io/docs/wasm-pack/tutorials/index.html\n[template-docs]: https://rustwasm.github.io/docs/wasm-pack/tutorials/npm-browser-packages/index.html\n\n## 🚴 Usage\n\n### 🛠️ Build with `wasm-pack build`\n\n```\nwasm-pack build\n```\n\n### 🔬 Test in Headless Browsers with `wasm-pack test`\n\n```\nwasm-pack test --headless --firefox\n```\n\n### 🎁 Publish to NPM with `wasm-pack publish`\n\n```\nwasm-pack publish\n```\n\n## 🔋 Batteries Included\n\n- [`wasm-bindgen`](https://github.com/rustwasm/wasm-bindgen) for communicating\n  between WebAssembly and JavaScript.\n- [`console_error_panic_hook`](https://github.com/rustwasm/console_error_panic_hook)\n  for logging panic messages to the developer console.\n- [`wee_alloc`](https://github.com/rustwasm/wee_alloc), an allocator optimized\n  for small code size.\n"
  },
  {
    "path": "build-wasm.sh",
    "content": "#!/bin/bash\n\n# The initial build\n# Set wee_alloc as a smaller allocator.\n# We do it here instead of Cargo.toml, to keep\n# the default allocator in the native Rust library build.\nwasm-pack build -- --features wee_alloc\n\necho \"Initial size\"\n\nwc -c pkg/blurhash_wasm_bg.wasm\n\n# Optimize wasm\n# NOTE: Again, setting -Os did not decrease the size,\n# so might as well optimise for speed.\n# You might need to install wasm-opt from binaryen:\n# https://github.com/WebAssembly/binaryen/releases\nwasm-opt pkg/blurhash_wasm_bg.wasm -O3 -o pkg/blurhash_wasm_bg.wasm\n\necho \"Size after wasm-opt\"\nwc -c pkg/blurhash_wasm_bg.wasm\n\necho \"Size after gzip\"\ngzip -9 < pkg/blurhash_wasm_bg.wasm | wc -c\n"
  },
  {
    "path": "demo/.babelrc",
    "content": "{\n  \"plugins\": [\n    [\"@babel/plugin-transform-react-jsx\", { \"pragma\":\"h\" }]\n  ]\n}\n"
  },
  {
    "path": "demo/.gitignore",
    "content": "node_modules\ndist\n"
  },
  {
    "path": "demo/.travis.yml",
    "content": "language: node_js\nnode_js: \"10\"\n\nscript:\n  - ./node_modules/.bin/webpack\n"
  },
  {
    "path": "demo/App.js",
    "content": "import * as blurhash from 'blurhash-wasm';\n\n// Using react/preact in this demo mostly for convenience and habit.\n// You can of course render blurhashes however you want!\nimport {h, Component} from 'preact';\nimport {useState, useRef, useEffect} from 'preact/hooks';\n\nexport function App(props) {\n  const {images} = props;\n  return (\n    <main className=\"pa3 vs4 mw8 center\">\n      <Pitch />\n      <div className=\"vs3\">\n        <h2 id=\"demo\">Demo</h2>\n        {images.map(image => (\n          <div className=\"mb5\">\n            <div className=\"mb3 mw6\">\n              <CustomImage image={image} key={image.id} />\n            </div>\n            <ImageCredit credit={image.credit} />\n          </div>\n        ))}\n      </div>\n    </main>\n  );\n}\n\nfunction CustomImage(props) {\n  const {src, alt, hash, ratio} = props.image;\n\n  // Hardcoded width/height for the decode and canvas\n  // We keep these low and let the UI scale them up\n  const WIDTH = 32; // pixels\n  const HEIGHT = 32; // pixels\n\n  const canvasRef = useRef(null);\n\n  // Cycle the opacity of the final image, for demo purposes\n  // (You could also do this with CSS animation keyframes :) )\n  const [opacity, setOpacity] = useState(-1);\n\n  useInterval(() => {\n    setOpacity(prevOpacity => prevOpacity * -1);\n  }, 2000);\n\n  // When the component mounts, set the image placeholder\n  useEffect(\n    () => {\n      // Decode the hash into pixels\n      try {\n        const pixels = blurhash.decode(hash, WIDTH, HEIGHT);\n        // Set the pixels to the canvas\n        const asClamped = new Uint8ClampedArray(pixels);\n        const imageData = new ImageData(asClamped, WIDTH, HEIGHT);\n\n        const canvasEl = canvasRef.current;\n\n        if (canvasEl) {\n          const ctx = canvasEl.getContext('2d');\n          ctx.putImageData(imageData, 0, 0);\n        }\n      } catch (error) {\n        console.error(error);\n      }\n    },\n    [hash]\n  );\n\n  // Layout notes:\n  // canvas goes below the img\n  // both canvas and img have a fixed aspect-ratio placeholder\n  // to preserve the layout size before either has loaded.\n  return (\n    <div>\n      <div className={`aspect-ratio aspect-ratio--${ratio}`}>\n        <canvas\n          ref={canvasRef}\n          width={WIDTH}\n          height={HEIGHT}\n          className=\"aspect-ratio--object\"\n        />\n        <img\n          src={src}\n          alt={alt}\n          className=\"aspect-ratio--object transition-opacity\"\n          style={{opacity: opacity}}\n        />\n      </div>\n    </div>\n  );\n}\n\nfunction ImageCredit(props) {\n  const {username, displayName} = props.credit;\n  return (\n    <p>\n      Photo by <a href={`https://unsplash.com/@${username}`}>{displayName}</a>{' '}\n      on <a href=\"https://unsplash.com\">Unsplash</a>\n    </p>\n  );\n}\n\nfunction Pitch() {\n  return (\n    <div className=\"vs4\">\n      <div>\n        <h1>Rust Wasm BlurHash</h1>\n        <a href=\"#demo\">Skip to Demo</a>\n        <p>\n          A Rust and WebAssembly implementation of the{' '}\n          <a href=\"https://blurha.sh\">BlurHash algorithm</a>.\n        </p>\n        <p>\n          BlurHash is \"a compact representation of a placeholder for an image.\"\n          It enables you to store that representation in your database. It can\n          then be transferred together with the initial data, in order to decode\n          and show it, before the main image request has finished (or even\n          started).\n        </p>\n        <p>\n          You can seamlessly use it in the browser through JS imports and\n          bundling.\n        </p>\n      </div>\n      <pre>\n        <code>{`npm install blurhash-wasm`}</code>\n      </pre>\n      <pre>\n        <code>\n          {`import * as blurhash from \"blurhash-wasm\";\n\n// You can use this to construct canvas-compatible resources\ntry {\n  const pixels = blurhash.decode(\"LKO2?U%2Tw=w]~RBVZRi};RPxuwH\", 40, 30);\n} catch (error) {\n  console.log(error);\n}`}\n        </code>\n      </pre>\n      <div className=\"vs3\">\n        <h2>Credits</h2>\n        <ul className=\"vs2\">\n          <li>\n            The Blurhash algorithm was originally written by{' '}\n            <a href=\"https://github.com/DagAgren\">Dag Ågren</a>. Implementations\n            are maintained by{' '}\n            <a href=\"https://github.com/woltapp/blurhash#authors\">\n              folks at Wolt and outside\n            </a>\n            .\n          </li>\n          <li>\n            blurhash-wasm is written by{' '}\n            <a href=\"https://twitter.com/isfotis\">\n              Fotis Papado&shy;georgo&shy;poulos\n            </a>\n            .\n          </li>\n        </ul>\n      </div>\n      <div className=\"vs3\">\n        <h2>Sources and installation</h2>\n        <ul className=\"vs2\">\n          <li>\n            <a href=\"https://github.com/fpapado/blurhash-rust-wasm\">\n              Source on Github\n            </a>\n          </li>\n          <li>\n            <a href=\"https://npmjs.com/blurhash-wasm\">Package on npm</a>\n          </li>\n          <li>\n            <a href=\"https://crates.io/crates/blurhash-wasm\">\n              Package on crates.io\n            </a>\n          </li>\n          <li>\n            <a href=\"https://github.com/fpapado/blurhash-rust-wasm/tree/master/demo\">\n              Source for this demo\n            </a>\n          </li>\n        </ul>\n      </div>\n    </div>\n  );\n}\n\n/**\n * Internal custom hook to periodically call a function\n * @see https://overreacted.io/making-setinterval-declarative-with-react-hooks/\n */\nfunction useInterval(callback, delay) {\n  const savedCallback = useRef();\n\n  // Remember the latest callback.\n  useEffect(\n    () => {\n      savedCallback.current = callback;\n    },\n    [callback]\n  );\n\n  // Set up the interval.\n  useEffect(\n    () => {\n      function tick() {\n        savedCallback.current();\n      }\n      if (delay !== null) {\n        let id = setInterval(tick, delay);\n        return () => clearInterval(id);\n      }\n    },\n    [delay]\n  );\n}\n"
  },
  {
    "path": "demo/LICENSE-APACHE",
    "content": "                              Apache License\n                        Version 2.0, January 2004\n                     http://www.apache.org/licenses/\n\nTERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n1. Definitions.\n\n   \"License\" shall mean the terms and conditions for use, reproduction,\n   and distribution as defined by Sections 1 through 9 of this document.\n\n   \"Licensor\" shall mean the copyright owner or entity authorized by\n   the copyright owner that is granting the License.\n\n   \"Legal Entity\" shall mean the union of the acting entity and all\n   other entities that control, are controlled by, or are under common\n   control with that entity. For the purposes of this definition,\n   \"control\" means (i) the power, direct or indirect, to cause the\n   direction or management of such entity, whether by contract or\n   otherwise, or (ii) ownership of fifty percent (50%) or more of the\n   outstanding shares, or (iii) beneficial ownership of such entity.\n\n   \"You\" (or \"Your\") shall mean an individual or Legal Entity\n   exercising permissions granted by this License.\n\n   \"Source\" form shall mean the preferred form for making modifications,\n   including but not limited to software source code, documentation\n   source, and configuration files.\n\n   \"Object\" form shall mean any form resulting from mechanical\n   transformation or translation of a Source form, including but\n   not limited to compiled object code, generated documentation,\n   and conversions to other media types.\n\n   \"Work\" shall mean the work of authorship, whether in Source or\n   Object form, made available under the License, as indicated by a\n   copyright notice that is included in or attached to the work\n   (an example is provided in the Appendix below).\n\n   \"Derivative Works\" shall mean any work, whether in Source or Object\n   form, that is based on (or derived from) the Work and for which the\n   editorial revisions, annotations, elaborations, or other modifications\n   represent, as a whole, an original work of authorship. For the purposes\n   of this License, Derivative Works shall not include works that remain\n   separable from, or merely link (or bind by name) to the interfaces of,\n   the Work and Derivative Works thereof.\n\n   \"Contribution\" shall mean any work of authorship, including\n   the original version of the Work and any modifications or additions\n   to that Work or Derivative Works thereof, that is intentionally\n   submitted to Licensor for inclusion in the Work by the copyright owner\n   or by an individual or Legal Entity authorized to submit on behalf of\n   the copyright owner. For the purposes of this definition, \"submitted\"\n   means any form of electronic, verbal, or written communication sent\n   to the Licensor or its representatives, including but not limited to\n   communication on electronic mailing lists, source code control systems,\n   and issue tracking systems that are managed by, or on behalf of, the\n   Licensor for the purpose of discussing and improving the Work, but\n   excluding communication that is conspicuously marked or otherwise\n   designated in writing by the copyright owner as \"Not a Contribution.\"\n\n   \"Contributor\" shall mean Licensor and any individual or Legal Entity\n   on behalf of whom a Contribution has been received by Licensor and\n   subsequently incorporated within the Work.\n\n2. Grant of Copyright License. Subject to the terms and conditions of\n   this License, each Contributor hereby grants to You a perpetual,\n   worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n   copyright license to reproduce, prepare Derivative Works of,\n   publicly display, publicly perform, sublicense, and distribute the\n   Work and such Derivative Works in Source or Object form.\n\n3. Grant of Patent License. Subject to the terms and conditions of\n   this License, each Contributor hereby grants to You a perpetual,\n   worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n   (except as stated in this section) patent license to make, have made,\n   use, offer to sell, sell, import, and otherwise transfer the Work,\n   where such license applies only to those patent claims licensable\n   by such Contributor that are necessarily infringed by their\n   Contribution(s) alone or by combination of their Contribution(s)\n   with the Work to which such Contribution(s) was submitted. If You\n   institute patent litigation against any entity (including a\n   cross-claim or counterclaim in a lawsuit) alleging that the Work\n   or a Contribution incorporated within the Work constitutes direct\n   or contributory patent infringement, then any patent licenses\n   granted to You under this License for that Work shall terminate\n   as of the date such litigation is filed.\n\n4. Redistribution. You may reproduce and distribute copies of the\n   Work or Derivative Works thereof in any medium, with or without\n   modifications, and in Source or Object form, provided that You\n   meet the following conditions:\n\n   (a) You must give any other recipients of the Work or\n       Derivative Works a copy of this License; and\n\n   (b) You must cause any modified files to carry prominent notices\n       stating that You changed the files; and\n\n   (c) You must retain, in the Source form of any Derivative Works\n       that You distribute, all copyright, patent, trademark, and\n       attribution notices from the Source form of the Work,\n       excluding those notices that do not pertain to any part of\n       the Derivative Works; and\n\n   (d) If the Work includes a \"NOTICE\" text file as part of its\n       distribution, then any Derivative Works that You distribute must\n       include a readable copy of the attribution notices contained\n       within such NOTICE file, excluding those notices that do not\n       pertain to any part of the Derivative Works, in at least one\n       of the following places: within a NOTICE text file distributed\n       as part of the Derivative Works; within the Source form or\n       documentation, if provided along with the Derivative Works; or,\n       within a display generated by the Derivative Works, if and\n       wherever such third-party notices normally appear. The contents\n       of the NOTICE file are for informational purposes only and\n       do not modify the License. You may add Your own attribution\n       notices within Derivative Works that You distribute, alongside\n       or as an addendum to the NOTICE text from the Work, provided\n       that such additional attribution notices cannot be construed\n       as modifying the License.\n\n   You may add Your own copyright statement to Your modifications and\n   may provide additional or different license terms and conditions\n   for use, reproduction, or distribution of Your modifications, or\n   for any such Derivative Works as a whole, provided Your use,\n   reproduction, and distribution of the Work otherwise complies with\n   the conditions stated in this License.\n\n5. Submission of Contributions. Unless You explicitly state otherwise,\n   any Contribution intentionally submitted for inclusion in the Work\n   by You to the Licensor shall be under the terms and conditions of\n   this License, without any additional terms or conditions.\n   Notwithstanding the above, nothing herein shall supersede or modify\n   the terms of any separate license agreement you may have executed\n   with Licensor regarding such Contributions.\n\n6. Trademarks. This License does not grant permission to use the trade\n   names, trademarks, service marks, or product names of the Licensor,\n   except as required for reasonable and customary use in describing the\n   origin of the Work and reproducing the content of the NOTICE file.\n\n7. Disclaimer of Warranty. Unless required by applicable law or\n   agreed to in writing, Licensor provides the Work (and each\n   Contributor provides its Contributions) on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n   implied, including, without limitation, any warranties or conditions\n   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n   PARTICULAR PURPOSE. You are solely responsible for determining the\n   appropriateness of using or redistributing the Work and assume any\n   risks associated with Your exercise of permissions under this License.\n\n8. Limitation of Liability. In no event and under no legal theory,\n   whether in tort (including negligence), contract, or otherwise,\n   unless required by applicable law (such as deliberate and grossly\n   negligent acts) or agreed to in writing, shall any Contributor be\n   liable to You for damages, including any direct, indirect, special,\n   incidental, or consequential damages of any character arising as a\n   result of this License or out of the use or inability to use the\n   Work (including but not limited to damages for loss of goodwill,\n   work stoppage, computer failure or malfunction, or any and all\n   other commercial damages or losses), even if such Contributor\n   has been advised of the possibility of such damages.\n\n9. Accepting Warranty or Additional Liability. While redistributing\n   the Work or Derivative Works thereof, You may choose to offer,\n   and charge a fee for, acceptance of support, warranty, indemnity,\n   or other liability obligations and/or rights consistent with this\n   License. However, in accepting such obligations, You may act only\n   on Your own behalf and on Your sole responsibility, not on behalf\n   of any other Contributor, and only if You agree to indemnify,\n   defend, and hold each Contributor harmless for any liability\n   incurred by, or claims asserted against, such Contributor by reason\n   of your accepting any such warranty or additional liability.\n\nEND OF TERMS AND CONDITIONS\n\nAPPENDIX: How to apply the Apache License to your work.\n\n   To apply the Apache License to your work, attach the following\n   boilerplate notice, with the fields enclosed by brackets \"[]\"\n   replaced with your own identifying information. (Don't include\n   the brackets!)  The text should be enclosed in the appropriate\n   comment syntax for the file format. We also recommend that a\n   file or class name and description of purpose be included on the\n   same \"printed page\" as the copyright notice for easier\n   identification within third-party archives.\n\nCopyright [yyyy] [name of copyright owner]\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n"
  },
  {
    "path": "demo/LICENSE-MIT",
    "content": "Copyright (c) [year] [name]\n\nPermission is hereby granted, free of charge, to any\nperson obtaining a copy of this software and associated\ndocumentation files (the \"Software\"), to deal in the\nSoftware without restriction, including without\nlimitation the rights to use, copy, modify, merge,\npublish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software\nis furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice\nshall be included in all copies or substantial portions\nof the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF\nANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED\nTO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\nSHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR\nIN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n"
  },
  {
    "path": "demo/README.md",
    "content": "<div align=\"center\">\n\n  <h1><code>create-wasm-app</code></h1>\n\n  <strong>An <code>npm init</code> template for kick starting a project that uses NPM packages containing Rust-generated WebAssembly and bundles them with Webpack.</strong>\n\n  <p>\n    <a href=\"https://travis-ci.org/rustwasm/create-wasm-app\"><img src=\"https://img.shields.io/travis/rustwasm/create-wasm-app.svg?style=flat-square\" alt=\"Build Status\" /></a>\n  </p>\n\n  <h3>\n    <a href=\"#usage\">Usage</a>\n    <span> | </span>\n    <a href=\"https://discordapp.com/channels/442252698964721669/443151097398296587\">Chat</a>\n  </h3>\n\n  <sub>Built with 🦀🕸 by <a href=\"https://rustwasm.github.io/\">The Rust and WebAssembly Working Group</a></sub>\n</div>\n\n## About\n\nThis template is designed for depending on NPM packages that contain\nRust-generated WebAssembly and using them to create a Website.\n\n* Want to create an NPM package with Rust and WebAssembly? [Check out\n  `wasm-pack-template`.](https://github.com/rustwasm/wasm-pack-template)\n* Want to make a monorepo-style Website without publishing to NPM? Check out\n  [`rust-webpack-template`](https://github.com/rustwasm/rust-webpack-template)\n  and/or\n  [`rust-parcel-template`](https://github.com/rustwasm/rust-parcel-template).\n\n## 🚴 Usage\n\n```\nnpm init wasm-app\n```\n\n## 🔋 Batteries Included\n\n- `.gitignore`: ignores `node_modules`\n- `LICENSE-APACHE` and `LICENSE-MIT`: most Rust projects are licensed this way, so these are included for you\n- `README.md`: the file you are reading now!\n- `index.html`: a bare bones html document that includes the webpack bundle\n- `index.js`: example js file with a comment showing how to import and use a wasm pkg\n- `package.json` and `package-lock.json`:\n  - pulls in devDependencies for using webpack:\n      - [`webpack`](https://www.npmjs.com/package/webpack)\n      - [`webpack-cli`](https://www.npmjs.com/package/webpack-cli)\n      - [`webpack-dev-server`](https://www.npmjs.com/package/webpack-dev-server)\n  - defines a `start` script to run `webpack-dev-server`\n- `webpack.config.js`: configuration file for bundling your js with webpack\n\n## License\n\nLicensed under either of\n\n* Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)\n* MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)\n\nat your option.\n\n### Contribution\n\nUnless you explicitly state otherwise, any contribution intentionally\nsubmitted for inclusion in the work by you, as defined in the Apache-2.0\nlicense, shall be dual licensed as above, without any additional terms or\nconditions.\n"
  },
  {
    "path": "demo/bootstrap.js",
    "content": "// A dependency graph that contains any wasm must all be imported\n// asynchronously. This `bootstrap.js` file does the single async import, so\n// that no one else needs to worry about it again.\nimport(\"./index.js\")\n  .catch(e => console.error(\"Error importing `index.js`:\", e));\n"
  },
  {
    "path": "demo/data.json",
    "content": "{\n  \"images\": [\n    {\n      \"id\": 1,\n      \"src\": \"/images/1.jpg\",\n      \"alt\": \"A mountain range in blue and pale purple colours.\",\n      \"hash\": \"LUDT3yayV?ay%jWBa#a}9Xj[j@fP\",\n      \"ratio\": \"4x6\",\n      \"credit\": { \"username\": \"eth_gaaar\", \"displayName\": \"Edgar Hernández\" }\n    },\n    {\n      \"id\": 2,\n      \"src\": \"/images/2.jpg\",\n      \"alt\": \"A panoramic view of white and blue roofs on a Greek island.\",\n      \"hash\": \"L3JkcZ^+00~V00009G0000R:%$4T\",\n      \"ratio\": \"4x6\",\n      \"credit\": {\n        \"username\": \"hellothisisbenjamin\",\n        \"displayName\": \"Benjamin Behre\"\n      }\n    },\n    {\n      \"id\": 3,\n      \"src\": \"/images/3.jpg\",\n      \"alt\": \"A row of coloured buildings, on a curved stret.\",\n      \"hash\": \"LFF$O@O,znM*~XNZ#+t8IUV@S5xu\",\n      \"ratio\": \"6x4\",\n      \"credit\": {\n        \"username\": \"jonathanricci\",\n        \"displayName\": \"Jonathan Ricci\"\n      }\n    }\n  ]\n}\n"
  },
  {
    "path": "demo/index.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en-US\" dir=\"ltr\">\n  <head>\n    <meta charset=\"utf-8\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n    <title>Rust Wasm Blurhash</title>\n\n    <style>\n      :root {\n        --blue: #1261C9;\n        --indigo: #1e12c9;\n        --indigo-darker: #1a10b4;\n      }\n      *:focus {\n        outline: 3px solid transparent;\n        box-shadow: 0 0 0 3px var(--indigo);\n      }\n      body {\n        hyphens: auto;\n        -webkit-hyphens: auto;\n        -moz-hyphens: auto;\n        -ms-hyphens: auto;\n      }\n      h1, h2 {\n        line-height: 1.25;\n      }\n      h2 {\n        margin-top: 0;\n        margin-bottom: 0;\n      }\n      p, li, h1, h2 {\n        max-width: 36em;\n      }\n      pre {\n        padding: 1rem;\n        overflow-x: auto;\n        -webkit-overflow-scroll: touch;\n        border-radius: 4px;\n        background-color: #eaeaef;\n        font-size: 1rem;\n      }\n      a:link, a:visited {\n        transition: color 0.12s ease;\n        color: var(--indigo);\n      }\n      a:hover, a:focus, a:active {\n        color: var(--indigo-darker);\n      }\n      a:focus {\n        text-decoration: none;\n      }\n      canvas {\n        display: block;\n      }\n      img {\n        display: block;\n        max-width: 100%;\n      }\n      .z-n1 {\n        z-index: -1;\n      }\n      .transition-opacity {\n        transition: opacity 1s ease-in-out;\n      }\n      .vs2 > * + * {\n        margin-top: 0.5rem;\n      }\n      .vs3 > * + * {\n        margin-top: 1rem;\n      }\n      .vs4 > * + * {\n        margin-top: 2rem;\n      }\n    </style>\n  </head>\n  <body class=\"f4 lh-copy sans-serif bg-near-white near-black\">\n    <div id=\"root\"></div>\n    <script src=\"./bootstrap.js\"></script>\n  </body>\n</html>\n"
  },
  {
    "path": "demo/index.js",
    "content": "import \"tachyons\"\nimport { App } from \"./App\";\nimport { render, h } from \"preact\";\n\n// You can imagine a similar data structure coming from your backend.\n// Note how the blurhash is included in the fields!\nimport data from \"./data.json\";\n\nfunction main() {\n  const root = document.getElementById(\"root\");\n  render(<App images={data.images} />, root);\n}\n\nmain();\n"
  },
  {
    "path": "demo/package.json",
    "content": "{\n  \"name\": \"blurhash-wasm-demo\",\n  \"version\": \"0.1.0\",\n  \"description\": \"A demo app for blurhash-wasm\",\n  \"main\": \"index.js\",\n  \"bin\": {\n    \"create-wasm-app\": \".bin/create-wasm-app.js\"\n  },\n  \"scripts\": {\n    \"build\": \"webpack --config webpack.config.js\",\n    \"start\": \"webpack-dev-server\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/rustwasm/create-wasm-app.git\"\n  },\n  \"keywords\": [\n    \"webassembly\",\n    \"wasm\",\n    \"rust\",\n    \"blurhash\"\n  ],\n  \"author\": \"Fotis Papadogeorgopoulos <fgpapado@gmail.com>\",\n  \"license\": \"(MIT OR Apache-2.0)\",\n  \"homepage\": \"https://github.com/fpapado/blurhash-rust-wasm\",\n  \"dependencies\": {\n    \"blurhash-wasm\": \"^0.2.0\",\n    \"preact\": \"^10.0.0-rc.0\",\n    \"tachyons\": \"^4.11.1\"\n  },\n  \"devDependencies\": {\n    \"@babel/core\": \"^7.5.5\",\n    \"@babel/plugin-transform-react-jsx\": \"^7.3.0\",\n    \"@babel/preset-env\": \"^7.5.5\",\n    \"babel-loader\": \"^8.0.6\",\n    \"copy-webpack-plugin\": \"^5.0.0\",\n    \"css-loader\": \"^3.1.0\",\n    \"hello-wasm-pack\": \"^0.1.0\",\n    \"mini-css-extract-plugin\": \"^0.8.0\",\n    \"webpack\": \"^4.29.3\",\n    \"webpack-cli\": \"^3.1.0\",\n    \"webpack-dev-server\": \"^3.1.5\"\n  }\n}\n"
  },
  {
    "path": "demo/webpack.config.js",
    "content": "const CopyWebpackPlugin = require(\"copy-webpack-plugin\");\nconst MiniCssExtractPlugin = require(\"mini-css-extract-plugin\");\nconst path = require(\"path\");\n\nmodule.exports = {\n  entry: \"./bootstrap.js\",\n  output: {\n    path: path.resolve(__dirname, \"dist\"),\n    filename: \"bootstrap.js\"\n  },\n  mode: \"development\",\n  plugins: [\n    new CopyWebpackPlugin([\"index.html\", \"public\"]),\n    new MiniCssExtractPlugin({\n      // Options similar to the same options in webpackOptions.output\n      // all options are optional\n      filename: \"[name].[contenthash].css\",\n      chunkFilename: \"[id].css\",\n      ignoreOrder: false // Enable to remove warnings about conflicting order\n    })\n  ],\n  module: {\n    rules: [\n      {\n        test: /\\.m?js$/,\n        exclude: /(node_modules|bower_components)/,\n        use: {\n          loader: \"babel-loader\",\n          options: {\n            presets: [\"@babel/preset-env\"],\n            plugins: [[\"@babel/plugin-transform-react-jsx\", { pragma: \"h\" }]]\n          }\n        }\n      },\n      {\n        test: /\\.css$/,\n        use: [\n          {\n            loader: MiniCssExtractPlugin.loader,\n            options: {\n              hmr: process.env.NODE_ENV === \"development\"\n            }\n          },\n          \"css-loader\"\n        ]\n      }\n    ]\n  }\n};\n"
  },
  {
    "path": "netlify.toml",
    "content": "# This file configures the headers and redirect rules for Netlify.\n# Some are important for the page to work correctly, and other\n# are for performance.\n# Reference: https://www.netlify.com/docs/netlify-toml-reference/\n\n# Global settings applied to the whole site.\n#\n# “base” is the directory to change to before starting build. If you set base:\n#        that is where we will look for package.json/.nvmrc/etc, not repo root!\n# “command” is your build command.\n# “publish” is the directory to publish (relative to the root of your repo).\n\n[build]\n  base    = \"demo\"\n  publish = \"demo/dist\"\n  command = \"npm run build\"\n\n# Redirects\n# Anything else, we redirect to index.html\n[[redirects]]\n  from = \"/*\"\n  to = \"/index.html\"\n  status = 200\n\n# Headers\n[[headers]]\n  # Anything under /static is hashed, so we can cache indefinitely\n  for = \"/static/*\"\n\n  [headers.values]\n    cache-control = '''\n    public,\n    max-age=31536000,\n    immutable'''\n\n[[headers]]\n  # Assets under images/ are mutable, but large-ish\n  # We cache them for a short time, to avoid excessive data consumption\n  for = \"/images/*\"\n\n  [headers.values]\n    cache-control =  '''\n    public,\n    max-age=600,\n    must-revalidate'''\n"
  },
  {
    "path": "src/lib.rs",
    "content": "mod utils;\n\nuse std::cmp::Ordering;\nuse std::convert::TryFrom;\nuse std::f64::consts::PI;\nuse thiserror::*;\nuse wasm_bindgen::prelude::*;\n\n// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global\n// allocator.\n#[cfg(feature = \"wee_alloc\")]\n#[global_allocator]\nstatic ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;\n\n// TODO: Add adjustable 'punch'\n// TODO: Avoid panicing infrasturcture (checked division, .get, no unwrap)\n\n#[derive(Clone, Copy, Debug, PartialEq, Eq, Error)]\npub enum Error {\n    #[error(\"the length of the hash is invalid\")]\n    LengthInvalid,\n    #[error(\"the specified number of components does not match the actual length\")]\n    LengthMismatch,\n}\n\n#[derive(Clone, Copy, Debug, PartialEq, Eq, Error)]\npub enum EncodingError {\n    #[error(\"cannot encode this number of components\")]\n    ComponentsNumberInvalid,\n    #[error(\"the bytes per pixel does not match the pixel count\")]\n    BytesPerPixelMismatch,\n}\n\n// Decode\n\n/// Decode for WASM target. If an error occurs, the function will throw a `JsError`.\n#[wasm_bindgen(js_name = \"decode\")]\npub fn wasm_decode(blur_hash: &str, width: usize, height: usize) -> Result<Vec<u8>, JsValue> {\n    decode(blur_hash, width, height).map_err(|err| js_sys::Error::new(&err.to_string()).into())\n}\n\npub fn decode(blur_hash: &str, width: usize, height: usize) -> Result<Vec<u8>, Error> {\n    if blur_hash.len() < 6 {\n        return Err(Error::LengthInvalid);\n    }\n\n    // 1. Number of components\n    // For a BlurHash with nx components along the X axis and ny components\n    // along the Y axis, this is equal to (nx - 1) + (ny - 1) * 9.\n    let size_flag = decode_base83_string(blur_hash.get(0..1).unwrap());\n\n    let num_y = (size_flag / 9) + 1;\n    let num_x = (size_flag % 9) + 1;\n\n    // Validate that the number of digits is what we expect:\n    // 1 (size flag) + 1 (maximum value) + 4 (average colour) + (num_x - num_y - 1) components * 2 digits each\n    let expected_digits = 4 + 2 * num_x * num_y;\n\n    if blur_hash.len() != expected_digits {\n        return Err(Error::LengthMismatch);\n    }\n\n    // 2. Maximum AC component value, 1 digit.\n    // All AC components are scaled by this value.\n    // It represents a floating-point value of (max + 1) / 166.\n    let quantised_maximum_value = decode_base83_string(blur_hash.get(1..2).unwrap());\n    let maximum_value = ((quantised_maximum_value + 1) as f64) / 166f64;\n\n    let mut colours: Vec<[f64; 3]> = Vec::with_capacity(num_x * num_y);\n\n    for i in 0..(num_x * num_y) {\n        if i == 0 {\n            // 3. Average colour, 4 digits.\n            let value = decode_base83_string(blur_hash.get(2..6).unwrap());\n            colours.push(decode_dc(value));\n        } else {\n            // 4. AC components, 2 digits each, nx * ny - 1 components in total.\n            let value = decode_base83_string(blur_hash.get((4 + i * 2)..(4 + i * 2 + 2)).unwrap());\n            colours.push(decode_ac(value, maximum_value * 1.0));\n        }\n    }\n\n    // Now, construct the image\n    // NOTE: We include an alpha channel of 255 as well, because it is more convenient,\n    // for various representations (browser canvas, for example).\n    // This could probably be configured\n    let bytes_per_row = width * 4;\n\n    let mut pixels = vec![0; bytes_per_row * height];\n\n    for y in 0..height {\n        for x in 0..width {\n            let mut r = 0f64;\n            let mut g = 0f64;\n            let mut b = 0f64;\n\n            for j in 0..num_y {\n                for i in 0..num_x {\n                    let basis = f64::cos(PI * (x as f64) * (i as f64) / (width as f64))\n                        * f64::cos(PI * (y as f64) * (j as f64) / (height as f64));\n                    let colour = colours[i + j * num_x];\n                    r += colour[0] * basis;\n                    g += colour[1] * basis;\n                    b += colour[2] * basis;\n                }\n            }\n\n            let int_r = linear_to_srgb(r);\n            let int_g = linear_to_srgb(g);\n            let int_b = linear_to_srgb(b);\n\n            pixels[4 * x + y * bytes_per_row] = int_r as u8;\n            pixels[4 * x + 1 + y * bytes_per_row] = int_g as u8;\n            pixels[4 * x + 2 + y * bytes_per_row] = int_b as u8;\n            pixels[4 * x + 3 + y * bytes_per_row] = 255 as u8;\n        }\n    }\n\n    Ok(pixels)\n}\n\nfn decode_dc(value: usize) -> [f64; 3] {\n    let int_r = value >> 16;\n    let int_g = (value >> 8) & 255;\n    let int_b = value & 255;\n    [\n        srgb_to_linear(int_r),\n        srgb_to_linear(int_g),\n        srgb_to_linear(int_b),\n    ]\n}\n\nfn decode_ac(value: usize, maximum_value: f64) -> [f64; 3] {\n    let quant_r = f64::floor((value / (19 * 19)) as f64);\n    let quant_g = f64::floor(((value / 19) as f64) % 19f64);\n    let quant_b = (value as f64) % 19f64;\n    [\n        sign_pow((quant_r - 9f64) / 9f64, 2f64) * maximum_value,\n        sign_pow((quant_g - 9f64) / 9f64, 2f64) * maximum_value,\n        sign_pow((quant_b - 9f64) / 9f64, 2f64) * maximum_value,\n    ]\n}\n\nfn sign_pow(value: f64, exp: f64) -> f64 {\n    value.abs().powf(exp).copysign(value)\n}\n\nfn linear_to_srgb(value: f64) -> usize {\n    let v = f64::max(0f64, f64::min(1f64, value));\n    if v <= 0.003_130_8 {\n        (v * 12.92 * 255f64 + 0.5) as usize\n    } else {\n        ((1.055 * f64::powf(v, 1f64 / 2.4) - 0.055) * 255f64 + 0.5) as usize\n    }\n}\n\nfn srgb_to_linear(value: usize) -> f64 {\n    let v = (value as f64) / 255f64;\n    if v <= 0.04045 {\n        v / 12.92\n    } else {\n        ((v + 0.055) / 1.055).powf(2.4)\n    }\n}\n\n// Encode\n\n// TODO: Think about argument order here...\n// What is more common in Rust? Data or config first?\npub fn encode(\n    pixels: Vec<u8>,\n    cx: usize,\n    cy: usize,\n    width: usize,\n    height: usize,\n) -> Result<String, EncodingError> {\n    // Should we assume RGBA for round-trips? Or does it not matter?\n    let bytes_per_row = width * 4;\n    let bytes_per_pixel = 4;\n\n    // NOTE: We could clamp instead of Err.\n    // The TS version does that. Not sure which one is better.\n    // We also could (should?) be checking for the color space\n    if cx < 1 || cx > 9 || cy < 1 || cy > 9 {\n        return Err(EncodingError::ComponentsNumberInvalid);\n    }\n\n    if width * height * 4 != pixels.len() {\n        return Err(EncodingError::BytesPerPixelMismatch);\n    }\n\n    let mut dc: [f64; 3] = [0., 0., 0.];\n    let mut ac: Vec<[f64; 3]> = Vec::with_capacity(cy * cx - 1);\n\n    for y in 0..cy {\n        for x in 0..cx {\n            let normalisation = if x == 0 && y == 0 { 1f64 } else { 2f64 };\n            let factor = multiply_basis_function(\n                &pixels,\n                width,\n                height,\n                bytes_per_row,\n                bytes_per_pixel,\n                0,\n                |a, b| {\n                    (normalisation\n                        * f64::cos((PI * x as f64 * a) / width as f64)\n                        * f64::cos((PI * y as f64 * b) / height as f64))\n                },\n            );\n\n            if x == 0 && y == 0 {\n                // The first iteration is the dc\n                dc = factor;\n            } else {\n                // All others are the ac\n                ac.push(factor);\n            }\n        }\n    }\n\n    let mut hash = String::new();\n\n    let size_flag = ((cx - 1) + (cy - 1) * 9) as usize;\n    hash += &encode_base83_string(size_flag, 1);\n\n    let maximum_value: f64;\n\n    if !ac.is_empty() {\n        // I'm sure there's a better way to write this; following the Swift atm :)\n        let actual_maximum_value = ac\n            .clone()\n            .into_iter()\n            .map(|[a, b, c]| f64::max(f64::max(f64::abs(a), f64::abs(b)), f64::abs(c)))\n            .max_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal))\n            .unwrap();\n        let quantised_maximum_value = usize::max(\n            0,\n            usize::min(82, f64::floor(actual_maximum_value * 166f64 - 0.5) as usize),\n        );\n        maximum_value = ((quantised_maximum_value + 1) as f64) / 166f64;\n        hash += &encode_base83_string(quantised_maximum_value, 1);\n    } else {\n        maximum_value = 1f64;\n        hash += &encode_base83_string(0, 1);\n    }\n\n    hash += &encode_base83_string(encode_dc(dc), 4);\n\n    for factor in ac {\n        hash += &encode_base83_string(encode_ac(factor, maximum_value), 2);\n    }\n\n    Ok(hash)\n}\n\nfn multiply_basis_function<F>(\n    pixels: &[u8],\n    width: usize,\n    height: usize,\n    bytes_per_row: usize,\n    bytes_per_pixel: usize,\n    pixel_offset: usize,\n    basis_function: F,\n) -> [f64; 3]\nwhere\n    F: Fn(f64, f64) -> f64,\n{\n    let mut r = 0f64;\n    let mut g = 0f64;\n    let mut b = 0f64;\n\n    for x in 0..width {\n        for y in 0..height {\n            let basis = basis_function(x as f64, y as f64);\n            r += basis\n                * srgb_to_linear(\n                    usize::try_from(pixels[bytes_per_pixel * x + pixel_offset + y * bytes_per_row])\n                        .unwrap(),\n                );\n            g += basis\n                * srgb_to_linear(\n                    usize::try_from(\n                        pixels[bytes_per_pixel * x + pixel_offset + 1 + y * bytes_per_row],\n                    )\n                    .unwrap(),\n                );\n            b += basis\n                * srgb_to_linear(\n                    usize::try_from(\n                        pixels[bytes_per_pixel * x + pixel_offset + 2 + y * bytes_per_row],\n                    )\n                    .unwrap(),\n                );\n        }\n    }\n\n    let scale = 1f64 / ((width * height) as f64);\n\n    [r * scale, g * scale, b * scale]\n}\n\nfn encode_dc(value: [f64; 3]) -> usize {\n    let rounded_r = linear_to_srgb(value[0]);\n    let rounded_g = linear_to_srgb(value[1]);\n    let rounded_b = linear_to_srgb(value[2]);\n    ((rounded_r << 16) + (rounded_g << 8) + rounded_b) as usize\n}\n\nfn encode_ac(value: [f64; 3], maximum_value: f64) -> usize {\n    let quant_r = f64::floor(f64::max(\n        0f64,\n        f64::min(\n            18f64,\n            f64::floor(sign_pow(value[0] / maximum_value, 0.5) * 9f64 + 9.5),\n        ),\n    ));\n    let quant_g = f64::floor(f64::max(\n        0f64,\n        f64::min(\n            18f64,\n            f64::floor(sign_pow(value[1] / maximum_value, 0.5) * 9f64 + 9.5),\n        ),\n    ));\n    let quant_b = f64::floor(f64::max(\n        0f64,\n        f64::min(\n            18f64,\n            f64::floor(sign_pow(value[2] / maximum_value, 0.5) * 9f64 + 9.5),\n        ),\n    ));\n\n    (quant_r * 19f64 * 19f64 + quant_g * 19f64 + quant_b) as usize\n}\n\n// Base83\n\n// I considered using lazy_static! for this, but other implementations\n// seem to hard-code these as well. Doing that for consistency.\nstatic ENCODE_CHARACTERS: [char; 83] = [\n    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',\n    'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b',\n    'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',\n    'v', 'w', 'x', 'y', 'z', '#', '$', '%', '*', '+', ',', '-', '.', ':', ';', '=', '?', '@', '[',\n    ']', '^', '_', '{', '|', '}', '~',\n];\n\nfn decode_base83_string(string: &str) -> usize {\n    string\n        .chars()\n        .filter_map(|character| ENCODE_CHARACTERS.iter().position(|&c| c == character))\n        .fold(0, |value, digit| value * 83 + digit)\n}\n\nfn encode_base83_string(value: usize, length: u32) -> String {\n    (1..=length)\n        .map(|i| (value / usize::pow(83, length - i)) % 83)\n        .map(|digit| ENCODE_CHARACTERS[digit])\n        .collect()\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    #[test]\n    fn it_decodes_size_flag() {\n        assert_eq!(21, decode_base83_string(\"L\"));\n        assert_eq!(0, decode_base83_string(\"0\"));\n    }\n    #[test]\n    fn decodes_size_0_out_of_range() {\n        let res = decode_base83_string(\"/\");\n        assert_eq!(\n            0, res,\n            \"Did not expect to decode size for input out of range (expected 0), but got {}\",\n            res\n        );\n    }\n}\n"
  },
  {
    "path": "src/utils.rs",
    "content": "pub fn set_panic_hook() {\n    // When the `console_error_panic_hook` feature is enabled, we can call the\n    // `set_panic_hook` function at least once during initialization, and then\n    // we will get better error messages if our code ever panics.\n    //\n    // For more details see\n    // https://github.com/rustwasm/console_error_panic_hook#readme\n    #[cfg(feature = \"console_error_panic_hook\")]\n    console_error_panic_hook::set_once();\n}\n"
  },
  {
    "path": "tests/integration_test.rs",
    "content": "use blurhash_wasm::{decode, encode};\nuse image;\nuse std::convert::TryFrom;\n\n#[test]\nfn err_if_hash_length_less_than_6() {\n    assert_eq!(\n        Err(blurhash_wasm::Error::LengthInvalid),\n        decode(\"L\", 40, 30)\n    );\n}\n\n#[test]\nfn decodes_ok() {\n    // From the online demo\n    let res = decode(\"LUDT3yayV?ay%jWBa#a}9Xj[j@fP\", 40, 30);\n\n    // From a known encode/decode\n    let expected = image::open(\"tests/data/decode-test-expected.png\")\n        .unwrap()\n        .to_rgba();\n\n    match res {\n        Ok(img) => {\n            // image::save_buffer(\"decode-test-out.png\", &img, 40, 30, image::RGBA(8));\n            assert_eq!(expected.to_vec(), img);\n        }\n\n        Err(_err) => assert!(false),\n    }\n}\n\n#[test]\nfn encodes_ok() {\n    // From a known encode/decode\n    let input = image::open(\"tests/data/encode-test-input.jpg\")\n        .unwrap()\n        .to_rgba();\n    let (width, height) = input.dimensions();\n\n    // From the online demo\n    // let expected = \"LKO2?U%2Tw=w]~RBVZRi};RPxuwH\";\n\n    // From our encoding, not sure why they differ\n    let expected = \"LKO2?V%2Tw=^]~RBVZRi};RPxuwH\";\n\n    let res = encode(\n        input.into_vec(),\n        4,\n        3,\n        usize::try_from(width).unwrap(),\n        usize::try_from(height).unwrap(),\n    );\n\n    match res {\n        Ok(actual) => {\n            assert_eq!(expected, actual);\n        }\n\n        Err(_err) => assert!(false),\n    }\n}\n\n#[test]\nfn encodes_ok_2() {\n    // From a known encode/decode\n    let input = image::open(\"tests/data/encode-test-input-2.jpg\")\n        .unwrap()\n        .to_rgba();\n    let (width, height) = input.dimensions();\n\n    // From the online demo\n    // let expected = \"LGF5]+Yk^6#M@-5c,1J5@[or[Q6.\";\n\n    // From our encoding\n    // Again, weird mismatch\n    let expected = \"LGFFaXYk^6#M@-5c,1Ex@@or[j6o\";\n\n    let res = encode(\n        input.into_vec(),\n        4,\n        3,\n        usize::try_from(width).unwrap(),\n        usize::try_from(height).unwrap(),\n    );\n\n    match res {\n        Ok(actual) => {\n            assert_eq!(expected, actual);\n        }\n\n        Err(_err) => assert!(false),\n    }\n}\n\n#[test]\nfn round_trips_ok() {\n    // From a known encode/decode\n    let input = image::open(\"tests/data/encode-test-input.jpg\")\n        .unwrap()\n        .to_rgba();\n    let (width, height) = input.dimensions();\n\n    // From the online demo\n    // let expected = \"LKO2?U%2Tw=w]~RBVZRi};RPxuwH\";\n\n    // From our encoding, not sure why they differ\n    let expected_encode = \"LKO2?V%2Tw=^]~RBVZRi};RPxuwH\";\n\n    let encode_res = encode(\n        input.into_vec(),\n        4,\n        3,\n        usize::try_from(width).unwrap(),\n        usize::try_from(height).unwrap(),\n    );\n\n    match encode_res {\n        Ok(actual_encode) => {\n            assert_eq!(expected_encode, actual_encode);\n            let expected_decode = image::open(\"tests/data/roundtrip-test-input-decode.png\")\n                .unwrap()\n                .to_rgba();\n\n            let decode_res = decode(&actual_encode, 32, 32);\n\n            match decode_res {\n                Ok(actual_decode) => {\n                    assert_eq!(expected_decode.to_vec(), actual_decode);\n                }\n\n                Err(_err) => assert!(false),\n            }\n        }\n\n        Err(_err) => assert!(false),\n    }\n}\n"
  },
  {
    "path": "tests/web.rs",
    "content": "//! Test suite for the Web and headless browsers.\n\n#![cfg(target_arch = \"wasm32\")]\n\nextern crate wasm_bindgen_test;\nuse wasm_bindgen_test::*;\n\nwasm_bindgen_test_configure!(run_in_browser);\n\n#[wasm_bindgen_test]\nfn pass() {\n    assert_eq!(1 + 1, 2);\n}\n"
  }
]