Convert a value

@param   {*}         value       Value to convert
@param   {Boolean}   rawBuffer   true to return a raw buffer
@param   {Boolean}   cast        true to cast the value
@returns {*}         converted value
510823
function convertValue(value, cast) {
  var val;
  if (value === null || value === undefined) {
    return value;
  }
  val = Buffer.isBuffer(value) ? value.toString('utf8') : value;
  if (cast !== false && typeof val === 'string') {
    try {
      return JSON.parse(val);
    } catch (e) {}
  }
  return val;
}
546438
function convert (buffer, from, to) {
	//ensure formats are full
	if (!isNormalized(from)) from = normalize(from)
	if (!isNormalized(to)) to = normalize(to)

	//convert buffer/alike to arrayBuffer
	var data
	if (buffer instanceof ArrayBuffer) {
		data = buffer
	}
	else if (ArrayBuffer.isView(buffer)) {
		if (buffer.byteOffset != null) data = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
		else data = buffer.buffer;
	}
	else {
		data = (new Uint8Array(buffer.length != null ? buffer : [buffer])).buffer
	}

	//ignore needless conversion
	if (equal(from ,to)) {
		return data
	}

	//create containers for conversion
	var fromArray = new (arrayClass(from))(data)

	//toArray is automatically filled with mapped values
	//but in some cases mapped badly, e. g. float → int(round + rotate)
	var toArray = new (arrayClass(to))(fromArray)

	//if range differ, we should apply more thoughtful mapping
	if (from.max !== to.max) {
		fromArray.forEach(function (value, idx) {
			//ignore not changed range
			//bring to 0..1
			var normalValue = (value - from.min) / (from.max - from.min)

			//bring to new format ranges
			value = normalValue * (to.max - to.min) + to.min

			//clamp (buffers does not like values outside of bounds)
			toArray[idx] = Math.max(to.min, Math.min(to.max, value))
		})
	}

	//reinterleave, if required
	if (from.interleaved != to.interleaved) {
		var channels = from.channels
		var len = Math.floor(fromArray.length / channels)

		//deinterleave
		if (from.interleaved && !to.interleaved) {
			toArray = toArray.map(function (value, idx, data) {
				var targetOffset = idx % len
				var targetChannel = ~~(idx / len)

				return data[targetOffset * channels + targetChannel]
			})
		}
		//interleave
		else if (!from.interleaved && to.interleaved) {
			toArray = toArray.map(function (value, idx, data) {
				var targetOffset = ~~(idx / channels)
				var targetChannel = idx % channels

				return data[targetChannel * len + targetOffset]
			})
		}
	}

	//ensure endianness
	if (!to.float && from.byteOrder !== to.byteOrder) {
		var le = to.byteOrder === 'LE'
		var view = new DataView(toArray.buffer)
		var step = to.bitDepth / 8
		var methodName = 'set' + getDataViewSuffix(to)
		for (var i = 0, l = toArray.length; i < l; i++) {
			view[methodName](i*step, toArray[i], le)
		}
	}

	return toArray.buffer
}
606029
def cast(value, context, reconstantize: true, convert: true)
      @klass ||= klass

      if matches?(value)
        value
      elsif reconstantize
        @klass = klass
        public_send(__method__, value, context,
          reconstantize: false,
          convert: convert
        )
      elsif !value.nil? && convert && (converter = options[:converter])
        value = convert(klass, value, converter)
        public_send(__method__, value, context,
          reconstantize: reconstantize,
          convert: false
        )
      else
        super(value, context)
      end
    end
181136
function toBuffer(data, encoding) {
    return (typeof Buffer.from === 'function' && Buffer.from !== Uint8Array.from) ?
        Buffer.from(data, encoding) : new Buffer(data, encoding);
}
1320236
def _cast_boolean(value):
    
    _BOOLEANS = {'1': True, 'yes': True, 'true': True, 'on': True,
                 '0': False, 'no': False, 'false': False, 'off': False, '': False}
    value = str(value)
    if value.lower() not in _BOOLEANS:
        raise ValueError('Not a boolean: %s' % value)

    return _BOOLEANS[value.lower()]
966630
def cast_value(parent, value)
      if !allow_blank && value.to_s.empty?
        nil
      else
        value = typecast_value(parent, self, value)
        associate_casted_value_to_parent(parent, value)
      end
    end
531180
protected Object cast(Object value) {
        switch (type) {
            case STRING :
               return valueFactories.getStringFactory().create(value);
            case LONG :
                return valueFactories.getLongFactory().create(value);
            case NAME :
                return valueFactories.getNameFactory().create(value);
            case PATH :
                return valueFactories.getPathFactory().create(value);
            case DATE :
                return valueFactories.getDateFactory().create(value);
            case BOOLEAN :
                return valueFactories.getBooleanFactory().create(value);
            case URI :
                return valueFactories.getUriFactory().create(value);
            case REFERENCE :
                return valueFactories.getReferenceFactory().create(value);
            case SIMPLEREFERENCE :
                return valueFactories.getSimpleReferenceFactory().create(value);
            case WEAKREFERENCE :
                return valueFactories.getWeakReferenceFactory().create(value);
            default :
                return value;
        }
    }
956334
@SuppressWarnings({ "unchecked", "rawtypes" })
    public static Object convert(Object value, Class<?> type) {
        if (value == null || type == null || type.isAssignableFrom(value.getClass())) {
            return value;
        }
        if (value instanceof String) {
            String string = (String) value;
            if (char.class.equals(type) || Character.class.equals(type)) {
                if (string.length() != 1) {
                    throw new IllegalArgumentException(String.format("can not convert String(%s) to char!" +
                        " when convert String to char, the String must only 1 char.", string));
                }
                return string.charAt(0);
            } else if (type.isEnum()) {
                return Enum.valueOf((Class<Enum>) type, string);
            } else if (type == BigInteger.class) {
                return new BigInteger(string);
            } else if (type == BigDecimal.class) {
                return new BigDecimal(string);
            } else if (type == Short.class || type == short.class) {
                return Short.valueOf(string);
            } else if (type == Integer.class || type == int.class) {
                return Integer.valueOf(string);
            } else if (type == Long.class || type == long.class) {
                return Long.valueOf(string);
            } else if (type == Double.class || type == double.class) {
                return new Double(string);
            } else if (type == Float.class || type == float.class) {
                return new Float(string);
            } else if (type == Byte.class || type == byte.class) {
                return Byte.valueOf(string);
            } else if (type == Boolean.class || type == boolean.class) {
                return Boolean.valueOf(string);
            } else if (type == Date.class || type == java.sql.Date.class || type == java.sql.Time.class ||
                type == java.sql.Timestamp.class) {
                try {
                    if (type == Date.class) {
                        return DateUtils.strToDate(string, DateUtils.DATE_FORMAT_TIME);
                    } else if (type == java.sql.Date.class) {
                        return new java.sql.Date(DateUtils.strToLong(string));
                    } else if (type == java.sql.Timestamp.class) {
                        return new java.sql.Timestamp(DateUtils.strToLong(string));
                    } else {
                        return new java.sql.Time(DateUtils.strToLong(string));
                    }
                } catch (ParseException e) {
                    throw new IllegalStateException("Failed to parse date " + value + " by format " +
                        DateUtils.DATE_FORMAT_TIME + ", cause: " + e.getMessage(), e);
                }
            } else if (type == Class.class) {
                return ClassTypeUtils.getClass((String) value);
            }
        } else if (value instanceof Number) {
            Number number = (Number) value;
            if (type == byte.class || type == Byte.class) {
                return number.byteValue();
            } else if (type == short.class || type == Short.class) {
                return number.shortValue();
            } else if (type == int.class || type == Integer.class) {
                return number.intValue();
            } else if (type == long.class || type == Long.class) {
                return number.longValue();
            } else if (type == float.class || type == Float.class) {
                return number.floatValue();
            } else if (type == double.class || type == Double.class) {
                return number.doubleValue();
            } else if (type == BigInteger.class) {
                return BigInteger.valueOf(number.longValue());
            } else if (type == BigDecimal.class) {
                return BigDecimal.valueOf(number.doubleValue());
            } else if (type == Date.class) {
                return new Date(number.longValue());
            } else if (type == java.sql.Date.class) {
                return new java.sql.Date(number.longValue());
            } else if (type == java.sql.Time.class) {
                return new java.sql.Time(number.longValue());
            } else if (type == java.sql.Timestamp.class) {
                return new java.sql.Timestamp(number.longValue());
            }
        } else if (value instanceof Collection) {
            Collection collection = (Collection) value;
            if (type.isArray()) {
                int length = collection.size();
                Object array = Array.newInstance(type.getComponentType(), length);
                int i = 0;
                for (Object item : collection) {
                    Array.set(array, i++, item);
                }
                return array;
            } else if (!type.isInterface()) {
                try {
                    Collection result = (Collection) type.newInstance();
                    result.addAll(collection);
                    return result;
                } catch (Throwable ignore) { // NOPMD
                }
            } else if (type == List.class) {
                return new ArrayList<Object>(collection);
            } else if (type == Set.class) {
                return new HashSet<Object>(collection);
            }
        } else if (value.getClass().isArray() && Collection.class.isAssignableFrom(type)) {
            Collection collection;
            if (!type.isInterface()) {
                try {
                    collection = (Collection) type.newInstance();
                } catch (Throwable e) {
                    collection = new ArrayList<Object>();
                }
            } else if (type == Set.class) {
                collection = new HashSet<Object>();
            } else {
                collection = new ArrayList<Object>();
            }
            int length = Array.getLength(value);
            for (int i = 0; i < length; i++) {
                collection.add(Array.get(value, i));
            }
            return collection;
        }
        return value;
    }
1318731
def _cast_to_type(self, value):
        
        if not isinstance(value, dict):
            self.fail('invalid', value=value)
        return value
778529
@SuppressWarnings("PMD.LooseCoupling")
    public static Object castValue(Method m, Class<?> castType, String value) {

        try {
            if (castType.isEnum()) {
                Method valueOf;
                try {
                    valueOf = castType.getMethod("valueOf", String.class);
                    return valueOf.invoke(null, value);
                } catch (Exception e) {
                    log.info("enum value of excute error : (" + castType.getName() + ") | " + value);
                    return null;
                }
            } else if (castType == Integer.class || castType == int.class) {
                return Integer.parseInt(value);
            } else if (castType == Long.class || castType == long.class) {
                return Long.parseLong(value);
            } else if (castType == Double.class || castType == double.class) {
                return Double.parseDouble(value);
            } else if (castType == Boolean.class || castType == boolean.class) {
                return Boolean.parseBoolean(value);
            } else if (castType == Float.class || castType == float.class) {
                return Float.parseFloat(value);
            } else if (castType == String.class) {
                return value;
            } else if (castType == ArrayList.class || castType == List.class) {
                ParameterizedType paramType = (ParameterizedType) m.getGenericParameterTypes()[0];
                Class<?> paramClass = (Class<?>) paramType.getActualTypeArguments()[0];
                List<Object> castList = new ArrayList<>();
                String[] values = value.split(",");
                for (String v : values) {
                    castList.add(castValue(m, paramClass, v));
                }

                return castList;
            } else {
                log.info("invalid castType : " + castType);
                return null;
            }
        } catch (NumberFormatException e) {
            log.info("value : " + value + " is invalid value, setter parameter type is  : " + castType);
            return null;
        }
    }
519928
def cast(parent, value)
      return value unless casted
      if type.is_a?(Array)
        # Convert to array if it is not already
        value = [value].compact unless value.is_a?(Array)
        arr = value.collect { |data| cast_value(parent, data) }
        # allow casted_by calls to be passed up chain by wrapping in CastedArray
        value = type_class != String ? ::CouchRest::CastedArray.new(arr, self) : arr
        value.casted_by = parent if value.respond_to?(:casted_by)
      elsif !value.nil?
        value = cast_value(parent, value)
      end
      value
    end
817539
def _cast_boolean(self, value):
        
        if value.lower() not in self._BOOLEANS:
            raise ValueError('Not a boolean: %s' % value)

        return self._BOOLEANS[value.lower()]
397292
function(value) {
            var toString = Object.prototype.toString;
            return value === true || value === false || (!!value && typeof value === 'object' && toString.call(value) === '[object Boolean]');
        }
544340
function asBuffer(data, encoding) {
    let result = data;
    if (!isNullOrUndefined(result)) {
        if ('object' !== typeof result) {
            // handle as string
            encoding = normalizeString(encoding);
            if (!encoding) {
                encoding = 'utf8';
            }
            result = new Buffer(toStringSafe(result), encoding);
        }
    }
    return result;
}
1120228
function castShorthand (value) {
  var obj

  if (typeof value === 'string') obj = { link: value }
  else if (typeof value === 'function') obj = { type: value }
  else if (Array.isArray(value)) {
    obj = {}

    if (value[1]) obj.inverse = value[1]
    else obj.isArray = true

    // Extract type or link.
    if (Array.isArray(value[0])) {
      obj.isArray = true
      value = value[0][0]
    }
    else value = value[0]

    if (typeof value === 'string') obj.link = value
    else if (typeof value === 'function') obj.type = value
  }
  else return value

  return obj
}
599923
function(rawBuffer) {
    if (rawBuffer && this.offset === 0) return this.buffer;

    var out = new Buffer(8);
    this.buffer.copy(out, 0, this.offset, this.offset + 8);
    return out;
  }
961912
def _cast_to_type(self, value):
        
        if not isinstance(value, list):
            self.fail('invalid', value=value)
        return value