Documentation
¶
Overview ¶
Author: L6 / #1665 lane (Codex gpt-6.1-sol). Keep public numeric text at the existing kind and FLOAT-spelling owners.
Package convert provides type conversion utilities for NornicDB.
This package consolidates type conversion functions used throughout the codebase, ensuring consistent behavior for numeric conversions, slice transformations, and string parsing.
Key Functions:
- ToFloat64: Convert various types to float64
- ToInt64: Convert various types to int64
- ToFloat64Slice: Convert slices to []float64
- ToFloat32Slice: Convert slices to []float32
All conversion functions return a success boolean to allow callers to handle conversion failures gracefully.
Example:
// Convert any numeric type to float64
if f, ok := convert.ToFloat64(someValue); ok {
// Use f
}
// Convert slice to []float32 for vector operations
floats := convert.ToFloat32Slice(data)
if floats != nil {
// Use floats
}
ELI12:
This package is like a universal translator for numbers. You give it any kind of number (whole number, decimal, even text that looks like a number), and it converts it to the type you need. If it can't convert something (like "hello"), it tells you by returning false or nil.
Index ¶
- Constants
- Variables
- func AppendBoltFloat(dst []byte, value float64) []byte
- func AppendBoltInteger(dst []byte, value int64) []byte
- func AppendBoltNumber(dst []byte, value interface{}) ([]byte, bool)
- func AppendBoltUnsigned(dst []byte, value uint64) []byte
- func AppendFloatEquivalenceKey(dst []byte, number float64) []byte
- func AppendIntegerEquivalenceKey(dst []byte, number int64) []byte
- func AppendNumericText(dst []byte, value interface{}) ([]byte, bool)
- func AppendUnsignedEquivalenceKey(dst []byte, number uint64) []byte
- func DecodeBoltNumber(data []byte) (value interface{}, size int, recognized bool, err error)
- func FloatEquivalenceKey(number float64) string
- func FloatValue(value interface{}) (float64, bool)
- func FormatFloat(value float64, bits int) string
- func Int64(value interface{}, policy IntegerPolicy) (int64, bool)
- func Int64Bits(value interface{}, bits int, policy IntegerPolicy) (int64, bool)
- func IntegerEquivalenceKey(number int64) string
- func IntegerValue(value interface{}) (int64, bool)
- func IsInteger(value interface{}) bool
- func ListValue(value interface{}) ([]interface{}, bool)
- func NativeScalar(value interface{}) bool
- func NextNaNKey() uint64
- func NumericFloat64(value interface{}) (float64, bool)
- func NumericFloat64Slice(value interface{}) ([]float64, bool)
- func NumericText(value interface{}) (string, bool)
- func SignedInteger(value interface{}) (int64, bool)
- func ToFloat32Slice(v interface{}) []float32
- func ToFloat64(v interface{}) (float64, bool)
- func ToFloat64Slice(v interface{}) ([]float64, bool)
- func ToInt(value interface{}, policy IntegerPolicy) (int, bool)
- func ToInt64(v interface{}) (int64, bool)
- func ToStringSlice(v interface{}) []string
- func ToUint64(value interface{}, policy IntegerPolicy) (uint64, bool)
- func UnsignedEquivalenceKey(number uint64) string
- func UnsignedInteger(value interface{}) (uint64, bool)
- type IntegerPolicy
- type JSONEncoder
- type List
- type Number
- func (number Number) Float() (float64, bool)
- func (number Number) Float32() (float32, bool)
- func (number Number) Float64() float64
- func (number Number) Int64(policy IntegerPolicy) (int64, bool)
- func (number Number) Int64Bits(bits int, policy IntegerPolicy) (int64, bool)
- func (number Number) IsInteger() bool
- func (number Number) Kind() NumberKind
- func (number Number) Signed() (int64, bool)
- func (number Number) Uint64(policy IntegerPolicy) (uint64, bool)
- func (number Number) Uint64Bits(bits int, policy IntegerPolicy) (uint64, bool)
- func (number Number) Unsigned() (uint64, bool)
- type NumberKind
- type NumberListIssue
- type OrderedJSONMap
- type UnsupportedNumberError
Constants ¶
const CypherIntegerConversion = IntegerFloat | IntegerSaturate | IntegerStrings | IntegerDecimalStrings | IntegerBool | IntegerTrimStrings
CypherIntegerConversion follows numeric toInteger/toIntegerList: a floating value saturates (NaN is zero); a string must fit after exact decimal truncation.
Variables ¶
var CypherInputJSON cypherInputJSONDomain
CypherInputJSON owns external Cypher values: parameters, request bodies, explicit fromJson conversions and load.json. It has one number policy, Neo4j 5.26's: an integer outside the 64-bit range is rejected (UnsupportedNumberError) and an out-of-range FLOAT reads as +/-Infinity. It is a different type from PropertyJSON; no policy argument, generic decoder constructor or mutable policy is exposed to callers.
var PropertyJSON propertyJSONDomain
PropertyJSON owns existing graph data: exports, imports, backups, document transforms, result properties, recovery and replication fallbacks. INTEGER retains the complete int64/uint64 domain. It never falls back to FLOAT. Every production entry point is bound to its domain in json_data_paths.json.
Functions ¶
func AppendBoltFloat ¶
func AppendBoltInteger ¶
func AppendBoltNumber ¶
AppendBoltNumber writes the same numeric kinds as the JSON codec. PackStream has signed INTEGER and FLOAT, but no unsigned integer. NornicDB's native unsigned extension above MaxInt64 therefore travels as an exact decimal STRING. It must never wrap to a negative INTEGER or round to FLOAT.
func AppendBoltUnsigned ¶
AppendBoltUnsigned owns the unsigned protocol boundary for both typed scalar dispatch and reflective numeric values. Signed and FLOAT leaves need no unsigned range check or intermediate Number carrier.
func AppendFloatEquivalenceKey ¶
AppendFloatEquivalenceKey appends a float's equivalence key.
func AppendIntegerEquivalenceKey ¶
AppendIntegerEquivalenceKey appends a signed integer's equivalence key.
func AppendNumericText ¶
AppendNumericText appends the same INTEGER or FLOAT token as NumericText to dst, without allocating an intermediate string for a surrounding document. It leaves dst unchanged and returns false for a non-numeric value. For example, AppendNumericText([]byte("value="), float64(2)) appends "2.0".
func AppendUnsignedEquivalenceKey ¶
AppendUnsignedEquivalenceKey appends an unsigned integer's equivalence key.
func DecodeBoltNumber ¶
DecodeBoltNumber recognizes a numeric prefix and reports bytes consumed. A recognized but truncated number is an error; other markers belong to the enclosing protocol decoder. This shares the numeric boundary with writers.
func FloatEquivalenceKey ¶
FloatEquivalenceKey is a float's equivalence key.
func FloatValue ¶
func FormatFloat ¶
FormatFloat writes a float as Neo4j does (Java's Double.toString): plain decimals with at least one fractional digit from 10^-3 up to 10^7 ("0.001", "9999999.0"), scientific notation with an upper-case E outside that range ("1.0E7", "1.23456789E-4"), and "Infinity", "-Infinity" and "NaN". bits is the value's precision (32 or 64), so a float32 keeps its shortest text. It is the one text of a float: toString(), point text and the HTTP API's numbers use it.
func Int64 ¶
func Int64(value interface{}, policy IntegerPolicy) (int64, bool)
Int64 is the checked narrowing owner. Unsigned overflow always fails. Floating overflow either fails or saturates according to policy, never a Go cast's platform-dependent result. Strings never use float64 as an integer intermediate.
func IntegerEquivalenceKey ¶
IntegerEquivalenceKey is a signed integer's equivalence key.
func IntegerValue ¶
IntegerValue recognizes integer kinds only and checks signed representability.
func ListValue ¶
func ListValue(value interface{}) ([]interface{}, bool)
ListValue is the boxed-list adapter of ReadList, shared by all collection and nested-list algorithms. It does not add another representation classifier.
func NativeScalar ¶
func NativeScalar(value interface{}) bool
NativeScalar reports whether value is nil or one of the native Go string, boolean or numeric property types. It neither coerces values nor admits named types, pointers, containers, uintptr or complex numbers. Callers whose policy excludes null must test that separately; nil remains a safe equality value.
For example, NativeScalar(int64(7)) is true, while NativeScalar([]int64{7}) is false.
func NumericFloat64 ¶
NumericFloat64 reads numbers only. It deliberately does not parse strings.
func NumericFloat64Slice ¶
NumericFloat64Slice uses the same list and numeric readers but rejects text. Vector/math callers retain their numeric-only argument contract.
func NumericText ¶
NumericText formats a runtime INTEGER or FLOAT without narrowing its value or erasing its numeric kind. INTEGERs keep exact decimal digits; FLOATs use FormatFloat, including a fractional token for whole values and negative zero. A float32 keeps its own shortest text. Non-numeric values are left to the caller's existing string, temporal or container representation.
For example, NumericText(int64(2)) returns "2", while NumericText(float64(2)) returns "2.0". It does not admit or coerce inputs.
func SignedInteger ¶
func ToFloat32Slice ¶
func ToFloat32Slice(v interface{}) []float32
ToFloat32Slice converts various slice types to []float32. Returns slice on success, nil on failure.
This is commonly used for converting data to embedding vector format, since most ML models use float32 vectors.
Supported types:
- []float32 (returned as-is)
- []float64 (each element converted)
- []interface{} (each element converted)
Example:
s := ToFloat32Slice([]interface{}{1, 2.5, 3}) // Returns [1.0, 2.5, 3.0]
s := ToFloat32Slice([]float64{1.0, 2.0}) // Returns [1.0, 2.0]
ELI12:
This converts a list of numbers to the format used by AI/ML models for vector embeddings. The result is more memory efficient than float64.
func ToFloat64 ¶
ToFloat64 converts various numeric types to float64. Returns (value, true) on success, (0, false) on failure.
This is the STANDARD conversion function for all numeric types. Use this instead of custom type switches throughout the codebase.
Supported types:
- float64 (returned as-is)
- float32 (converted)
- int, int32, int64 (lossless for values within float64 range)
- string (parsed as decimal, supports scientific notation)
String parsing supports:
- Decimal: "3.14", "-2.5"
- Scientific notation: "1.23e-4", "6.02e23"
- Special values: "NaN", "Inf", "-Inf"
Example 1 - Numeric types:
f, ok := ToFloat64(42) // Returns (42.0, true) f, ok := ToFloat64(int64(99)) // Returns (99.0, true) f, ok := ToFloat64(3.14) // Returns (3.14, true)
Example 2 - String parsing:
f, ok := ToFloat64("3.14") // Returns (3.14, true)
f, ok := ToFloat64("1.5e-3") // Returns (0.0015, true)
f, ok := ToFloat64("invalid") // Returns (0, false)
Example 3 - Error handling:
value := "user_input"
if f, ok := ToFloat64(value); ok {
result := f * 2.0
} else {
return fmt.Errorf("invalid number: %s", value)
}
ELI12:
This function is like a universal translator for numbers. You give it any kind of number (whole number, decimal, even text that looks like a number), and it converts it to a decimal number (float64). If it can't convert it (like trying to convert "hello" to a number), it tells you by returning false.
func ToFloat64Slice ¶
ToFloat64Slice converts various slice types to []float64. Returns (slice, true) on success, (nil, false) on failure.
Supported types:
- []float64 (returned as-is)
- []float32 (each element converted)
- []interface{} (each element converted via ToFloat64)
Example:
s, ok := ToFloat64Slice([]interface{}{1, 2.5, "3"}) // Returns ([1.0, 2.5, 3.0], true)
s, ok := ToFloat64Slice([]float32{1.0, 2.0}) // Returns ([1.0, 2.0], true)
ELI12:
This takes a list of numbers (in any format) and converts them all to decimal numbers. If any number in the list can't be converted, it returns nil to tell you something went wrong.
func ToInt ¶
func ToInt(value interface{}, policy IntegerPolicy) (int, bool)
ToInt applies the same conversion and checks the native int width afterwards.
func ToInt64 ¶
ToInt64 converts various numeric types to int64. Returns (value, true) on success, (0, false) on failure.
Supported types:
- int64 (returned as-is)
- int, int32, int16, int8 (converted)
- uint, uint32, uint16, uint8, uint64 (converted if within int64 range)
- float64, float32 (truncated toward zero)
- string (parsed as integer)
Example:
i, ok := ToInt64(42) // Returns (42, true)
i, ok := ToInt64(3.7) // Returns (3, true) - truncated
i, ok := ToInt64("123") // Returns (123, true)
i, ok := ToInt64("invalid") // Returns (0, false)
ELI12:
This converts numbers to whole numbers (integers). If you give it a decimal like 3.7, it chops off the .7 part and gives you 3.
func ToStringSlice ¶
func ToStringSlice(v interface{}) []string
ToStringSlice converts various slice types to []string. Returns slice on success, nil on failure.
Supported types:
- []string (returned as-is)
- []interface{} (each element converted via fmt.Sprint)
Example:
s := ToStringSlice([]interface{}{"a", "b", "c"}) // Returns ["a", "b", "c"]
s := ToStringSlice([]interface{}{1, 2, 3}) // Returns ["1", "2", "3"]
func ToUint64 ¶
func ToUint64(value interface{}, policy IntegerPolicy) (uint64, bool)
ToUint64 is the unsigned target of the same checked numeric conversion. It is used by typed plugin signatures; fractional/nonfinite values remain invalid.
func UnsignedEquivalenceKey ¶
UnsignedEquivalenceKey is an unsigned integer's equivalence key.
func UnsignedInteger ¶
Types ¶
type IntegerPolicy ¶
type IntegerPolicy uint16
IntegerPolicy selects the caller's existing coercion contract. Range checks and numeric type recognition remain here, including for plugin target types.
const ( IntegerFloat IntegerPolicy = 1 << iota IntegerWholeFloat IntegerSaturate IntegerStrings IntegerDecimalStrings IntegerBool IntegerTrimStrings IntegerClampBounds )
const IntegerOnly IntegerPolicy = 0
type JSONEncoder ¶
type JSONEncoder struct {
// contains filtered or unexported fields
}
JSONEncoder is constructed only by a domain entry point. FLOAT has a fractional or exponent part, including in typed envelopes. Custom JSON/text marshalers, raw JSON, binary data, field tags and encoding/json's errors retain their contracts. Writers traverse borrowed values directly without proxy envelopes or copied property containers. Field plans contain immutable metadata only.
func (*JSONEncoder) Encode ¶
func (encoder *JSONEncoder) Encode(value interface{}) error
func (*JSONEncoder) SetEscapeHTML ¶
func (encoder *JSONEncoder) SetEscapeHTML(escape bool)
func (*JSONEncoder) SetIndent ¶
func (encoder *JSONEncoder) SetIndent(prefix, indent string)
type List ¶
type List struct {
// contains filtered or unexported fields
}
List is a borrowed runtime list view. Numeric consumers can visit coordinates without first allocating a boxed copy; collection consumers use Values.
func ReadList ¶
ReadList is the single runtime slice/array reader. Graph scalars using a named slice explicitly retain scalar identity. No consumer enumerates slice widths.
func (List) At ¶
At retains the engine's established []int/[]float32 element coercions. Other carriers, including nested lists and named scalars, retain their values.
func (List) ElementNumberKind ¶
func (list List) ElementNumberKind() NumberKind
ElementNumberKind retains a typed empty list's numeric element kind. Boxed lists have no declared numeric kind; their elements are read individually.
func (List) Numbers32 ¶
func (list List) Numbers32() ([]float32, *NumberListIssue)
Numbers32 reads every coordinate or reports the first unconvertible value.
type Number ¶
type Number struct {
// contains filtered or unexported fields
}
Number is a numeric value without a lossy conversion. bits holds an integer's original bits or a float64's IEEE representation; kind determines its reader.
func ReadNumber ¶
ReadNumber is the single runtime numeric-kind reader, including named scalar types carried by typed lists. Text and booleans are conversion policies, not numeric values.
func ReadReflectNumber ¶
ReadReflectNumber is the same reader for reflective plugin arguments and named scalars; it avoids constructing a boxed copy of a reflect.Value.
func (Number) Float32 ¶
Float32 checks a finite narrowing before casting. Existing IEEE nonfinite inputs remain representable; vector callers validate finiteness separately.
func (Number) Int64 ¶
func (number Number) Int64(policy IntegerPolicy) (int64, bool)
Int64 narrows an already-read number through the same checked boundary.
func (Number) Int64Bits ¶
func (number Number) Int64Bits(bits int, policy IntegerPolicy) (int64, bool)
func (Number) Kind ¶
func (number Number) Kind() NumberKind
func (Number) Uint64 ¶
func (number Number) Uint64(policy IntegerPolicy) (uint64, bool)
Uint64 narrows an already-read number to an unsigned plugin target.
func (Number) Uint64Bits ¶
func (number Number) Uint64Bits(bits int, policy IntegerPolicy) (uint64, bool)
type NumberKind ¶
type NumberKind uint8
NumberKind preserves signed, unsigned and floating identity. In particular, comparisons must not narrow an unsigned integer or round an integer to float.
const ( NotNumber NumberKind = iota SignedNumber UnsignedNumber FloatNumber )
type NumberListIssue ¶
NumberListIssue lets a public adapter retain its existing localized invalid- type or out-of-range policy without reimplementing coordinate conversion.
type OrderedJSONMap ¶
OrderedJSONMap is a borrowed JSON object whose keys are emitted in the supplied order. Only Keys are emitted; a missing key has a null value. Keys and Values must remain unchanged for the duration of encoding. For example, OrderedJSONMap{Keys: []string{"id"}, Values: map[string]interface{}{"id": int64(7)}} encodes as {"id":7}.
func (OrderedJSONMap) MarshalJSON ¶
func (value OrderedJSONMap) MarshalJSON() ([]byte, error)
type UnsupportedNumberError ¶
type UnsupportedNumberError struct{ Lexeme string }
UnsupportedNumberError is Neo4j's rejection of an external INTEGER outside the 64-bit range ("Unsupported type of Number").
func (*UnsupportedNumberError) Error ¶
func (e *UnsupportedNumberError) Error() string