123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- 'use strict';
- const Hoek = require('@hapi/hoek');
- const Any = require('../any');
- const internals = {};
- internals.Binary = class extends Any {
- constructor() {
- super();
- this._type = 'binary';
- }
- _base(value, state, options) {
- const result = {
- value
- };
- if (typeof value === 'string' &&
- options.convert) {
- try {
- result.value = Buffer.from(value, this._flags.encoding);
- }
- catch (e) { }
- }
- result.errors = Buffer.isBuffer(result.value) ? null : this.createError('binary.base', null, state, options);
- return result;
- }
- encoding(encoding) {
- Hoek.assert(Buffer.isEncoding(encoding), 'Invalid encoding:', encoding);
- if (this._flags.encoding === encoding) {
- return this;
- }
- const obj = this.clone();
- obj._flags.encoding = encoding;
- return obj;
- }
- min(limit) {
- Hoek.assert(Number.isSafeInteger(limit) && limit >= 0, 'limit must be a positive integer');
- return this._test('min', limit, function (value, state, options) {
- if (value.length >= limit) {
- return value;
- }
- return this.createError('binary.min', { limit, value }, state, options);
- });
- }
- max(limit) {
- Hoek.assert(Number.isSafeInteger(limit) && limit >= 0, 'limit must be a positive integer');
- return this._test('max', limit, function (value, state, options) {
- if (value.length <= limit) {
- return value;
- }
- return this.createError('binary.max', { limit, value }, state, options);
- });
- }
- length(limit) {
- Hoek.assert(Number.isSafeInteger(limit) && limit >= 0, 'limit must be a positive integer');
- return this._test('length', limit, function (value, state, options) {
- if (value.length === limit) {
- return value;
- }
- return this.createError('binary.length', { limit, value }, state, options);
- });
- }
- };
- module.exports = new internals.Binary();
|