All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.scalactic.anyvals.NonZeroInt.scala Maven / Gradle / Ivy

The newest version!
/*
 * Copyright 2001-2016 Artima, Inc.
 *
 * 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.
 */
package org.scalactic.anyvals

import scala.collection.immutable.Range
import scala.language.implicitConversions
import scala.util.{Try, Success, Failure}

import org.scalactic.{Validation, Pass, Fail}
import org.scalactic.{Or, Good, Bad}

/**
 * An AnyVal for non-zero Ints.
 *
 * Note: a NonZeroInt may not equal 0.
 *
 * 

* Because NonZeroInt is an AnyVal it will usually be * as efficient as an Int, being boxed only when an Int * would have been boxed. *

* *

* The NonZeroInt.apply factory method is implemented in terms of a macro that * checks literals for validity at compile time. Calling NonZeroInt.apply with * a literal Int value will either produce a valid NonZeroInt instance * at run time or an error at compile time. Here's an example: *

* *
 * scala> import anyvals._
 * import anyvals._
 *
 * scala> NonZeroInt(42)
 * res0: org.scalactic.anyvals.NonZeroInt = NonZeroInt(42)
 *
 * scala> NonZeroInt(0)
 * <console>:14: error: NonZeroInt.apply can only be invoked on a non-zero (i != 0) literal, like NonZeroInt(42).
 *               NonZeroInt(0)
 *                     ^
 * 
* *

* NonZeroInt.apply cannot be used if the value being passed is a variable (i.e., not a literal), because * the macro cannot determine the validity of variables at compile time (just literals). If you try to pass a variable * to NonZeroInt.apply, you'll get a compiler error that suggests you use a different factor method, * NonZeroInt.from, instead: *

* *
 * scala> val x = 1
 * x: Int = 1
 *
 * scala> NonZeroInt(x)
 * <console>:15: error: NonZeroInt.apply can only be invoked on a non-zero integer literal, like NonZeroInt(42). Please use NonZeroInt.from instead.
 *               NonZeroInt(x)
 *                     ^
 * 
* *

* The NonZeroInt.from factory method will inspect the value at runtime and return an Option[NonZeroInt]. If * the value is valid, NonZeroInt.from will return a Some[NonZeroInt], else it will return a None. * Here's an example: *

* *
 * scala> NonZeroInt.from(x)
 * res3: Option[org.scalactic.anyvals.NonZeroInt] = Some(NonZeroInt(1))
 *
 * scala> val y = 0
 * y: Int = 0
 *
 * scala> NonZeroInt.from(y)
 * res4: Option[org.scalactic.anyvals.NonZeroInt] = None
 * 
* *

* The NonZeroInt.apply factory method is marked implicit, so that you can pass literal Ints * into methods that require NonZeroInt, and get the same compile-time checking you get when calling * NonZeroInt.apply explicitly. Here's an example: *

* *
 * scala> def invert(pos: NonZeroInt): Int = Int.MaxValue - pos
 * invert: (pos: org.scalactic.anyvals.NonZeroInt)Int
 *
 * scala> invert(1)
 * res0: Int = 2147483646
 *
 * scala> invert(Int.MaxValue)
 * res1: Int = 0
 *
 * scala> invert(0)
 * <console>:15: error: NonZeroInt.apply can only be invoked on a non-zero (i != 0) integer literal, like NonZeroInt(42).
 *               invert(0)
 *                      ^
 *
 * scala> invert(-1)
 * <console>:15: error: NonZeroInt.apply can only be invoked on a non-zero (i != 0) integer literal, like NonZeroInt(42).
 *               invert(-1)
 *                       ^
 *
 * 
* *

* This example also demonstrates that the NonZeroInt companion object also defines implicit widening conversions * when either no loss of precision will occur or a similar conversion is provided in Scala. (For example, the implicit * conversion from Int to Float in Scala can lose precision.) This makes it convenient to * use a NonZeroInt where an Int or wider type is needed. An example is the subtraction in the body * of the invert method defined above, Int.MaxValue - pos. Although Int.MaxValue is * an Int, which has no - method that takes a NonZeroInt (the type of pos), * you can still subtract pos, because the NonZeroInt will be implicitly widened to Int. *

* * @param value The Int value underlying this NonZeroInt. */ final class NonZeroInt private (val value: Int) extends AnyVal { /** * A string representation of this NonZeroInt. */ override def toString: String = s"NonZeroInt(${value.toString()})" /** * Converts this NonZeroInt to a Byte. */ def toByte: Byte = value.toByte /** * Converts this NonZeroInt to a Short. */ def toShort: Short = value.toShort /** * Converts this NonZeroInt to a Char. */ def toChar: Char = value.toChar /** * Converts this NonZeroInt to an Int. */ def toInt: Int = value.toInt /** * Converts this NonZeroInt to a Long. */ def toLong: Long = value.toLong /** * Converts this NonZeroInt to a Float. */ def toFloat: Float = value.toFloat /** * Converts this NonZeroInt to a Double. */ def toDouble: Double = value.toDouble /** * Returns the bitwise negation of this value. * @example {{{ * ~5 == -6 * // in binary: ~00000101 == * // 11111010 * }}} */ def unary_~ : Int = ~value /** Returns this value, unmodified. */ def unary_+ : NonZeroInt = this /** Returns the negation of this value. */ def unary_- : NonZeroInt = NonZeroInt.ensuringValid(-value) /** * Converts this NonZeroInt's value to a string then concatenates the given string. */ def +(x: String): String = s"${value.toString()}${x.toString()}" /** * Returns this value bit-shifted left by the specified number of bits, * filling in the new right bits with zeroes. * @example {{{ 6 << 3 == 48 // in binary: 0110 << 3 == 0110000 }}} */ def <<(x: Int): Int = value << x /** * Returns this value bit-shifted left by the specified number of bits, * filling in the new right bits with zeroes. * @example {{{ 6 << 3 == 48 // in binary: 0110 << 3 == 0110000 }}} */ def <<(x: Long): Int = value << x /** * Returns this value bit-shifted right by the specified number of bits, * filling the new left bits with zeroes. * @example {{{ 21 >>> 3 == 2 // in binary: 010101 >>> 3 == 010 }}} * @example {{{ * -21 >>> 3 == 536870909 * // in binary: 11111111 11111111 11111111 11101011 >>> 3 == * // 00011111 11111111 11111111 11111101 * }}} */ def >>>(x: Int): Int = value >>> x /** * Returns this value bit-shifted right by the specified number of bits, * filling the new left bits with zeroes. * @example {{{ 21 >>> 3 == 2 // in binary: 010101 >>> 3 == 010 }}} * @example {{{ * -21 >>> 3 == 536870909 * // in binary: 11111111 11111111 11111111 11101011 >>> 3 == * // 00011111 11111111 11111111 11111101 * }}} */ def >>>(x: Long): Int = value >>> x /** * Returns this value bit-shifted left by the specified number of bits, * filling in the right bits with the same value as the left-most bit of this. * The effect of this is to retain the sign of the value. * @example {{{ * -21 >> 3 == -3 * // in binary: 11111111 11111111 11111111 11101011 >> 3 == * // 11111111 11111111 11111111 11111101 * }}} */ def >>(x: Int): Int = value >> x /** * Returns this value bit-shifted left by the specified number of bits, * filling in the right bits with the same value as the left-most bit of this. * The effect of this is to retain the sign of the value. * @example {{{ * -21 >> 3 == -3 * // in binary: 11111111 11111111 11111111 11101011 >> 3 == * // 11111111 11111111 11111111 11111101 * }}} */ def >>(x: Long): Int = value >> x /** Returns `true` if this value is less than x, `false` otherwise. */ def <(x: Byte): Boolean = value < x /** Returns `true` if this value is less than x, `false` otherwise. */ def <(x: Short): Boolean = value < x /** Returns `true` if this value is less than x, `false` otherwise. */ def <(x: Char): Boolean = value < x /** Returns `true` if this value is less than x, `false` otherwise. */ def <(x: Int): Boolean = value < x /** Returns `true` if this value is less than x, `false` otherwise. */ def <(x: Long): Boolean = value < x /** Returns `true` if this value is less than x, `false` otherwise. */ def <(x: Float): Boolean = value < x /** Returns `true` if this value is less than x, `false` otherwise. */ def <(x: Double): Boolean = value < x /** Returns `true` if this value is less than or equal to x, `false` otherwise. */ def <=(x: Byte): Boolean = value <= x /** Returns `true` if this value is less than or equal to x, `false` otherwise. */ def <=(x: Short): Boolean = value <= x /** Returns `true` if this value is less than or equal to x, `false` otherwise. */ def <=(x: Char): Boolean = value <= x /** Returns `true` if this value is less than or equal to x, `false` otherwise. */ def <=(x: Int): Boolean = value <= x /** Returns `true` if this value is less than or equal to x, `false` otherwise. */ def <=(x: Long): Boolean = value <= x /** Returns `true` if this value is less than or equal to x, `false` otherwise. */ def <=(x: Float): Boolean = value <= x /** Returns `true` if this value is less than or equal to x, `false` otherwise. */ def <=(x: Double): Boolean = value <= x /** Returns `true` if this value is greater than x, `false` otherwise. */ def >(x: Byte): Boolean = value > x /** Returns `true` if this value is greater than x, `false` otherwise. */ def >(x: Short): Boolean = value > x /** Returns `true` if this value is greater than x, `false` otherwise. */ def >(x: Char): Boolean = value > x /** Returns `true` if this value is greater than x, `false` otherwise. */ def >(x: Int): Boolean = value > x /** Returns `true` if this value is greater than x, `false` otherwise. */ def >(x: Long): Boolean = value > x /** Returns `true` if this value is greater than x, `false` otherwise. */ def >(x: Float): Boolean = value > x /** Returns `true` if this value is greater than x, `false` otherwise. */ def >(x: Double): Boolean = value > x /** Returns `true` if this value is greater than or equal to x, `false` otherwise. */ def >=(x: Byte): Boolean = value >= x /** Returns `true` if this value is greater than or equal to x, `false` otherwise. */ def >=(x: Short): Boolean = value >= x /** Returns `true` if this value is greater than or equal to x, `false` otherwise. */ def >=(x: Char): Boolean = value >= x /** Returns `true` if this value is greater than or equal to x, `false` otherwise. */ def >=(x: Int): Boolean = value >= x /** Returns `true` if this value is greater than or equal to x, `false` otherwise. */ def >=(x: Long): Boolean = value >= x /** Returns `true` if this value is greater than or equal to x, `false` otherwise. */ def >=(x: Float): Boolean = value >= x /** Returns `true` if this value is greater than or equal to x, `false` otherwise. */ def >=(x: Double): Boolean = value >= x /** * Returns the bitwise OR of this value and `x`. * @example {{{ * (0xf0 | 0xaa) == 0xfa * // in binary: 11110000 * // | 10101010 * // -------- * // 11111010 * }}} */ def |(x: Byte): Int = value | x /** * Returns the bitwise OR of this value and `x`. * @example {{{ * (0xf0 | 0xaa) == 0xfa * // in binary: 11110000 * // | 10101010 * // -------- * // 11111010 * }}} */ def |(x: Short): Int = value | x /** * Returns the bitwise OR of this value and `x`. * @example {{{ * (0xf0 | 0xaa) == 0xfa * // in binary: 11110000 * // | 10101010 * // -------- * // 11111010 * }}} */ def |(x: Char): Int = value | x /** * Returns the bitwise OR of this value and `x`. * @example {{{ * (0xf0 | 0xaa) == 0xfa * // in binary: 11110000 * // | 10101010 * // -------- * // 11111010 * }}} */ def |(x: Int): Int = value | x /** * Returns the bitwise OR of this value and `x`. * @example {{{ * (0xf0 | 0xaa) == 0xfa * // in binary: 11110000 * // | 10101010 * // -------- * // 11111010 * }}} */ def |(x: Long): Long = value | x /** * Returns the bitwise AND of this value and `x`. * @example {{{ * (0xf0 & 0xaa) == 0xa0 * // in binary: 11110000 * // & 10101010 * // -------- * // 10100000 * }}} */ def &(x: Byte): Int = value & x /** * Returns the bitwise AND of this value and `x`. * @example {{{ * (0xf0 & 0xaa) == 0xa0 * // in binary: 11110000 * // & 10101010 * // -------- * // 10100000 * }}} */ def &(x: Short): Int = value & x /** * Returns the bitwise AND of this value and `x`. * @example {{{ * (0xf0 & 0xaa) == 0xa0 * // in binary: 11110000 * // & 10101010 * // -------- * // 10100000 * }}} */ def &(x: Char): Int = value & x /** * Returns the bitwise AND of this value and `x`. * @example {{{ * (0xf0 & 0xaa) == 0xa0 * // in binary: 11110000 * // & 10101010 * // -------- * // 10100000 * }}} */ def &(x: Int): Int = value & x /** * Returns the bitwise AND of this value and `x`. * @example {{{ * (0xf0 & 0xaa) == 0xa0 * // in binary: 11110000 * // & 10101010 * // -------- * // 10100000 * }}} */ def &(x: Long): Long = value & x /** * Returns the bitwise XOR of this value and `x`. * @example {{{ * (0xf0 ^ 0xaa) == 0x5a * // in binary: 11110000 * // ^ 10101010 * // -------- * // 01011010 * }}} */ def ^(x: Byte): Int = value ^ x /** * Returns the bitwise XOR of this value and `x`. * @example {{{ * (0xf0 ^ 0xaa) == 0x5a * // in binary: 11110000 * // ^ 10101010 * // -------- * // 01011010 * }}} */ def ^(x: Short): Int = value ^ x /** * Returns the bitwise XOR of this value and `x`. * @example {{{ * (0xf0 ^ 0xaa) == 0x5a * // in binary: 11110000 * // ^ 10101010 * // -------- * // 01011010 * }}} */ def ^(x: Char): Int = value ^ x /** * Returns the bitwise XOR of this value and `x`. * @example {{{ * (0xf0 ^ 0xaa) == 0x5a * // in binary: 11110000 * // ^ 10101010 * // -------- * // 01011010 * }}} */ def ^(x: Int): Int = value ^ x /** * Returns the bitwise XOR of this value and `x`. * @example {{{ * (0xf0 ^ 0xaa) == 0x5a * // in binary: 11110000 * // ^ 10101010 * // -------- * // 01011010 * }}} */ def ^(x: Long): Long = value ^ x /** Returns the sum of this value and `x`. */ def +(x: Byte): Int = value + x /** Returns the sum of this value and `x`. */ def +(x: Short): Int = value + x /** Returns the sum of this value and `x`. */ def +(x: Char): Int = value + x /** Returns the sum of this value and `x`. */ def +(x: Int): Int = value + x /** Returns the sum of this value and `x`. */ def +(x: Long): Long = value + x /** Returns the sum of this value and `x`. */ def +(x: Float): Float = value + x /** Returns the sum of this value and `x`. */ def +(x: Double): Double = value + x /** Returns the difference of this value and `x`. */ def -(x: Byte): Int = value - x /** Returns the difference of this value and `x`. */ def -(x: Short): Int = value - x /** Returns the difference of this value and `x`. */ def -(x: Char): Int = value - x /** Returns the difference of this value and `x`. */ def -(x: Int): Int = value - x /** Returns the difference of this value and `x`. */ def -(x: Long): Long = value - x /** Returns the difference of this value and `x`. */ def -(x: Float): Float = value - x /** Returns the difference of this value and `x`. */ def -(x: Double): Double = value - x /** Returns the product of this value and `x`. */ def *(x: Byte): Int = value * x /** Returns the product of this value and `x`. */ def *(x: Short): Int = value * x /** Returns the product of this value and `x`. */ def *(x: Char): Int = value * x /** Returns the product of this value and `x`. */ def *(x: Int): Int = value * x /** Returns the product of this value and `x`. */ def *(x: Long): Long = value * x /** Returns the product of this value and `x`. */ def *(x: Float): Float = value * x /** Returns the product of this value and `x`. */ def *(x: Double): Double = value * x /** Returns the quotient of this value and `x`. */ def /(x: Byte): Int = value / x /** Returns the quotient of this value and `x`. */ def /(x: Short): Int = value / x /** Returns the quotient of this value and `x`. */ def /(x: Char): Int = value / x /** Returns the quotient of this value and `x`. */ def /(x: Int): Int = value / x /** Returns the quotient of this value and `x`. */ def /(x: Long): Long = value / x /** Returns the quotient of this value and `x`. */ def /(x: Float): Float = value / x /** Returns the quotient of this value and `x`. */ def /(x: Double): Double = value / x /** Returns the remainder of the division of this value by `x`. */ def %(x: Byte): Int = value % x /** Returns the remainder of the division of this value by `x`. */ def %(x: Short): Int = value % x /** Returns the remainder of the division of this value by `x`. */ def %(x: Char): Int = value % x /** Returns the remainder of the division of this value by `x`. */ def %(x: Int): Int = value % x /** Returns the remainder of the division of this value by `x`. */ def %(x: Long): Long = value % x /** Returns the remainder of the division of this value by `x`. */ def %(x: Float): Float = value % x /** Returns the remainder of the division of this value by `x`. */ def %(x: Double): Double = value % x // Stuff from RichInt: /** * Returns a string representation of this NonZeroInt's underlying Int as an * unsigned integer in base 2. * *

* The unsigned integer value is the argument plus 232 * if this NonZeroInt's underlying Int is negative; otherwise it is equal to the * underlying Int. This value is converted to a string of ASCII digits * in binary (base 2) with no extra leading 0s. * If the unsigned magnitude is zero, it is represented by a * single zero character '0' * ('\u0030'); otherwise, the first character of * the representation of the unsigned magnitude will not be the * zero character. The characters '0' * ('\u0030') and '1' * ('\u0031') are used as binary digits. *

* * @return the string representation of the unsigned integer value * represented by this NonZeroInt's underlying Int in binary (base 2). */ def toBinaryString: String = java.lang.Integer.toBinaryString(value) /** * Returns a string representation of this NonZeroInt's underlying Int as an * unsigned integer in base 16. * *

* The unsigned integer value is the argument plus 232 * if this NonZeroInt's underlying Int is negative; otherwise, it is equal to the * this NonZeroInt's underlying Int This value is converted to a string of ASCII digits * in hexadecimal (base 16) with no extra leading * 0s. If the unsigned magnitude is zero, it is * represented by a single zero character '0' * ('\u0030'); otherwise, the first character of * the representation of the unsigned magnitude will not be the * zero character. The following characters are used as * hexadecimal digits: *

* *
* 0123456789abcdef *
* * These are the characters '\u0030' through * '\u0039' and '\u0061' through * '\u0066'. If uppercase letters are * desired, the toUpperCase method may * be called on the result. * * @return the string representation of the unsigned integer value * represented by this NonZeroInt's underlying Int in hexadecimal (base 16). */ def toHexString: String = java.lang.Integer.toHexString(value) /** * Returns a string representation of this NonZeroInt's underlying Int as an * unsigned integer in base 8. * *

The unsigned integer value is this NonZeroInt's underlying Int plus 232 * if the underlying Int is negative; otherwise, it is equal to the * underlying Int. This value is converted to a string of ASCII digits * in octal (base 8) with no extra leading 0s. * *

If the unsigned magnitude is zero, it is represented by a * single zero character '0' * ('\u0030'); otherwise, the first character of * the representation of the unsigned magnitude will not be the * zero character. The following characters are used as octal * digits: * *

* 01234567 *
* * These are the characters '\u0030' through * '\u0037'. * * @return the string representation of the unsigned integer value * represented by this NonZeroInt's underlying Int in octal (base 8). */ def toOctalString: String = java.lang.Integer.toOctalString(value) /** * Create a Range from this NonZeroInt value * until the specified end (exclusive) with step value 1. * * @param end The final bound of the range to make. * @return A [[scala.collection.immutable.Range]] from `this` up to but * not including `end`. */ def until(end: Int): Range = Range(value, end) /** * Create a Range from this NonZeroInt value * until the specified end (exclusive) with the specified step value. * * @param end The final bound of the range to make. * @param step The number to increase by for each step of the range. * @return A [[scala.collection.immutable.Range]] from `this` up to but * not including `end`. */ def until(end: Int, step: Int): Range = Range(value, end, step) /** * Create an inclusive Range from this NonZeroInt value * to the specified end with step value 1. * * @param end The final bound of the range to make. * @return A [[scala.collection.immutable.Range]] from `'''this'''` up to * and including `end`. */ def to(end: Int): Range.Inclusive = Range.inclusive(value, end) /** * Create an inclusive Range from this NonZeroInt value * to the specified end with the specified step value. * * @param end The final bound of the range to make. * @param step The number to increase by for each step of the range. * @return A [[scala.collection.immutable.Range]] from `'''this'''` up to * and including `end`. */ def to(end: Int, step: Int): Range.Inclusive = Range.inclusive(value, end, step) /** * Returns this if this > that or that otherwise. */ def max(that: NonZeroInt): NonZeroInt = if (math.max(value, that.value) == value) this else that /** * Returns this if this < that or that otherwise. */ def min(that: NonZeroInt): NonZeroInt = if (math.min(value, that.value) == value) this else that /** * Applies the passed Int => Int function to the underlying Int * value, and if the result is positive, returns the result wrapped in a NonZeroInt, * else throws AssertionError. * * A factory/assertion method that produces a PosInt given a * valid Int value, or throws AssertionError, * if given an invalid Int value. * * Note: you should use this method only when you are convinced that it will * always succeed, i.e., never throw an exception. It is good practice to * add a comment near the invocation of this method indicating ''why'' you think * it will always succeed to document your reasoning. If you are not sure an * `ensuringValid` call will always succeed, you should use one of the other * factory or validation methods provided on this object instead: `isValid`, * `tryingValid`, `passOrElse`, `goodOrElse`, or `rightOrElse`. * *

* This method will inspect the result of applying the given function to this * NonZeroInt's underlying Int value and if the result * is non-zero, it will return a NonZeroInt representing that value. * Otherwise, the Int value returned by the given function is * not non-zero, so this method will throw AssertionError. *

* *

* This method differs from a vanilla assert or ensuring * call in that you get something you didn't already have if the assertion * succeeds: a type that promises an Int is non-zero. * With this method, you are asserting that you are convinced the result of * the computation represented by applying the given function to this NonZeroInt's * value will not overflow. Instead of overflowing silently like Int, this * method will signal an overflow with a loud AssertionError. *

* * @param f the Int => Int function to apply to this NonZeroInt's * underlying Int value. * @return the result of applying this NonZeroInt's underlying Int value to * to the passed function, wrapped in a NonZeroInt if it is non-zero (else throws AssertionError). * @throws AssertionError if the result of applying this NonZeroInt's underlying Int value to * to the passed function is not non-zero. */ def ensuringValid(f: Int => Int): NonZeroInt = { val candidateResult: Int = f(value) if (NonZeroIntMacro.isValid(candidateResult)) new NonZeroInt(candidateResult) else throw new AssertionError(s"${candidateResult.toString()}, the result of applying the passed function to ${value.toString()}, was not a valid NonZeroInt") } } /** * The companion object for NonZeroInt that offers factory methods that * produce NonZeroInts, implicit widening conversions from NonZeroInt * to other numeric types, and maximum and minimum constant values for NonZeroInt. */ object NonZeroInt { /** * The largest value representable as a non-zero Int, which is NonZeroInt(2147483647). */ final val MaxValue: NonZeroInt = NonZeroInt.ensuringValid(Int.MaxValue) /** * The smallest value representable as a non-zero Int, which is NonZeroInt(-2147483648). */ final val MinValue: NonZeroInt = NonZeroInt.ensuringValid(Int.MinValue) // Can't use the macro here /** * A factory method that produces an Option[NonZeroInt] given an * Int value. * *

* This method will inspect the passed Int value and if * it is a non-zero Int, i.e., a non-zero integer value, * it will return a NonZeroInt representing that value, * wrapped in a Some. Otherwise, the passed Int * value is not non-zero integer value, so this method will return None. *

* *

* This factory method differs from the apply factory method * in that apply is implemented via a macro that inspects * Int literals at compile time, whereas from inspects * Int values at run time. *

* * @param value the Int to inspect, and if non-zero, return * wrapped in a Some[NonZeroInt]. * @return the specified Int value wrapped * in a Some[NonZeroInt], if it is non-zero, else None. */ def from(value: Int): Option[NonZeroInt] = if (NonZeroIntMacro.isValid(value)) Some(new NonZeroInt(value)) else None /** * A factory/assertion method that produces a NonZeroInt given a * valid Int value, or throws AssertionError, * if given an invalid Int value. * * Note: you should use this method only when you are convinced that it will * always succeed, i.e., never throw an exception. It is good practice to * add a comment near the invocation of this method indicating ''why'' you think * it will always succeed to document your reasoning. If you are not sure an * `ensuringValid` call will always succeed, you should use one of the other * factory or validation methods provided on this object instead: `isValid`, * `tryingValid`, `passOrElse`, `goodOrElse`, or `rightOrElse`. * *

* This method will inspect the passed Int value and if * it is a non-zero Int, it will return a NonZeroInt * representing that value. Otherwise, the passed Int value is not non-zero, so this * method will throw AssertionError. *

* *

* This factory method differs from the apply factory method * in that apply is implemented via a macro that inspects * Int literals at compile time, whereas this method inspects * Int values at run time. * It differs from a vanilla assert or ensuring * call in that you get something you didn't already have if the assertion * succeeds: a type that promises an Int is non-zero. *

* * @param value the Int to inspect, and if non-zero, return * wrapped in a NonZeroInt. * @return the specified Int value wrapped * in a NonZeroInt, if it is non-zero, else throws AssertionError. * @throws AssertionError if the passed value is not non-zero */ def ensuringValid(value: Int): NonZeroInt = if (NonZeroIntMacro.isValid(value)) new NonZeroInt(value) else { throw new AssertionError(s"${value.toString()} was not a valid NonZeroInt") } /** * A factory/validation method that produces a NonZeroInt, wrapped * in a Success, given a valid Int value, or if the * given Int is invalid, an AssertionError, wrapped * in a Failure. * *

* This method will inspect the passed Int value and if * it is a non-zero Int, it will return a NonZeroInt * representing that value, wrapped in a Success. * Otherwise, the passed Int value is not non-zero, so this * method will return an AssertionError, wrapped in a Failure. *

* *

* This factory method differs from the apply factory method * in that apply is implemented via a macro that inspects * Int literals at compile time, whereas this method inspects * Int values at run time. *

* * @param value the Int to inspect, and if non-zero, return * wrapped in a Success(NonZeroInt). * @return the specified Int value wrapped * in a Success(NonZeroInt), if it is non-zero, else a Failure(AssertionError). */ def tryingValid(value: Int): Try[NonZeroInt] = if (NonZeroIntMacro.isValid(value)) Success(new NonZeroInt(value)) else Failure(new AssertionError(s"${value.toString()} was not a valid NonZeroInt")) /** * A validation method that produces a Pass * given a valid Int value, or * an error value of type E produced by passing the * given invalid Int value * to the given function f, wrapped in a Fail. * *

* This method will inspect the passed Int value and if * it is a non-zero Int, it will return a Pass. * Otherwise, the passed Int value is non-zero, so this * method will return a result of type E obtained by passing * the invalid Int value to the given function f, * wrapped in a `Fail`. *

* *

* This factory method differs from the apply factory method * in that apply is implemented via a macro that inspects * Int literals at compile time, whereas this method inspects * Int values at run time. *

* * @param value the `Int` to validate that it is non-zero. * @return a `Pass` if the specified `Int` value is non-zero, * else a `Fail` containing an error value produced by passing the * specified `Int` to the given function `f`. */ def passOrElse[E](value: Int)(f: Int => E): Validation[E] = if (NonZeroIntMacro.isValid(value)) Pass else Fail(f(value)) /** * A factory/validation method that produces a NonZeroInt, wrapped * in a Good, given a valid Int value, or if the * given Int is invalid, an error value of type B * produced by passing the given invalid Int value * to the given function f, wrapped in a Bad. * *

* This method will inspect the passed Int value and if * it is a non-zero Int, it will return a NonZeroInt * representing that value, wrapped in a Good. * Otherwise, the passed Int value is not non-zero, so this * method will return a result of type B obtained by passing * the invalid Int value to the given function f, * wrapped in a `Bad`. *

* *

* This factory method differs from the apply factory method * in that apply is implemented via a macro that inspects * Int literals at compile time, whereas this method inspects * Int values at run time. *

* * @param value the Int to inspect, and if non-zero, return * wrapped in a Good(NonZeroInt). * @return the specified Int value wrapped * in a Good(NonZeroInt), if it is non-zero, else a Bad(f(value)). */ def goodOrElse[B](value: Int)(f: Int => B): NonZeroInt Or B = if (NonZeroIntMacro.isValid(value)) Good(NonZeroInt.ensuringValid(value)) else Bad(f(value)) /** * A factory/validation method that produces a NonZeroInt, wrapped * in a Right, given a valid Int value, or if the * given Int is invalid, an error value of type L * produced by passing the given invalid Int value * to the given function f, wrapped in a Left. * *

* This method will inspect the passed Int value and if * it is a non-zero Int, it will return a NonZeroInt * representing that value, wrapped in a Right. * Otherwise, the passed Int value is not non-zero, so this * method will return a result of type L obtained by passing * the invalid Int value to the given function f, * wrapped in a `Left`. *

* *

* This factory method differs from the apply factory method * in that apply is implemented via a macro that inspects * Int literals at compile time, whereas this method inspects * Int values at run time. *

* * @param value the Int to inspect, and if non-zero, return * wrapped in a Right(NonZeroInt). * @return the specified Int value wrapped * in a Right(NonZeroInt), if it is non-zero, else a Left(f(value)). */ def rightOrElse[L](value: Int)(f: Int => L): Either[L, NonZeroInt] = if (NonZeroIntMacro.isValid(value)) Right(NonZeroInt.ensuringValid(value)) else Left(f(value)) /** * A predicate method that returns true if a given * Int value is non-zero. * * @param value the Int to inspect, and if non-zero, return true. * @return true if the specified Int is non-zero, else false. */ def isValid(value: Int): Boolean = NonZeroIntMacro.isValid(value) /** * A factory method that produces a NonZeroInt given a * Int value and a default NonZeroInt. * *

* This method will inspect the passed Int value and if * it is a positive Int, i.e., a value greater * than 0.0, it will return a NonZeroInt representing that value. * Otherwise, the passed Int value is 0 or negative, so this * method will return the passed default value. *

* *

* This factory method differs from the apply * factory method in that apply is implemented * via a macro that inspects Int literals at * compile time, whereas from inspects * Int values at run time. *

* * @param value the Int to inspect, and if positive, return. * @param default the NonZeroInt to return if the passed * Int value is not positive. * @return the specified Int value wrapped in a * NonZeroInt, if it is positive, else the * default NonZeroInt value. */ def fromOrElse(value: Int, default: => NonZeroInt): NonZeroInt = if (NonZeroIntMacro.isValid(value)) new NonZeroInt(value) else default import language.experimental.macros /** * A factory method, implemented via a macro, that produces a NonZeroInt * if passed a valid Int literal, otherwise a compile time error. * *

* The macro that implements this method will inspect the specified Int * expression at compile time. If * the expression is a positive Int literal, i.e., with a * value greater than 0, it will return a NonZeroInt representing that value. * Otherwise, the passed Int * expression is either a literal that is 0 or negative, or is not a literal, so * this method will give a compiler error. *

* *

* This factory method differs from the from factory method * in that this method is implemented via a macro that inspects * Int literals at compile time, whereas from inspects * Int values at run time. *

* * @param value the Int literal expression to inspect at compile time, * and if positive, to return wrapped in a NonZeroInt at run time. * @return the specified, valid Int literal value wrapped * in a NonZeroInt. (If the specified expression is not a valid * Int literal, the invocation of this method will not * compile.) */ inline implicit def apply(value: => Int): NonZeroInt = ${ NonZeroIntMacro('{value}) } /** * Implicit widening conversion from NonZeroInt to Int. * * @param pos the NonZeroInt to widen * @return the Int value underlying the specified NonZeroInt. */ implicit def widenToInt(pos: NonZeroInt): Int = pos.value /** * Implicit widening conversion from NonZeroInt to Long. * * @param pos the NonZeroInt to widen * @return the Int value underlying the specified NonZeroInt, * widened to Long. */ implicit def widenToLong(pos: NonZeroInt): Long = pos.value /** * Implicit widening conversion from NonZeroInt to Float. * * @param pos the NonZeroInt to widen * @return the Int value underlying the specified NonZeroInt, * widened to Float. */ implicit def widenToFloat(pos: NonZeroInt): Float = pos.value /** * Implicit widening conversion from NonZeroInt to Double. * * @param pos the NonZeroInt to widen * @return the Int value underlying the specified NonZeroInt, * widened to Double. */ implicit def widenToDouble(pos: NonZeroInt): Double = pos.value /** * Implicit widening conversion from NonZeroInt to NonZeroLong. * * @param pos the NonZeroInt to widen * @return the Int value underlying the specified NonZeroInt, * widened to Long and wrapped in a NonZeroLong. */ implicit def widenToNonZeroLong(pos: NonZeroInt): NonZeroLong = NonZeroLong.ensuringValid(pos.value) /** * Implicit widening conversion from NonZeroInt to NonZeroFloat. * * @param pos the NonZeroInt to widen * @return the Int value underlying the specified NonZeroInt, * widened to Float and wrapped in a NonZeroFloat. */ implicit def widenToNonZeroFloat(pos: NonZeroInt): NonZeroFloat = NonZeroFloat.ensuringValid(pos.value) /** * Implicit widening conversion from NonZeroInt to NonZeroDouble. * * @param pos the NonZeroInt to widen * @return the Int value underlying the specified NonZeroInt, * widened to Double and wrapped in a NonZeroDouble. */ implicit def widenToNonZeroDouble(pos: NonZeroInt): NonZeroDouble = NonZeroDouble.ensuringValid(pos.value) /** * Implicit Ordering instance. */ implicit val ordering: Ordering[NonZeroInt] = new Ordering[NonZeroInt] { def compare(x: NonZeroInt, y: NonZeroInt): Int = x.toInt.compare(y) } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy