Repository: fpapado/blurhash-rust-wasm
Branch: master
Commit: a81e33c46a10
Files: 23
Total size: 48.5 KB
Directory structure:
gitextract_tzlsaf77/
├── .gitignore
├── Cargo.toml
├── LICENSE.md
├── README.md
├── build-wasm.sh
├── demo/
│ ├── .babelrc
│ ├── .gitignore
│ ├── .travis.yml
│ ├── App.js
│ ├── LICENSE-APACHE
│ ├── LICENSE-MIT
│ ├── README.md
│ ├── bootstrap.js
│ ├── data.json
│ ├── index.html
│ ├── index.js
│ ├── package.json
│ └── webpack.config.js
├── netlify.toml
├── src/
│ ├── lib.rs
│ └── utils.rs
└── tests/
├── integration_test.rs
└── web.rs
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
/target
**/*.rs.bk
Cargo.lock
bin/
pkg/
wasm-pack.log
.vscode/
================================================
FILE: Cargo.toml
================================================
[package]
name = "blurhash-wasm"
version = "0.2.0"
authors = ["fpapado <fgpapado@gmail.com>"]
edition = "2018"
description = "A Rust and WASM implementation of the blurhash algorithm"
repository = "https://github.com/fpapado/blurhash-rust-wasm"
license = "MIT"
[lib]
crate-type = ["cdylib", "rlib"]
[features]
default = ["console_error_panic_hook"]
[dependencies]
wasm-bindgen = "0.2"
js-sys = "0.3"
thiserror = "1"
# The `console_error_panic_hook` crate provides better debugging of panics by
# logging them with `console.error`. This is great for development, but requires
# all the `std::fmt` and `std::panicking` infrastructure, so isn't great for
# code size when deploying.
console_error_panic_hook = { version = "0.1.1", optional = true }
# `wee_alloc` is a tiny allocator for wasm that is only ~1K in code size
# compared to the default allocator's ~10K. It is slower than the default
# allocator, however.
#
# Unfortunately, `wee_alloc` requires nightly Rust when targeting wasm for now.
wee_alloc = { version = "0.4.2", optional = true }
[dev-dependencies]
wasm-bindgen-test = "0.2"
image = "0.22.0"
[profile.release]
# Tell `rustc` to optimize for small code size.
# When measuring, this didn't really change size much (it actually increased!).
# For that reason, we've left it out for now.
# opt-level = 's'
lto = true
================================================
FILE: LICENSE.md
================================================
MIT License
Copyright (c) 2019 Fotis Papadogeorgopoulos
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
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 OR COPYRIGHT HOLDERS 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.
================================================
FILE: README.md
================================================
# blurhash-wasm
A Rust implementation of the [blurhash algorithm](https://github.com/woltapp/blurhash).
It is compiled to WebAssembly (WASM), and [available on npm as `blurhash-wasm`](https://npmjs.com/blurhash-wasm).
BlurHash 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).
[Online Demo](https://blurhash-wasm.netlify.com).
## Usage in JS
### Installation
You will need a package manager, either npm ([comes with node](https://nodejs.org/en/download/)) or [yarn](https://yarnpkg.com/lang/en/docs/install/).
You will also need a bundler, [webpack](https://webpack.js.org/) or [Rollup](https://rollupjs.org/guide/en/), configured for your project.
Then, in a terminal:
```shell
npm install blurhash-wasm
# Or, yarn add blurhash-wasm
```
The [demo app source](/demo) has a complete example of using `blurhash-wasm`.
### decode
```js
import * as blurhash from "blurhash-wasm";
// You can use this to construct canvas-compatible resources
try {
const pixels = blurhash.decode("LKO2?U%2Tw=w]~RBVZRi};RPxuwH", 40, 30);
} catch (error) {
console.log(error);
}
```
### encode
Implented, aim to be published in 0.3.0
## Usage in Rust
### Installation
You will need [Rust and Cargo](https://doc.rust-lang.org/cargo/getting-started/installation.html).
Add the version you want to `Cargo.toml`:
```
[dependencies]
blurhash-wasm = "0.1.0"
```
### decode
```rust
use blurhash_wasm;
// Result<Vec<u8>, blurhash::Error>
let res = blurhash::decode("LKO2?U%2Tw=w]~RBVZRi};RPxuwH", 40, 30);
```
### encode
Implented, aim to be published in 0.3.0
## About the setup
[**Based on the rust wasm-pack template**][template-docs]
This template is designed for compiling Rust libraries into WebAssembly and
publishing the resulting package to NPM.
Be sure to check out [other `wasm-pack` tutorials online][tutorials] for other
templates and usages of `wasm-pack`.
[tutorials]: https://rustwasm.github.io/docs/wasm-pack/tutorials/index.html
[template-docs]: https://rustwasm.github.io/docs/wasm-pack/tutorials/npm-browser-packages/index.html
## 🚴 Usage
### 🛠️ Build with `wasm-pack build`
```
wasm-pack build
```
### 🔬 Test in Headless Browsers with `wasm-pack test`
```
wasm-pack test --headless --firefox
```
### 🎁 Publish to NPM with `wasm-pack publish`
```
wasm-pack publish
```
## 🔋 Batteries Included
- [`wasm-bindgen`](https://github.com/rustwasm/wasm-bindgen) for communicating
between WebAssembly and JavaScript.
- [`console_error_panic_hook`](https://github.com/rustwasm/console_error_panic_hook)
for logging panic messages to the developer console.
- [`wee_alloc`](https://github.com/rustwasm/wee_alloc), an allocator optimized
for small code size.
================================================
FILE: build-wasm.sh
================================================
#!/bin/bash
# The initial build
# Set wee_alloc as a smaller allocator.
# We do it here instead of Cargo.toml, to keep
# the default allocator in the native Rust library build.
wasm-pack build -- --features wee_alloc
echo "Initial size"
wc -c pkg/blurhash_wasm_bg.wasm
# Optimize wasm
# NOTE: Again, setting -Os did not decrease the size,
# so might as well optimise for speed.
# You might need to install wasm-opt from binaryen:
# https://github.com/WebAssembly/binaryen/releases
wasm-opt pkg/blurhash_wasm_bg.wasm -O3 -o pkg/blurhash_wasm_bg.wasm
echo "Size after wasm-opt"
wc -c pkg/blurhash_wasm_bg.wasm
echo "Size after gzip"
gzip -9 < pkg/blurhash_wasm_bg.wasm | wc -c
================================================
FILE: demo/.babelrc
================================================
{
"plugins": [
["@babel/plugin-transform-react-jsx", { "pragma":"h" }]
]
}
================================================
FILE: demo/.gitignore
================================================
node_modules
dist
================================================
FILE: demo/.travis.yml
================================================
language: node_js
node_js: "10"
script:
- ./node_modules/.bin/webpack
================================================
FILE: demo/App.js
================================================
import * as blurhash from 'blurhash-wasm';
// Using react/preact in this demo mostly for convenience and habit.
// You can of course render blurhashes however you want!
import {h, Component} from 'preact';
import {useState, useRef, useEffect} from 'preact/hooks';
export function App(props) {
const {images} = props;
return (
<main className="pa3 vs4 mw8 center">
<Pitch />
<div className="vs3">
<h2 id="demo">Demo</h2>
{images.map(image => (
<div className="mb5">
<div className="mb3 mw6">
<CustomImage image={image} key={image.id} />
</div>
<ImageCredit credit={image.credit} />
</div>
))}
</div>
</main>
);
}
function CustomImage(props) {
const {src, alt, hash, ratio} = props.image;
// Hardcoded width/height for the decode and canvas
// We keep these low and let the UI scale them up
const WIDTH = 32; // pixels
const HEIGHT = 32; // pixels
const canvasRef = useRef(null);
// Cycle the opacity of the final image, for demo purposes
// (You could also do this with CSS animation keyframes :) )
const [opacity, setOpacity] = useState(-1);
useInterval(() => {
setOpacity(prevOpacity => prevOpacity * -1);
}, 2000);
// When the component mounts, set the image placeholder
useEffect(
() => {
// Decode the hash into pixels
try {
const pixels = blurhash.decode(hash, WIDTH, HEIGHT);
// Set the pixels to the canvas
const asClamped = new Uint8ClampedArray(pixels);
const imageData = new ImageData(asClamped, WIDTH, HEIGHT);
const canvasEl = canvasRef.current;
if (canvasEl) {
const ctx = canvasEl.getContext('2d');
ctx.putImageData(imageData, 0, 0);
}
} catch (error) {
console.error(error);
}
},
[hash]
);
// Layout notes:
// canvas goes below the img
// both canvas and img have a fixed aspect-ratio placeholder
// to preserve the layout size before either has loaded.
return (
<div>
<div className={`aspect-ratio aspect-ratio--${ratio}`}>
<canvas
ref={canvasRef}
width={WIDTH}
height={HEIGHT}
className="aspect-ratio--object"
/>
<img
src={src}
alt={alt}
className="aspect-ratio--object transition-opacity"
style={{opacity: opacity}}
/>
</div>
</div>
);
}
function ImageCredit(props) {
const {username, displayName} = props.credit;
return (
<p>
Photo by <a href={`https://unsplash.com/@${username}`}>{displayName}</a>{' '}
on <a href="https://unsplash.com">Unsplash</a>
</p>
);
}
function Pitch() {
return (
<div className="vs4">
<div>
<h1>Rust Wasm BlurHash</h1>
<a href="#demo">Skip to Demo</a>
<p>
A Rust and WebAssembly implementation of the{' '}
<a href="https://blurha.sh">BlurHash algorithm</a>.
</p>
<p>
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).
</p>
<p>
You can seamlessly use it in the browser through JS imports and
bundling.
</p>
</div>
<pre>
<code>{`npm install blurhash-wasm`}</code>
</pre>
<pre>
<code>
{`import * as blurhash from "blurhash-wasm";
// You can use this to construct canvas-compatible resources
try {
const pixels = blurhash.decode("LKO2?U%2Tw=w]~RBVZRi};RPxuwH", 40, 30);
} catch (error) {
console.log(error);
}`}
</code>
</pre>
<div className="vs3">
<h2>Credits</h2>
<ul className="vs2">
<li>
The Blurhash algorithm was originally written by{' '}
<a href="https://github.com/DagAgren">Dag Ågren</a>. Implementations
are maintained by{' '}
<a href="https://github.com/woltapp/blurhash#authors">
folks at Wolt and outside
</a>
.
</li>
<li>
blurhash-wasm is written by{' '}
<a href="https://twitter.com/isfotis">
Fotis Papado­georgo­poulos
</a>
.
</li>
</ul>
</div>
<div className="vs3">
<h2>Sources and installation</h2>
<ul className="vs2">
<li>
<a href="https://github.com/fpapado/blurhash-rust-wasm">
Source on Github
</a>
</li>
<li>
<a href="https://npmjs.com/blurhash-wasm">Package on npm</a>
</li>
<li>
<a href="https://crates.io/crates/blurhash-wasm">
Package on crates.io
</a>
</li>
<li>
<a href="https://github.com/fpapado/blurhash-rust-wasm/tree/master/demo">
Source for this demo
</a>
</li>
</ul>
</div>
</div>
);
}
/**
* Internal custom hook to periodically call a function
* @see https://overreacted.io/making-setinterval-declarative-with-react-hooks/
*/
function useInterval(callback, delay) {
const savedCallback = useRef();
// Remember the latest callback.
useEffect(
() => {
savedCallback.current = callback;
},
[callback]
);
// Set up the interval.
useEffect(
() => {
function tick() {
savedCallback.current();
}
if (delay !== null) {
let id = setInterval(tick, delay);
return () => clearInterval(id);
}
},
[delay]
);
}
================================================
FILE: demo/LICENSE-APACHE
================================================
Apache License
Version 2.0, January 2004
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.
================================================
FILE: demo/LICENSE-MIT
================================================
Copyright (c) [year] [name]
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
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 OR COPYRIGHT HOLDERS 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.
================================================
FILE: demo/README.md
================================================
<div align="center">
<h1><code>create-wasm-app</code></h1>
<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>
<p>
<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>
</p>
<h3>
<a href="#usage">Usage</a>
<span> | </span>
<a href="https://discordapp.com/channels/442252698964721669/443151097398296587">Chat</a>
</h3>
<sub>Built with 🦀🕸 by <a href="https://rustwasm.github.io/">The Rust and WebAssembly Working Group</a></sub>
</div>
## About
This template is designed for depending on NPM packages that contain
Rust-generated WebAssembly and using them to create a Website.
* Want to create an NPM package with Rust and WebAssembly? [Check out
`wasm-pack-template`.](https://github.com/rustwasm/wasm-pack-template)
* Want to make a monorepo-style Website without publishing to NPM? Check out
[`rust-webpack-template`](https://github.com/rustwasm/rust-webpack-template)
and/or
[`rust-parcel-template`](https://github.com/rustwasm/rust-parcel-template).
## 🚴 Usage
```
npm init wasm-app
```
## 🔋 Batteries Included
- `.gitignore`: ignores `node_modules`
- `LICENSE-APACHE` and `LICENSE-MIT`: most Rust projects are licensed this way, so these are included for you
- `README.md`: the file you are reading now!
- `index.html`: a bare bones html document that includes the webpack bundle
- `index.js`: example js file with a comment showing how to import and use a wasm pkg
- `package.json` and `package-lock.json`:
- pulls in devDependencies for using webpack:
- [`webpack`](https://www.npmjs.com/package/webpack)
- [`webpack-cli`](https://www.npmjs.com/package/webpack-cli)
- [`webpack-dev-server`](https://www.npmjs.com/package/webpack-dev-server)
- defines a `start` script to run `webpack-dev-server`
- `webpack.config.js`: configuration file for bundling your js with webpack
## License
Licensed under either of
* Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
* MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
at your option.
### Contribution
Unless you explicitly state otherwise, any contribution intentionally
submitted for inclusion in the work by you, as defined in the Apache-2.0
license, shall be dual licensed as above, without any additional terms or
conditions.
================================================
FILE: demo/bootstrap.js
================================================
// A dependency graph that contains any wasm must all be imported
// asynchronously. This `bootstrap.js` file does the single async import, so
// that no one else needs to worry about it again.
import("./index.js")
.catch(e => console.error("Error importing `index.js`:", e));
================================================
FILE: demo/data.json
================================================
{
"images": [
{
"id": 1,
"src": "/images/1.jpg",
"alt": "A mountain range in blue and pale purple colours.",
"hash": "LUDT3yayV?ay%jWBa#a}9Xj[j@fP",
"ratio": "4x6",
"credit": { "username": "eth_gaaar", "displayName": "Edgar Hernández" }
},
{
"id": 2,
"src": "/images/2.jpg",
"alt": "A panoramic view of white and blue roofs on a Greek island.",
"hash": "L3JkcZ^+00~V00009G0000R:%$4T",
"ratio": "4x6",
"credit": {
"username": "hellothisisbenjamin",
"displayName": "Benjamin Behre"
}
},
{
"id": 3,
"src": "/images/3.jpg",
"alt": "A row of coloured buildings, on a curved stret.",
"hash": "LFF$O@O,znM*~XNZ#+t8IUV@S5xu",
"ratio": "6x4",
"credit": {
"username": "jonathanricci",
"displayName": "Jonathan Ricci"
}
}
]
}
================================================
FILE: demo/index.html
================================================
<!DOCTYPE html>
<html lang="en-US" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Rust Wasm Blurhash</title>
<style>
:root {
--blue: #1261C9;
--indigo: #1e12c9;
--indigo-darker: #1a10b4;
}
*:focus {
outline: 3px solid transparent;
box-shadow: 0 0 0 3px var(--indigo);
}
body {
hyphens: auto;
-webkit-hyphens: auto;
-moz-hyphens: auto;
-ms-hyphens: auto;
}
h1, h2 {
line-height: 1.25;
}
h2 {
margin-top: 0;
margin-bottom: 0;
}
p, li, h1, h2 {
max-width: 36em;
}
pre {
padding: 1rem;
overflow-x: auto;
-webkit-overflow-scroll: touch;
border-radius: 4px;
background-color: #eaeaef;
font-size: 1rem;
}
a:link, a:visited {
transition: color 0.12s ease;
color: var(--indigo);
}
a:hover, a:focus, a:active {
color: var(--indigo-darker);
}
a:focus {
text-decoration: none;
}
canvas {
display: block;
}
img {
display: block;
max-width: 100%;
}
.z-n1 {
z-index: -1;
}
.transition-opacity {
transition: opacity 1s ease-in-out;
}
.vs2 > * + * {
margin-top: 0.5rem;
}
.vs3 > * + * {
margin-top: 1rem;
}
.vs4 > * + * {
margin-top: 2rem;
}
</style>
</head>
<body class="f4 lh-copy sans-serif bg-near-white near-black">
<div id="root"></div>
<script src="./bootstrap.js"></script>
</body>
</html>
================================================
FILE: demo/index.js
================================================
import "tachyons"
import { App } from "./App";
import { render, h } from "preact";
// You can imagine a similar data structure coming from your backend.
// Note how the blurhash is included in the fields!
import data from "./data.json";
function main() {
const root = document.getElementById("root");
render(<App images={data.images} />, root);
}
main();
================================================
FILE: demo/package.json
================================================
{
"name": "blurhash-wasm-demo",
"version": "0.1.0",
"description": "A demo app for blurhash-wasm",
"main": "index.js",
"bin": {
"create-wasm-app": ".bin/create-wasm-app.js"
},
"scripts": {
"build": "webpack --config webpack.config.js",
"start": "webpack-dev-server"
},
"repository": {
"type": "git",
"url": "git+https://github.com/rustwasm/create-wasm-app.git"
},
"keywords": [
"webassembly",
"wasm",
"rust",
"blurhash"
],
"author": "Fotis Papadogeorgopoulos <fgpapado@gmail.com>",
"license": "(MIT OR Apache-2.0)",
"homepage": "https://github.com/fpapado/blurhash-rust-wasm",
"dependencies": {
"blurhash-wasm": "^0.2.0",
"preact": "^10.0.0-rc.0",
"tachyons": "^4.11.1"
},
"devDependencies": {
"@babel/core": "^7.5.5",
"@babel/plugin-transform-react-jsx": "^7.3.0",
"@babel/preset-env": "^7.5.5",
"babel-loader": "^8.0.6",
"copy-webpack-plugin": "^5.0.0",
"css-loader": "^3.1.0",
"hello-wasm-pack": "^0.1.0",
"mini-css-extract-plugin": "^0.8.0",
"webpack": "^4.29.3",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.5"
}
}
================================================
FILE: demo/webpack.config.js
================================================
const CopyWebpackPlugin = require("copy-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const path = require("path");
module.exports = {
entry: "./bootstrap.js",
output: {
path: path.resolve(__dirname, "dist"),
filename: "bootstrap.js"
},
mode: "development",
plugins: [
new CopyWebpackPlugin(["index.html", "public"]),
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// all options are optional
filename: "[name].[contenthash].css",
chunkFilename: "[id].css",
ignoreOrder: false // Enable to remove warnings about conflicting order
})
],
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: "babel-loader",
options: {
presets: ["@babel/preset-env"],
plugins: [["@babel/plugin-transform-react-jsx", { pragma: "h" }]]
}
}
},
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: process.env.NODE_ENV === "development"
}
},
"css-loader"
]
}
]
}
};
================================================
FILE: netlify.toml
================================================
# This file configures the headers and redirect rules for Netlify.
# Some are important for the page to work correctly, and other
# are for performance.
# Reference: https://www.netlify.com/docs/netlify-toml-reference/
# Global settings applied to the whole site.
#
# “base” is the directory to change to before starting build. If you set base:
# that is where we will look for package.json/.nvmrc/etc, not repo root!
# “command” is your build command.
# “publish” is the directory to publish (relative to the root of your repo).
[build]
base = "demo"
publish = "demo/dist"
command = "npm run build"
# Redirects
# Anything else, we redirect to index.html
[[redirects]]
from = "/*"
to = "/index.html"
status = 200
# Headers
[[headers]]
# Anything under /static is hashed, so we can cache indefinitely
for = "/static/*"
[headers.values]
cache-control = '''
public,
max-age=31536000,
immutable'''
[[headers]]
# Assets under images/ are mutable, but large-ish
# We cache them for a short time, to avoid excessive data consumption
for = "/images/*"
[headers.values]
cache-control = '''
public,
max-age=600,
must-revalidate'''
================================================
FILE: src/lib.rs
================================================
mod utils;
use std::cmp::Ordering;
use std::convert::TryFrom;
use std::f64::consts::PI;
use thiserror::*;
use wasm_bindgen::prelude::*;
// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
// TODO: Add adjustable 'punch'
// TODO: Avoid panicing infrasturcture (checked division, .get, no unwrap)
#[derive(Clone, Copy, Debug, PartialEq, Eq, Error)]
pub enum Error {
#[error("the length of the hash is invalid")]
LengthInvalid,
#[error("the specified number of components does not match the actual length")]
LengthMismatch,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Error)]
pub enum EncodingError {
#[error("cannot encode this number of components")]
ComponentsNumberInvalid,
#[error("the bytes per pixel does not match the pixel count")]
BytesPerPixelMismatch,
}
// Decode
/// Decode for WASM target. If an error occurs, the function will throw a `JsError`.
#[wasm_bindgen(js_name = "decode")]
pub fn wasm_decode(blur_hash: &str, width: usize, height: usize) -> Result<Vec<u8>, JsValue> {
decode(blur_hash, width, height).map_err(|err| js_sys::Error::new(&err.to_string()).into())
}
pub fn decode(blur_hash: &str, width: usize, height: usize) -> Result<Vec<u8>, Error> {
if blur_hash.len() < 6 {
return Err(Error::LengthInvalid);
}
// 1. Number of components
// For a BlurHash with nx components along the X axis and ny components
// along the Y axis, this is equal to (nx - 1) + (ny - 1) * 9.
let size_flag = decode_base83_string(blur_hash.get(0..1).unwrap());
let num_y = (size_flag / 9) + 1;
let num_x = (size_flag % 9) + 1;
// Validate that the number of digits is what we expect:
// 1 (size flag) + 1 (maximum value) + 4 (average colour) + (num_x - num_y - 1) components * 2 digits each
let expected_digits = 4 + 2 * num_x * num_y;
if blur_hash.len() != expected_digits {
return Err(Error::LengthMismatch);
}
// 2. Maximum AC component value, 1 digit.
// All AC components are scaled by this value.
// It represents a floating-point value of (max + 1) / 166.
let quantised_maximum_value = decode_base83_string(blur_hash.get(1..2).unwrap());
let maximum_value = ((quantised_maximum_value + 1) as f64) / 166f64;
let mut colours: Vec<[f64; 3]> = Vec::with_capacity(num_x * num_y);
for i in 0..(num_x * num_y) {
if i == 0 {
// 3. Average colour, 4 digits.
let value = decode_base83_string(blur_hash.get(2..6).unwrap());
colours.push(decode_dc(value));
} else {
// 4. AC components, 2 digits each, nx * ny - 1 components in total.
let value = decode_base83_string(blur_hash.get((4 + i * 2)..(4 + i * 2 + 2)).unwrap());
colours.push(decode_ac(value, maximum_value * 1.0));
}
}
// Now, construct the image
// NOTE: We include an alpha channel of 255 as well, because it is more convenient,
// for various representations (browser canvas, for example).
// This could probably be configured
let bytes_per_row = width * 4;
let mut pixels = vec![0; bytes_per_row * height];
for y in 0..height {
for x in 0..width {
let mut r = 0f64;
let mut g = 0f64;
let mut b = 0f64;
for j in 0..num_y {
for i in 0..num_x {
let basis = f64::cos(PI * (x as f64) * (i as f64) / (width as f64))
* f64::cos(PI * (y as f64) * (j as f64) / (height as f64));
let colour = colours[i + j * num_x];
r += colour[0] * basis;
g += colour[1] * basis;
b += colour[2] * basis;
}
}
let int_r = linear_to_srgb(r);
let int_g = linear_to_srgb(g);
let int_b = linear_to_srgb(b);
pixels[4 * x + y * bytes_per_row] = int_r as u8;
pixels[4 * x + 1 + y * bytes_per_row] = int_g as u8;
pixels[4 * x + 2 + y * bytes_per_row] = int_b as u8;
pixels[4 * x + 3 + y * bytes_per_row] = 255 as u8;
}
}
Ok(pixels)
}
fn decode_dc(value: usize) -> [f64; 3] {
let int_r = value >> 16;
let int_g = (value >> 8) & 255;
let int_b = value & 255;
[
srgb_to_linear(int_r),
srgb_to_linear(int_g),
srgb_to_linear(int_b),
]
}
fn decode_ac(value: usize, maximum_value: f64) -> [f64; 3] {
let quant_r = f64::floor((value / (19 * 19)) as f64);
let quant_g = f64::floor(((value / 19) as f64) % 19f64);
let quant_b = (value as f64) % 19f64;
[
sign_pow((quant_r - 9f64) / 9f64, 2f64) * maximum_value,
sign_pow((quant_g - 9f64) / 9f64, 2f64) * maximum_value,
sign_pow((quant_b - 9f64) / 9f64, 2f64) * maximum_value,
]
}
fn sign_pow(value: f64, exp: f64) -> f64 {
value.abs().powf(exp).copysign(value)
}
fn linear_to_srgb(value: f64) -> usize {
let v = f64::max(0f64, f64::min(1f64, value));
if v <= 0.003_130_8 {
(v * 12.92 * 255f64 + 0.5) as usize
} else {
((1.055 * f64::powf(v, 1f64 / 2.4) - 0.055) * 255f64 + 0.5) as usize
}
}
fn srgb_to_linear(value: usize) -> f64 {
let v = (value as f64) / 255f64;
if v <= 0.04045 {
v / 12.92
} else {
((v + 0.055) / 1.055).powf(2.4)
}
}
// Encode
// TODO: Think about argument order here...
// What is more common in Rust? Data or config first?
pub fn encode(
pixels: Vec<u8>,
cx: usize,
cy: usize,
width: usize,
height: usize,
) -> Result<String, EncodingError> {
// Should we assume RGBA for round-trips? Or does it not matter?
let bytes_per_row = width * 4;
let bytes_per_pixel = 4;
// NOTE: We could clamp instead of Err.
// The TS version does that. Not sure which one is better.
// We also could (should?) be checking for the color space
if cx < 1 || cx > 9 || cy < 1 || cy > 9 {
return Err(EncodingError::ComponentsNumberInvalid);
}
if width * height * 4 != pixels.len() {
return Err(EncodingError::BytesPerPixelMismatch);
}
let mut dc: [f64; 3] = [0., 0., 0.];
let mut ac: Vec<[f64; 3]> = Vec::with_capacity(cy * cx - 1);
for y in 0..cy {
for x in 0..cx {
let normalisation = if x == 0 && y == 0 { 1f64 } else { 2f64 };
let factor = multiply_basis_function(
&pixels,
width,
height,
bytes_per_row,
bytes_per_pixel,
0,
|a, b| {
(normalisation
* f64::cos((PI * x as f64 * a) / width as f64)
* f64::cos((PI * y as f64 * b) / height as f64))
},
);
if x == 0 && y == 0 {
// The first iteration is the dc
dc = factor;
} else {
// All others are the ac
ac.push(factor);
}
}
}
let mut hash = String::new();
let size_flag = ((cx - 1) + (cy - 1) * 9) as usize;
hash += &encode_base83_string(size_flag, 1);
let maximum_value: f64;
if !ac.is_empty() {
// I'm sure there's a better way to write this; following the Swift atm :)
let actual_maximum_value = ac
.clone()
.into_iter()
.map(|[a, b, c]| f64::max(f64::max(f64::abs(a), f64::abs(b)), f64::abs(c)))
.max_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal))
.unwrap();
let quantised_maximum_value = usize::max(
0,
usize::min(82, f64::floor(actual_maximum_value * 166f64 - 0.5) as usize),
);
maximum_value = ((quantised_maximum_value + 1) as f64) / 166f64;
hash += &encode_base83_string(quantised_maximum_value, 1);
} else {
maximum_value = 1f64;
hash += &encode_base83_string(0, 1);
}
hash += &encode_base83_string(encode_dc(dc), 4);
for factor in ac {
hash += &encode_base83_string(encode_ac(factor, maximum_value), 2);
}
Ok(hash)
}
fn multiply_basis_function<F>(
pixels: &[u8],
width: usize,
height: usize,
bytes_per_row: usize,
bytes_per_pixel: usize,
pixel_offset: usize,
basis_function: F,
) -> [f64; 3]
where
F: Fn(f64, f64) -> f64,
{
let mut r = 0f64;
let mut g = 0f64;
let mut b = 0f64;
for x in 0..width {
for y in 0..height {
let basis = basis_function(x as f64, y as f64);
r += basis
* srgb_to_linear(
usize::try_from(pixels[bytes_per_pixel * x + pixel_offset + y * bytes_per_row])
.unwrap(),
);
g += basis
* srgb_to_linear(
usize::try_from(
pixels[bytes_per_pixel * x + pixel_offset + 1 + y * bytes_per_row],
)
.unwrap(),
);
b += basis
* srgb_to_linear(
usize::try_from(
pixels[bytes_per_pixel * x + pixel_offset + 2 + y * bytes_per_row],
)
.unwrap(),
);
}
}
let scale = 1f64 / ((width * height) as f64);
[r * scale, g * scale, b * scale]
}
fn encode_dc(value: [f64; 3]) -> usize {
let rounded_r = linear_to_srgb(value[0]);
let rounded_g = linear_to_srgb(value[1]);
let rounded_b = linear_to_srgb(value[2]);
((rounded_r << 16) + (rounded_g << 8) + rounded_b) as usize
}
fn encode_ac(value: [f64; 3], maximum_value: f64) -> usize {
let quant_r = f64::floor(f64::max(
0f64,
f64::min(
18f64,
f64::floor(sign_pow(value[0] / maximum_value, 0.5) * 9f64 + 9.5),
),
));
let quant_g = f64::floor(f64::max(
0f64,
f64::min(
18f64,
f64::floor(sign_pow(value[1] / maximum_value, 0.5) * 9f64 + 9.5),
),
));
let quant_b = f64::floor(f64::max(
0f64,
f64::min(
18f64,
f64::floor(sign_pow(value[2] / maximum_value, 0.5) * 9f64 + 9.5),
),
));
(quant_r * 19f64 * 19f64 + quant_g * 19f64 + quant_b) as usize
}
// Base83
// I considered using lazy_static! for this, but other implementations
// seem to hard-code these as well. Doing that for consistency.
static ENCODE_CHARACTERS: [char; 83] = [
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b',
'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
'v', 'w', 'x', 'y', 'z', '#', '$', '%', '*', '+', ',', '-', '.', ':', ';', '=', '?', '@', '[',
']', '^', '_', '{', '|', '}', '~',
];
fn decode_base83_string(string: &str) -> usize {
string
.chars()
.filter_map(|character| ENCODE_CHARACTERS.iter().position(|&c| c == character))
.fold(0, |value, digit| value * 83 + digit)
}
fn encode_base83_string(value: usize, length: u32) -> String {
(1..=length)
.map(|i| (value / usize::pow(83, length - i)) % 83)
.map(|digit| ENCODE_CHARACTERS[digit])
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_decodes_size_flag() {
assert_eq!(21, decode_base83_string("L"));
assert_eq!(0, decode_base83_string("0"));
}
#[test]
fn decodes_size_0_out_of_range() {
let res = decode_base83_string("/");
assert_eq!(
0, res,
"Did not expect to decode size for input out of range (expected 0), but got {}",
res
);
}
}
================================================
FILE: src/utils.rs
================================================
pub fn set_panic_hook() {
// When the `console_error_panic_hook` feature is enabled, we can call the
// `set_panic_hook` function at least once during initialization, and then
// we will get better error messages if our code ever panics.
//
// For more details see
// https://github.com/rustwasm/console_error_panic_hook#readme
#[cfg(feature = "console_error_panic_hook")]
console_error_panic_hook::set_once();
}
================================================
FILE: tests/integration_test.rs
================================================
use blurhash_wasm::{decode, encode};
use image;
use std::convert::TryFrom;
#[test]
fn err_if_hash_length_less_than_6() {
assert_eq!(
Err(blurhash_wasm::Error::LengthInvalid),
decode("L", 40, 30)
);
}
#[test]
fn decodes_ok() {
// From the online demo
let res = decode("LUDT3yayV?ay%jWBa#a}9Xj[j@fP", 40, 30);
// From a known encode/decode
let expected = image::open("tests/data/decode-test-expected.png")
.unwrap()
.to_rgba();
match res {
Ok(img) => {
// image::save_buffer("decode-test-out.png", &img, 40, 30, image::RGBA(8));
assert_eq!(expected.to_vec(), img);
}
Err(_err) => assert!(false),
}
}
#[test]
fn encodes_ok() {
// From a known encode/decode
let input = image::open("tests/data/encode-test-input.jpg")
.unwrap()
.to_rgba();
let (width, height) = input.dimensions();
// From the online demo
// let expected = "LKO2?U%2Tw=w]~RBVZRi};RPxuwH";
// From our encoding, not sure why they differ
let expected = "LKO2?V%2Tw=^]~RBVZRi};RPxuwH";
let res = encode(
input.into_vec(),
4,
3,
usize::try_from(width).unwrap(),
usize::try_from(height).unwrap(),
);
match res {
Ok(actual) => {
assert_eq!(expected, actual);
}
Err(_err) => assert!(false),
}
}
#[test]
fn encodes_ok_2() {
// From a known encode/decode
let input = image::open("tests/data/encode-test-input-2.jpg")
.unwrap()
.to_rgba();
let (width, height) = input.dimensions();
// From the online demo
// let expected = "LGF5]+Yk^6#M@-5c,1J5@[or[Q6.";
// From our encoding
// Again, weird mismatch
let expected = "LGFFaXYk^6#M@-5c,1Ex@@or[j6o";
let res = encode(
input.into_vec(),
4,
3,
usize::try_from(width).unwrap(),
usize::try_from(height).unwrap(),
);
match res {
Ok(actual) => {
assert_eq!(expected, actual);
}
Err(_err) => assert!(false),
}
}
#[test]
fn round_trips_ok() {
// From a known encode/decode
let input = image::open("tests/data/encode-test-input.jpg")
.unwrap()
.to_rgba();
let (width, height) = input.dimensions();
// From the online demo
// let expected = "LKO2?U%2Tw=w]~RBVZRi};RPxuwH";
// From our encoding, not sure why they differ
let expected_encode = "LKO2?V%2Tw=^]~RBVZRi};RPxuwH";
let encode_res = encode(
input.into_vec(),
4,
3,
usize::try_from(width).unwrap(),
usize::try_from(height).unwrap(),
);
match encode_res {
Ok(actual_encode) => {
assert_eq!(expected_encode, actual_encode);
let expected_decode = image::open("tests/data/roundtrip-test-input-decode.png")
.unwrap()
.to_rgba();
let decode_res = decode(&actual_encode, 32, 32);
match decode_res {
Ok(actual_decode) => {
assert_eq!(expected_decode.to_vec(), actual_decode);
}
Err(_err) => assert!(false),
}
}
Err(_err) => assert!(false),
}
}
================================================
FILE: tests/web.rs
================================================
//! Test suite for the Web and headless browsers.
#![cfg(target_arch = "wasm32")]
extern crate wasm_bindgen_test;
use wasm_bindgen_test::*;
wasm_bindgen_test_configure!(run_in_browser);
#[wasm_bindgen_test]
fn pass() {
assert_eq!(1 + 1, 2);
}
gitextract_tzlsaf77/
├── .gitignore
├── Cargo.toml
├── LICENSE.md
├── README.md
├── build-wasm.sh
├── demo/
│ ├── .babelrc
│ ├── .gitignore
│ ├── .travis.yml
│ ├── App.js
│ ├── LICENSE-APACHE
│ ├── LICENSE-MIT
│ ├── README.md
│ ├── bootstrap.js
│ ├── data.json
│ ├── index.html
│ ├── index.js
│ ├── package.json
│ └── webpack.config.js
├── netlify.toml
├── src/
│ ├── lib.rs
│ └── utils.rs
└── tests/
├── integration_test.rs
└── web.rs
SYMBOL INDEX (30 symbols across 6 files)
FILE: demo/App.js
function App (line 8) | function App(props) {
function CustomImage (line 28) | function CustomImage(props) {
function ImageCredit (line 93) | function ImageCredit(props) {
function Pitch (line 103) | function Pitch() {
function useInterval (line 192) | function useInterval(callback, delay) {
FILE: demo/index.js
function main (line 9) | function main() {
FILE: src/lib.rs
type Error (line 19) | pub enum Error {
type EncodingError (line 27) | pub enum EncodingError {
function wasm_decode (line 38) | pub fn wasm_decode(blur_hash: &str, width: usize, height: usize) -> Resu...
function decode (line 42) | pub fn decode(blur_hash: &str, width: usize, height: usize) -> Result<Ve...
function decode_dc (line 122) | fn decode_dc(value: usize) -> [f64; 3] {
function decode_ac (line 133) | fn decode_ac(value: usize, maximum_value: f64) -> [f64; 3] {
function sign_pow (line 144) | fn sign_pow(value: f64, exp: f64) -> f64 {
function linear_to_srgb (line 148) | fn linear_to_srgb(value: f64) -> usize {
function srgb_to_linear (line 157) | fn srgb_to_linear(value: usize) -> f64 {
function encode (line 170) | pub fn encode(
function multiply_basis_function (line 257) | fn multiply_basis_function<F>(
function encode_dc (line 303) | fn encode_dc(value: [f64; 3]) -> usize {
function encode_ac (line 310) | fn encode_ac(value: [f64; 3], maximum_value: f64) -> usize {
function decode_base83_string (line 348) | fn decode_base83_string(string: &str) -> usize {
function encode_base83_string (line 355) | fn encode_base83_string(value: usize, length: u32) -> String {
function it_decodes_size_flag (line 367) | fn it_decodes_size_flag() {
function decodes_size_0_out_of_range (line 372) | fn decodes_size_0_out_of_range() {
FILE: src/utils.rs
function set_panic_hook (line 1) | pub fn set_panic_hook() {
FILE: tests/integration_test.rs
function err_if_hash_length_less_than_6 (line 6) | fn err_if_hash_length_less_than_6() {
function decodes_ok (line 14) | fn decodes_ok() {
function encodes_ok (line 34) | fn encodes_ok() {
function encodes_ok_2 (line 65) | fn encodes_ok_2() {
function round_trips_ok (line 97) | fn round_trips_ok() {
FILE: tests/web.rs
function pass (line 11) | fn pass() {
Condensed preview — 23 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (53K chars).
[
{
"path": ".gitignore",
"chars": 63,
"preview": "/target\n**/*.rs.bk\nCargo.lock\nbin/\npkg/\nwasm-pack.log\n.vscode/\n"
},
{
"path": "Cargo.toml",
"chars": 1339,
"preview": "[package]\nname = \"blurhash-wasm\"\nversion = \"0.2.0\"\nauthors = [\"fpapado <fgpapado@gmail.com>\"]\nedition = \"2018\"\n\ndescript"
},
{
"path": "LICENSE.md",
"chars": 1081,
"preview": "MIT License\n\nCopyright (c) 2019 Fotis Papadogeorgopoulos\n\nPermission is hereby granted, free of charge, to any person ob"
},
{
"path": "README.md",
"chars": 3064,
"preview": "# blurhash-wasm\n\nA Rust implementation of the [blurhash algorithm](https://github.com/woltapp/blurhash).\n\nIt is compiled"
},
{
"path": "build-wasm.sh",
"chars": 681,
"preview": "#!/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"
},
{
"path": "demo/.babelrc",
"chars": 83,
"preview": "{\n \"plugins\": [\n [\"@babel/plugin-transform-react-jsx\", { \"pragma\":\"h\" }]\n ]\n}\n"
},
{
"path": "demo/.gitignore",
"chars": 18,
"preview": "node_modules\ndist\n"
},
{
"path": "demo/.travis.yml",
"chars": 73,
"preview": "language: node_js\nnode_js: \"10\"\n\nscript:\n - ./node_modules/.bin/webpack\n"
},
{
"path": "demo/App.js",
"chars": 5884,
"preview": "import * as blurhash from 'blurhash-wasm';\n\n// Using react/preact in this demo mostly for convenience and habit.\n// You "
},
{
"path": "demo/LICENSE-APACHE",
"chars": 10850,
"preview": " Apache License\n Version 2.0, January 2004\n http"
},
{
"path": "demo/LICENSE-MIT",
"chars": 1052,
"preview": "Copyright (c) [year] [name]\n\nPermission is hereby granted, free of charge, to any\nperson obtaining a copy of this softwa"
},
{
"path": "demo/README.md",
"chars": 2583,
"preview": "<div align=\"center\">\n\n <h1><code>create-wasm-app</code></h1>\n\n <strong>An <code>npm init</code> template for kick star"
},
{
"path": "demo/bootstrap.js",
"chars": 279,
"preview": "// A dependency graph that contains any wasm must all be imported\n// asynchronously. This `bootstrap.js` file does the s"
},
{
"path": "demo/data.json",
"chars": 895,
"preview": "{\n \"images\": [\n {\n \"id\": 1,\n \"src\": \"/images/1.jpg\",\n \"alt\": \"A mountain range in blue and pale purpl"
},
{
"path": "demo/index.html",
"chars": 1740,
"preview": "<!DOCTYPE html>\n<html lang=\"en-US\" dir=\"ltr\">\n <head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"wid"
},
{
"path": "demo/index.js",
"chars": 362,
"preview": "import \"tachyons\"\nimport { App } from \"./App\";\nimport { render, h } from \"preact\";\n\n// You can imagine a similar data st"
},
{
"path": "demo/package.json",
"chars": 1158,
"preview": "{\n \"name\": \"blurhash-wasm-demo\",\n \"version\": \"0.1.0\",\n \"description\": \"A demo app for blurhash-wasm\",\n \"main\": \"inde"
},
{
"path": "demo/webpack.config.js",
"chars": 1283,
"preview": "const CopyWebpackPlugin = require(\"copy-webpack-plugin\");\nconst MiniCssExtractPlugin = require(\"mini-css-extract-plugin\""
},
{
"path": "netlify.toml",
"chars": 1197,
"preview": "# This file configures the headers and redirect rules for Netlify.\n# Some are important for the page to work correctly, "
},
{
"path": "src/lib.rs",
"chars": 12033,
"preview": "mod utils;\n\nuse std::cmp::Ordering;\nuse std::convert::TryFrom;\nuse std::f64::consts::PI;\nuse thiserror::*;\nuse wasm_bind"
},
{
"path": "src/utils.rs",
"chars": 445,
"preview": "pub fn set_panic_hook() {\n // When the `console_error_panic_hook` feature is enabled, we can call the\n // `set_pan"
},
{
"path": "tests/integration_test.rs",
"chars": 3283,
"preview": "use blurhash_wasm::{decode, encode};\nuse image;\nuse std::convert::TryFrom;\n\n#[test]\nfn err_if_hash_length_less_than_6() "
},
{
"path": "tests/web.rs",
"chars": 251,
"preview": "//! Test suite for the Web and headless browsers.\n\n#![cfg(target_arch = \"wasm32\")]\n\nextern crate wasm_bindgen_test;\nuse "
}
]
About this extraction
This page contains the full source code of the fpapado/blurhash-rust-wasm GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 23 files (48.5 KB), approximately 13.6k tokens, and a symbol index with 30 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.