package jsontext

import (
	
	
	
)

// Pointer is a JSON Pointer (RFC 6901), which references a JSON value relative to the root of the top-level
// JSON value.
//
// It is a list of tokens, each after a slash: a JSON object name, or the index of a JSON array element as a
// base-10 integer. An array index and an object name which is an integer can't be told apart without the
// structure of the value which the pointer refers to.
//
// A value has exactly one pointer, so two pointers are equal if and only if they point to the same value.
type Pointer string

// IsValid reports whether p is a valid JSON Pointer of RFC 6901. The concatenation of two valid pointers is a
// valid pointer.
func ( Pointer) () bool {
	if  != "" && [0] != '/' {
		return false
	}
	for  := 0;  < len(); ++ {
		if [] == '~' && (+1 == len() || [+1] != '0' && [+1] != '1') {
			return false
		}
	}
	return utf8.ValidString(string())
}

// Contains reports whether the JSON value which p points to is the one which pc points to or contains it.
func ( Pointer) ( Pointer) bool {
	return strings.HasPrefix(string(), string()) && (len() == len() || [len()] == '/')
}

// Parent returns p without its last token. The parent of the empty pointer is the empty pointer.
func ( Pointer) () Pointer {
	return [:max(strings.LastIndexByte(string(), '/'), 0)]
}

// LastToken returns the last token of p. The last token of the empty pointer is the empty string.
func ( Pointer) () string {
	 := [max(strings.LastIndexByte(string(), '/'), 0):]
	return unescapePointerToken(strings.TrimPrefix(string(), "/"))
}

// AppendToken appends the token tok to p and returns the pointer.
func ( Pointer) ( string) Pointer {
	if !utf8.ValidString() {
		 = string(appendValidUTF8(nil, ))
	}
	return Pointer(appendPointerToken([]byte(), ))
}

// appendValidUTF8 appends s, whose each byte of invalid UTF-8 is U+FFFD.
func appendValidUTF8[ ~[]byte | ~string]( []byte,  ) []byte {
	for  := 0;  < len(); {
		,  := utf8.DecodeRuneInString(string([:min(+utf8.UTFMax, len())]))
		if  == utf8.RuneError &&  == 1 {
			 = append(, "�"...)
		} else {
			 = append(, [:+]...)
		}
		 += 
	}
	return 
}

// Tokens returns an iterator over the tokens of p, from the first to the last.
func ( Pointer) () iter.Seq[string] {
	return func( func(string) bool) {
		for  := string();  != ""; {
			 = strings.TrimPrefix(, "/")
			 := strings.IndexByte(, '/')
			if  < 0 {
				 = len()
			}
			if !(unescapePointerToken([:])) {
				return
			}
			 = [:]
		}
	}
}

// appendPointerToken appends a slash and the token, whose '~' and '/' are escaped as "~0" and "~1".
func appendPointerToken[ ~[]byte | ~string]( []byte,  ) []byte {
	 = append(, '/')
	for  := 0;  < len(); ++ {
		switch [] {
		case '~':
			 = append(, "~0"...)
		case '/':
			 = append(, "~1"...)
		default:
			 = append(, [])
		}
	}
	return 
}

func unescapePointerToken( string) string {
	if !strings.Contains(, "~") {
		return 
	}
	return strings.NewReplacer("~1", "/", "~0", "~").Replace()
}