/*--------------------------------------------------------------------------

TypeBox

The MIT License (MIT)

Copyright (c) 2017-2026 Haydn Paterson

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

---------------------------------------------------------------------------*/

// ------------------------------------------------------------------
// Ranged Fast Path
// ------------------------------------------------------------------
/* Returns true if the value is a IPV4 address from index range offsets */
export function IsIPv4Internal(value: string, start: number, end: number): boolean {
  let dots = 0
  let num = 0
  let digits = 0
  let leading = 0
  for (let i = start; i < end; i++) {
    const ch = value.charCodeAt(i)
    if (ch === 46) { // '.'
      if (digits === 0 || num > 255 || (leading === 48 && digits > 1)) return false
      dots++
      num = 0
      digits = 0
      leading = 0
    } else if (ch >= 48 && ch <= 57) { // '0'-'9'
      if (digits === 0) leading = ch
      num = num * 10 + (ch - 48)
      digits++
    } else {
      return false
    }
  }
  return dots === 3 && digits > 0 && num <= 255 && !(leading === 48 && digits > 1)
}
/**
 * Returns true if the value is a IPV4 address
 * @specification http://tools.ietf.org/html/rfc2673#section-3.2
 */
export function IsIPv4(value: string): boolean {
  return IsIPv4Internal(value, 0, value.length)
}
