// Generated by IcedCoffeeScript 1.7.1-f
(function() {
  var ASP, Canceler, Warnings, assert, assert_no_nulls, asyncify, bufeq_secure, buffer_to_ui8a, bufferify, iced, katch, obj_extract, strip, trim, ui32a_to_ui8a, ui8Ga_to_ui32a, xxd, __iced_k, __iced_k_noop,
    __slice = [].slice;

  iced = require('iced-runtime');
  __iced_k = __iced_k_noop = function() {};

  Canceler = require('iced-error').Canceler;

  assert = require('assert');

  exports.uint_to_buffer = function(nbits, i) {
    var ret;
    ret = null;
    switch (nbits) {
      case 16:
        ret = new Buffer(2);
        ret.writeUInt16BE(i, 0);
        break;
      case 32:
        ret = new Buffer(4);
        ret.writeUInt32BE(i, 0);
        break;
      case 8:
        ret = new Buffer(1);
        ret.writeUInt8(i, 0);
        break;
      default:
        throw new Error("Bit types not found: " + nbit);
    }
    return ret;
  };

  exports.ASP = ASP = (function() {
    function ASP(_arg) {
      var canceler, delay, progress_hook;
      progress_hook = _arg.progress_hook, delay = _arg.delay, canceler = _arg.canceler;
      this._delay = delay != null ? delay : 2;
      this._canceler = canceler || (new Canceler());
      this._progress_hook = progress_hook || (function(obj) {});
      this._section = null;
    }

    ASP.prototype.section = function(s) {
      this._section = s;
      return this;
    };

    ASP.prototype.progress = function(o, cb) {
      var err, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      if (this._section) {
        o.section = this._section;
      }
      this._progress_hook(o);
      if (cb != null) {
        (function(_this) {
          return (function(__iced_k) {
            __iced_deferrals = new iced.Deferrals(__iced_k, {
              parent: ___iced_passed_deferral,
              filename: "/Users/max/src/keybase/pgp-utils/src/util.iced",
              funcname: "ASP.progress"
            });
            _this.delay(__iced_deferrals.defer({
              assign_fn: (function() {
                return function() {
                  return err = arguments[0];
                };
              })(),
              lineno: 43
            }));
            __iced_deferrals._fulfill();
          });
        })(this)((function(_this) {
          return function() {
            return __iced_k(cb(err));
          };
        })(this));
      } else {
        return __iced_k();
      }
    };

    ASP.prototype.delay = function(cb) {
      var ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      (function(_this) {
        return (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/Users/max/src/keybase/pgp-utils/src/util.iced",
            funcname: "ASP.delay"
          });
          setTimeout(__iced_deferrals.defer({
            lineno: 47
          }), _this.delay);
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          return cb(_this._canceler.err());
        };
      })(this));
    };

    ASP.prototype.canceler = function() {
      return this._canceler;
    };

    ASP.prototype.progress_hook = function() {
      return this._progress_hook;
    };

    ASP.make = function(asp) {
      return asp || (new ASP({}));
    };

    return ASP;

  })();

  exports.Warnings = Warnings = (function() {
    function Warnings() {
      this._w = [];
    }

    Warnings.prototype.push = function() {
      var args, _ref;
      args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
      return (_ref = this._w).push.apply(_ref, args);
    };

    Warnings.prototype.warnings = function() {
      return this._w;
    };

    return Warnings;

  })();

  exports.bufeq_fast = function(x, y) {
    var i, _i, _ref;
    if ((x == null) && (y == null)) {
      return true;
    }
    if ((x == null) || (y == null)) {
      return false;
    }
    if (x.length !== y.length) {
      return false;
    }
    for (i = _i = 0, _ref = x.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
      if (x.readUInt8(i) !== y.readUInt8(i)) {
        return false;
      }
    }
    return true;
  };

  exports.bufeq_secure = bufeq_secure = function(x, y) {
    var check, i, ret;
    ret = (function() {
      var _i, _ref;
      if ((x == null) && (y == null)) {
        return true;
      } else if ((x == null) || (y == null)) {
        return false;
      } else if (x.length !== y.length) {
        return false;
      } else {
        check = 0;
        for (i = _i = 0, _ref = x.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
          check |= x.readUInt8(i) ^ y.readUInt8(i);
        }
        return check === 0;
      }
    })();
    return ret;
  };

  exports.streq_secure = function(x, y) {
    var B;
    B = function(x) {
      if (x != null) {
        return bufferify(x);
      } else {
        return null;
      }
    };
    return bufeq_secure(B(x), B(y));
  };

  exports.bufferify = bufferify = function(s) {
    if (Buffer.isBuffer(s)) {
      return s;
    } else if (typeof s === 'string') {
      return new Buffer(s, 'utf8');
    } else {
      throw new Error("Cannot convert to buffer: " + s);
    }
  };

  exports.katch = katch = function(fn) {
    var e, err, ret;
    ret = err = null;
    try {
      ret = fn();
    } catch (_error) {
      e = _error;
      err = e;
    }
    return [err, ret];
  };

  exports.akatch = function(fn, cb) {
    return asyncify(katch(fn), cb);
  };

  exports.buffer_to_ui8a = buffer_to_ui8a = function(b) {
    var i, l, ret, _i;
    l = b.length;
    ret = new Uint8Array(l);
    for (i = _i = 0; 0 <= l ? _i < l : _i > l; i = 0 <= l ? ++_i : --_i) {
      ret[i] = b.readUInt8(i);
    }
    return ret;
  };

  exports.ui32a_to_ui8a = ui32a_to_ui8a = function(v, out) {
    var k, w, _i, _len;
    if (out == null) {
      out = null;
    }
    out || (out = new Uint8Array(v.length * 4));
    k = 0;
    for (_i = 0, _len = v.length; _i < _len; _i++) {
      w = v[_i];
      out[k++] = (w >> 24) & 0xff;
      out[k++] = (w >> 16) & 0xff;
      out[k++] = (w >> 8) & 0xff;
      out[k++] = w & 0xff;
    }
    return out;
  };

  exports.ui8a_to_ui32a = ui8Ga_to_ui32a = function(v, out) {
    var b, i, k, tmp, _i, _len;
    if (out == null) {
      out = null;
    }
    out || (out = new Uint32Array(v.length >> 2));
    k = 0;
    for (i = _i = 0, _len = v.length; _i < _len; i = _i += 4) {
      b = v[i];
      tmp = (b << 24) + (v[i + 1] << 16) + (v[i + 2] << 8) + v[i + 3];
      out[k++] = tmp;
    }
    return out;
  };

  exports.unix_time = function() {
    return Math.floor(Date.now() / 1000);
  };

  exports.json_stringify_sorted = function(o, opts) {
    var i, json_safe, lb, o2, sort_fn, space_it, spaces, str;
    opts = opts || {};
    sort_fn = opts.sort_fn || null;
    spaces = opts.spaces || null;
    lb = opts.spaces != null ? "\n" : "";
    if ((typeof spaces) === "number") {
      spaces = ((function() {
        var _i, _results;
        _results = [];
        for (i = _i = 0; 0 <= spaces ? _i < spaces : _i > spaces; i = 0 <= spaces ? ++_i : --_i) {
          _results.push(" ");
        }
        return _results;
      })()).join("");
    }
    space_it = function(depth) {
      if (spaces == null) {
        return "";
      }
      return "\n" + ((function() {
        var _i, _results;
        _results = [];
        for (i = _i = 0; 0 <= depth ? _i < depth : _i > depth; i = 0 <= depth ? ++_i : --_i) {
          _results.push(spaces);
        }
        return _results;
      })()).join("");
    };
    json_safe = function(os, depth) {
      var k, keys, s, sp, spp, v;
      if (Array.isArray(os)) {
        s = "[" + ((function() {
          var _i, _len, _results;
          _results = [];
          for (_i = 0, _len = os.length; _i < _len; _i++) {
            v = os[_i];
            _results.push(json_safe(v, depth + 1));
          }
          return _results;
        })()).join(',') + "]";
      } else if ((typeof os) === "object") {
        if (!os) {
          s = JSON.stringify(os);
        } else {
          sp = space_it(depth);
          spp = space_it(depth + 1);
          keys = (function() {
            var _results;
            _results = [];
            for (k in os) {
              _results.push(k);
            }
            return _results;
          })();
          if (sort_fn) {
            keys.sort(sort_fn);
          } else {
            keys.sort();
          }
          s = "{" + ((function() {
            var _i, _len, _results;
            _results = [];
            for (_i = 0, _len = keys.length; _i < _len; _i++) {
              k = keys[_i];
              _results.push(spp + JSON.stringify(k) + ":" + json_safe(os[k], depth + 1));
            }
            return _results;
          })()).join(',') + sp + "}";
        }
      } else {
        s = JSON.stringify(os);
      }
      return s;
    };
    str = JSON.stringify(o);
    if (str === void 0) {
      return str;
    } else {
      o2 = JSON.parse(str);
      return json_safe(o2, 0);
    }
  };

  exports.obj_extract = obj_extract = function(o, keys) {
    var k, ret, _i, _len;
    ret = {};
    for (_i = 0, _len = keys.length; _i < _len; _i++) {
      k = keys[_i];
      ret[k] = o[k];
    }
    return ret;
  };

  exports.base64u = {
    encode: function(b) {
      return b.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
    },
    decode: function(b) {
      b = (b + Array(5 - b.length % 4).join('=')).replace(/\-/g, '+').replace(/\_/g, '/');
      return new Buffer(b, 'base64');
    },
    verify: function(b) {
      return /^[A-Za-z0-9\-_]+$/.test(b);
    }
  };

  exports.assert_no_nulls = assert_no_nulls = function(v) {
    var e, ok, _i, _len;
    ok = true;
    for (_i = 0, _len = v.length; _i < _len; _i++) {
      e = v[_i];
      if (e == null) {
        ok = false;
      }
    }
    if (!ok) {
      console.error("Found 1 or more nulls in vector: ");
      console.error(v);
      return assert(false);
    }
  };

  exports.athrow = function(err, cb) {
    return cb(err);
  };

  exports.asyncify = asyncify = function(args, cb) {
    return cb.apply(null, args);
  };

  exports.format_fingerprint = function(raw) {
    var hex, i, parts;
    hex = raw.toString('hex').toUpperCase();
    parts = (function() {
      var _i, _ref, _results;
      _results = [];
      for (i = _i = 0, _ref = hex.length; _i < _ref; i = _i += 4) {
        _results.push(hex.slice(i, i + 4));
      }
      return _results;
    })();
    return parts.join(' ');
  };

  exports.format_pgp_fingerprint_2 = function(buf, opts) {
    var hex, i, length, parts, spc;
    if (opts == null) {
      opts = {};
    }
    hex = buf.toString('hex');
    length = (opts != null ? opts.length : void 0) || 40;
    spc = (opts != null ? opts.space : void 0) || ' ';
    hex = hex.toUpperCase().slice(-length);
    if (hex.length === 40) {
      parts = (function() {
        var _i, _ref, _results;
        _results = [];
        for (i = _i = 0, _ref = hex.length; _i < _ref; i = _i += 4) {
          _results.push(hex.slice(i, i + 4));
        }
        return _results;
      })();
      parts = (function() {
        var _i, _ref, _results;
        _results = [];
        for (i = _i = 0, _ref = parts.length; _i < _ref; i = _i += 5) {
          _results.push(parts.slice(i, i + 5).join(spc));
        }
        return _results;
      })();
      return parts.join(spc + spc);
    } else if (hex.length > 8) {
      parts = (function() {
        var _i, _ref, _results;
        _results = [];
        for (i = _i = 0, _ref = hex.length; _i < _ref; i = _i += 4) {
          _results.push(hex.slice(i, i + 4));
        }
        return _results;
      })();
      return parts.join(spc);
    } else {
      return hex;
    }
  };

  exports.fingerprint_to_key_id_64 = function(fp) {
    return fp.slice(-16);
  };

  exports.strip = strip = function(x) {
    return x.split(/\s+/).join('');
  };

  exports.trim = trim = function(x) {
    var m;
    if ((m = x != null ? x.match(/^\s+(.*?)$/) : void 0)) {
      x = m[1];
    }
    if ((m = x != null ? x.match(/^(.*?)\s+$/) : void 0)) {
      x = m[1];
    }
    return x;
  };

  exports.fpeq = function(fp1, fp2) {
    return strip(fp1).toLowerCase() === strip(fp2).toLowerCase();
  };

  exports.xxd = xxd = function(buf, opts) {
    var i, line, lines, p, pad, q, quartets, v;
    if (opts == null) {
      opts = {};
    }
    q = opts.q || 8;
    p = opts.p || 7;
    buf = buf.toString('hex');
    quartets = (function() {
      var _i, _ref, _results;
      _results = [];
      for (i = _i = 0, _ref = buf.length; _i < _ref; i = _i += 4) {
        _results.push(buf.slice(i, i + 4));
      }
      return _results;
    })();
    lines = (function() {
      var _i, _ref, _results;
      _results = [];
      for (i = _i = 0, _ref = quartets.length; q > 0 ? _i < _ref : _i > _ref; i = _i += q) {
        _results.push(quartets.slice(i, i + q).join(' '));
      }
      return _results;
    })();
    pad = function(s, n) {
      return ((function() {
        var _i, _ref, _results;
        _results = [];
        for (_i = 0, _ref = n - s.length; 0 <= _ref ? _i < _ref : _i > _ref; 0 <= _ref ? _i++ : _i--) {
          _results.push('0');
        }
        return _results;
      })()).join('') + s;
    };
    v = (function() {
      var _i, _len, _results;
      _results = [];
      for (i = _i = 0, _len = lines.length; _i < _len; i = ++_i) {
        line = lines[i];
        _results.push(pad((i * 2 * q).toString(16), p) + ": " + line);
      }
      return _results;
    })();
    return v.join("\n");
  };

}).call(this);
