Skip to content

Commit

Permalink
perf: simplify initial argument checking
Browse files Browse the repository at this point in the history
  • Loading branch information
dougwilson committed Dec 28, 2016
1 parent a8bd991 commit 242c838
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 9 deletions.
5 changes: 5 additions & 0 deletions HISTORY.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
unreleased
==========

* perf: simplify initial argument checking

2.3.2 / 2016-11-16
==================

Expand Down
42 changes: 33 additions & 9 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,22 +47,15 @@ var maxMaxAge = 60 * 60 * 24 * 365 * 1000; // 1 year
function favicon(path, options) {
var opts = options || {};

var buf;
var icon; // favicon cache
var maxAge = calcMaxAge(opts.maxAge);
var stat;

if (!path) throw new TypeError('path to favicon.ico is required');

if (Buffer.isBuffer(path)) {
buf = new Buffer(path.length);
path.copy(buf);

icon = createIcon(buf, maxAge);
icon = createIcon(copyBuffer(path), maxAge)
} else if (typeof path === 'string') {
path = resolve(path);
stat = fs.statSync(path);
if (stat.isDirectory()) throw createIsDirError(path);
path = resolveSync(path)
} else {
throw new TypeError('path to favicon.ico must be string or buffer');
}
Expand Down Expand Up @@ -109,6 +102,19 @@ function calcMaxAge(val) {
: maxMaxAge
}

/**
* Copy a given Buffer.
*
* @param {Buffer} buf
* @private
*/

function copyBuffer (buf) {
var copy = new Buffer(buf.length)
buf.copy(copy)
return copy
}

/**
* Create icon data from Buffer and max-age.
*
Expand Down Expand Up @@ -145,6 +151,24 @@ function createIsDirError(path) {
return error;
}

/**
* Resolve the path to icon.
*
* @param {string} iconPath
* @private
*/

function resolveSync (iconPath) {
var path = resolve(iconPath)
var stat = fs.statSync(path)

if (stat.isDirectory()) {
throw createIsDirError(path)
}

return path
}

/**
* Send icon data in response to a request.
*
Expand Down

0 comments on commit 242c838

Please sign in to comment.