UTF-8 code points, non-owning byte views, owned mutable strings, decoding, and text formatting helpers.
Char
A Unicode code-point value.
Fields
codepoint:Int32code point, initially0. Direct field writes are not validated.
- A non-
Textoperand must provide anInt32codepoint. ATextoperand is converted withtoChar; it need not contain exactly one character.
greater
(other -- cond) Returns TRUE when the other Char, or the first Char decoded from Text, has a greater code point than char.- A non-
Textoperand must provide anInt32codepoint. ATextoperand is converted withtoChar; it need not contain exactly one character.
less
(other -- cond) Returns TRUE when the other Char, or the first Char decoded from Text, has a lower code point than char.- A non-
Textoperand must provide anInt32codepoint. ATextoperand is converted withtoChar; it need not contain exactly one character.
Examples
"String" use
"control" use
{} () {} [
65i32 toChar .codepoint printStack _:;
] "main" exportFunction
Expected Output During Compilation
65 Cref
StringView
StringView stores an immutable byte reference and a copied byte count. Its default value has a NIL reference and size zero. Changes to the bytes are visible through a view, but its size does not track its source. Reallocating or freeing a buffer invalidates earlier references, iterators, Spans, and StringViews into it; none keeps the owner alive.
- The stored
Nat8reference isNIL.
Fields
SCHEMA_NAME: Static schema-name field with Text value"StringView".stringData: immutableNat8reference to the first byte.stringSize:Int32byte count.
- The reference's target has schema
Nat8; an empty view can carry its supplied address, while the default view has aNILreference.
size
(-- size) Returns the view length in UTF-8 code units, that is, bytes.- The result is
Nat32arithmetic.
iter
(-- iter) Returns a byte iterator over the view.nextreturns an immutableNat8reference followed by aCond. TRUE indicates a byte; FALSE indicates exhaustion, and its reference must not be dereferenced. Unless exhaustion is known, callnextthrough a mutable iterator such as@it.next; an immutable iterator is rejected at compile time. A known-exhausted immutable iterator is accepted and returns its immutableNat8 CrefwithFALSE; the reference may beNIL.
slice
(offset size -- view) Returns a view at byte offset with the supplied byte size.- The result refers to the same storage. Offset and size are not bounds-checked here. The result permits immutable byte access, even from a mutable receiver.
Constructors and converters
toStringView
((Nat8 Cref Int32) -- view) Constructs a StringView from a two-item Tuple containing an immutable Nat8 reference and an in-place Int32 byte count. Copy a count reference with new before placing it in the Tuple. The constructor checks the schema, not the address or byte range.- A mismatched schema raises
[toStringView], invalid argument, (Nat8 Cref Int32) expectedat compile time.
makeStringView
(object -- view) Creates a StringView from a StringView, Text, or String object.- A StringView is copied as a view; Text and String inputs supply their byte address and byte count. The result remains non-owning.
makeStringViewByAddress
(address -- view) Uses C strlen at address and returns a view of the bytes before the first zero byte.Examples
"String" use
"control" use
{} () {} [
view: "hi" makeStringView;
view.size printStack _:;
] "main" exportFunction
Expected Output During Compilation
2
String
An owned mutable byte string. Raw byte operations do not enforce well-formed UTF-8. The logical size excludes its trailing zero byte.
- Its backing
Nat8array starts with size and capacity zero.
Fields
SCHEMA_NAME: Static schema-name field with Text value"String".STRING: deprecated static emptyTuplemarker.chars: ownedNat8 Array; a non-empty backing array ends with one zero byte.
A non-empty backing array contains the logical bytes followed by one zero byte; an empty String need not contain a terminator. Direct changes to chars must preserve this invariant. Destruction frees the buffer still owned by the String.
ASSIGN: assigning another String: an immutable source is copied; a mutable source is moved and becomes empty. Initialization and destruction are automatic; INIT and DIE are reserved lifecycle hooks, not ordinary public API operations.
The cat*NZ methods append to raw chars storage; they neither remove an existing terminator nor add a new one. For an existing String, copy any source that aliases it before calling makeNZ, perform the NZ appends, then call makeZ once. For example, @s.makeNZ "text" @s.catStringNZ @s.makeZ appends to an existing String. Until makeZ restores the invariant, do not use the receiver's logical String operations; String.size excludes its last raw byte. Use chars.size for the raw byte count during this phase.
hash
(-- hash) Returns the StringView byte hash of the logical string contents.iter
(-- iter) Returns an iterator over the logical bytes.nextrequires a mutable iterator unless exhaustion is known; for a nonempty source use@it.next. An immutable iterator over a known-exhausted source is accepted and returns its immutableNat8 CrefwithFALSE; the reference may beNIL. When theCondis TRUE, the returned reference is mutable when the iterator was created from a mutableStringsuch as@s.iterand immutable otherwise. Ignore the reference when theCondis FALSE.
size
(-- size) Returns the logical byte count, excluding the trailing zero terminator.- Offset and size are used for address arithmetic without bounds checks; the returned view does not keep the String alive. The result permits immutable byte access, even from a mutable receiver.
catAsciiSymbolCode
(codepoint --) Appends an ASCII code in Nat32 form, from 0 through 127, and restores the trailing terminator.- The input must be
Nat32. Assertion checking reportsIs not ascii symbol code!for an invalid value; disabling runtime assertions does not remove this precondition.
catAsciiSymbolCodeNZ
(codepoint --) Appends an ASCII code point as one byte without adding the String's trailing zero terminator.codepointis aNat32value below128. Assertion checking reportsIs not ascii symbol code!for an invalid value; run-time checking requiresDEBUG. Disabling checks does not remove the range precondition.- Follow the NZ phase protocol.
catCharNZ
(char --) Appends the input code point encoded as UTF-8 without adding the String's trailing zero terminator.- The input supplies a
codepointfield that is cast toNat32; this method does not validate the Unicode scalar range. - Follow the NZ phase protocol.
- A source that aliases the receiver must be copied first (see the known-issue note below).
Known issue: a source that aliases the receiver is read after the receiver has been enlarged, so appending a String, or a view of it, to itself yields undefined bytes; copy the source first: s toString @s.catString.
catStringNZ
(source --) Appends the bytes of a Text, StringView, or String source without adding the String's trailing zero terminator.- An empty source appends nothing.
- Copy a source that aliases the receiver before entering the NZ phase; enlarging the backing array can invalidate a borrowed source.
- Follow the NZ phase protocol.
catInt
(number by3 --) Appends base-10 text for an integer or real number and restores the terminator.- Real inputs must be finite and fit the integer conversion:
Int64for negative inputs andNat64otherwise. They lose their fractional part; a negative input retains its minus sign, so-0.5produces-0. Zero produces0. by3is aCond. FALSE disables grouping; TRUE enables comma grouping; by3 inserts commas between groups of three integer digits. Real-number formatting bycatFloator groupedcatManyhas the known issue described below.
catIntNZ
(number by3 --) Appends base-10 text for an integer or real number with optional groups of three digits without adding the String's trailing zero terminator.by3is aCond;TRUEinserts comma separators andFALSEdisables grouping.- The numeric conversion and grouping rules of
catIntapply, including truncation of real inputs and their finite conversion ranges. - Follow the NZ phase protocol.
catNatNZ
(number by3 --) Appends unsigned decimal text with optional groups of three digits without adding the String's trailing zero terminator.- The input is converted to
Nat64before formatting. Negative signed inputs therefore use their unsigned representation; real inputs lose their fractional part and must be within the finite conversion range. by3is aCond;TRUEinserts comma separators andFALSEdisables grouping.- Zero produces one digit,
0. - Follow the NZ phase protocol.
catUint
(number --) Intended to append unsigned integer text and restore the terminator.Known issue: catUint calls the unavailable catUintNZ helper; any use fails at compile time with «catUintNZ», Name was not found. Unsigned numbers can be appended through cat.
catHexNZ
(number --) Appends the Nat64 representation of number as uppercase hexadecimal without a prefix, leading zero padding, or the String's trailing zero terminator.- The input is cast to
Nat64; zero produces0and hexadecimal digits from 10 through 15 use uppercaseAthroughF. - Follow the NZ phase protocol.
- Either zero produces
0.0; positive infinity, negative infinity, and NaN produceinf,-inf, andnan. Other negative values have a minus sign. Finite output retains a decimal point and at least one fractional digit. - For
Real64, fixed notation is selected for base-10 orders -4 through 8; forReal32, -3 through 7. Other orders use lowercaseefollowed by a decimal exponent, without a plus sign for a positive exponent. - With base-10 order
k, fixed notation uses a rounding precision of min(6, 8 - k) decimal places forReal64or min(5, 7 - k) forReal32. Exponential notation uses six or five decimal places of rounding precision in the significand, respectively. Trailing fractional zeros are omitted except for one required digit. Rounding can leave an unnormalized significand, such as10.0e9. by3is aCond. FALSE disables grouping; TRUE enables comma grouping.
Known issue: decimal scaling can overflow for very small finite values, such as 1e-303 Real64 and 1e-34 Real32. Their formatted output is not reliable.
Known issue: grouping real numbers can add a leading comma and group fractional digits. For example, grouped catMany appends ,123.5 for 123.5 By3 and 0.123,456 for 0.123456 By3; catFloat with by3 TRUE produces the same output. Avoid By3 for real-valued items; call catFloat with FALSE.
catFloatNZ
(number by3 --) Appends Real32 or Real64 formatting without adding the String's trailing zero terminator.- Zero, positive infinity, negative infinity, and NaN produce
0.0,inf,-inf, andnan. by3is aCond;TRUEenables the same grouping behavior ascatFloat, andFALSEdisables grouping.- The formatting rules and known issues of
catFloatapply, including its precision, notation, and tiny-value limits. - Follow the NZ phase protocol.
catBy3NZ
(arg --) Appends a supported integer or real value with grouping enabled, without adding the String's trailing zero terminator.- Signed integers, unsigned integers, and real values use
catIntNZ,catNatNZ, andcatFloatNZ, respectively, with grouping enabled. - An unsupported object raises
object is not supported for string concatenation. - Follow the NZ phase protocol.
catCondNZ
(cond --) Appends the textual form of a Cond without adding the String's trailing zero terminator.TRUEappends"TRUE";FALSEappends"FALSE".- Follow the NZ phase protocol.
cat
(object --) Appends one supported object and restores the terminator.CondproducesTRUEorFALSE. Integer inputs use ungrouped decimal text; real inputs usecatFloatformatting without grouping.Charis encoded as UTF-8;Text,StringView,String, and supported byteSpans contribute their bytes. SupportedSpaninputs areNat8 SpanandNat8 Cref Span; aNat8Arrayis not accepted directly, pass its span instead.- A source that aliases the receiver must be copied first; see the known-issue note at
catString. - An unsupported object raises
object is not supported for string concatenation.
catNZ
(arg --) Appends one supported object without adding the String's trailing zero terminator.Charis UTF-8 encoded;Text,StringView,String, and supported byte spans contribute their bytes.- A
Condproduces"TRUE"or"FALSE"; integer and real inputs use ungrouped decimal formatting. - Supported byte spans have item schema
Nat8and are eitherSpanorCref Span; aNat8Arrayis not accepted directly. - An unsupported object raises
object is not supported for string concatenation. - Follow the NZ phase protocol.
catMany
(source --) Appends items from a List, Tuple, Index, or Indexable accepted by toIndex, without inserting separators. An unmarked item uses cat. A following Hex selects catHex for the preceding item; a following By3 selects grouped integer or real formatting. The item must be accepted by that formatter, and the marker is consumed.- Markers are recognized by the presence of
HEXorBY3fields;HEXtakes precedence when both are present. - An invalid source raises
Built-in tuple, Index, or Indexable expected. An item rejected bycator by grouped formatting raisesobject is not supported for string concatenation; this includes a marker processed as an unmarked item. - Supply an independent indexed source. Copy any items that alias the receiver before building the sequence; for a
StringorStringViewitem, usetoString. Do not convert the sequence itself toString. See the known-issue note atcatString.
makeNZ
(--) Removes the final backing-array item when present, preparing a String for non-terminated appends.- It assumes the removed item is the trailing zero and does not inspect its value.
- It is a no-op for an empty backing array, and removing the item leaves capacity unchanged.
- Follow the NZ phase protocol.
makeZ
(--) Appends a zero byte when the backing array is nonempty, restoring the String's trailing zero terminator.- It leaves an empty backing array empty; on a nonempty array the appended
Nat8zero is excluded from the logicalString.size. - Follow the NZ phase protocol.
- A positive size leaves size + 1 backing bytes, ending in zero. Zero clears the backing item count without releasing reserved storage.
- Growth does not initialize new content; the former terminator can become a logical zero byte.
catSymbolCode
(codepoint --) Converts codePoint to Int32, then to Char, and appends it. Conversion can truncate a wider input before the code-point check.- The resulting code point must be in 0 through 0xD7FF or 0xE000 through 0x10FFFF. Assertion checking reports
invalid UTF-8 code pointfor an invalid value; disabling runtime assertions does not remove this precondition.
- The view is empty for an empty String; it does not own or retain the String's buffer. The result permits immutable byte access, even from a mutable receiver.
Examples
"String" use
"control" use
{} () {} [
text: "abc" toString;
text.size printStack _:;
@text.getStringView.size printStack _:;
] "main" exportFunction
Expected Output During Compilation
Int32
Int32
Formatting Example
"String" use
"control" use
{} Int32 {} [
text: String;
(123456 By3 ", " 255 Hex) @text.catMany
@text.getStringView print
0
] "main" exportFunction
Expected Output
123,456, FF
Numeric helper
- The exponent zero returns one in the base's schema, and the result otherwise retains the base's schema.
- A negative exponent first replaces the base with one divided by the base in that schema; integer bases therefore use integer division, while real bases produce reciprocals.
- The exponent must be greater than
-2147483648.
Known issue: the minimum Int32 exponent, -2147483648, cannot be negated in its schema. With a known exponent the loop fails during compilation; with an unknown exponent it does not terminate; do not pass that exponent.
Text helpers
strlen
(address -- length) Returns the C zero-terminated byte length at address.- The result excludes the zero byte and performs no UTF-8 validation.
addressand length have schemaNatx.addressmust point to readable storage containing a zero terminator.
addTerminator
(source -- terminated) Appends a zero byte to known Text, or to an owned String conversion of a non-Text input.- Known
TextreturnsTextwith one additional zero byte, even if it already ends in zero. - A non-
Textinput is converted withtoString; the appended zero counts toward the result's logical size, before its ordinary trailing terminator. - Use
toStringbefore adding a terminator when theTextis not known at compile time.
- Accepts the same indexed sources, items, and formatting markers as
String.catMany.
print
(object --) Formats a supported object and writes its bytes to standard output without adding a line feed.- Accepts every non-
Textinput supported byString.cat; a non-Stringobject is converted withtoStringfirst. Use control'sprintforText. Does not report write errors or retry short writes.
- Accepts the same indexed sources, items, and formatting markers as
String.catMany.
- Unsupported inputs fail with
object is not supported for string concatenation. - Accepts the same inputs as
String.cat, including known and unknownText.Text,StringView, andStringcontents are copied into the result; aStringinput is not moved, even when supplied through a mutable reference.
splitString
(source -- result) Splits Text, StringView, or String into non-owning StringViews, one for each byte range consumed by REPLACE-mode decoding.- The ranges retain the original bytes, including malformed bytes; they do not contain substituted replacement characters.
successis alwaysTRUEanderrorOffsetis always-1in this version; the failure branch is unreachable because REPLACE-mode decoding consumes at least one byte from a nonempty remainder.- Empty input produces an empty
charsArray. The source storage must outlive the returned views.
success:Cond; alwaysTRUEin this version.errorOffset:Int32; always-1in this version.chars: ownedStringView Arrayof non-owning ranges into the source bytes.
Examples
"String" use
"control" use
{} () {} [
parts: "你好" splitString;
parts.success printStack _:;
parts.chars.size printStack _:;
] "main" exportFunction
Expected Output During Compilation
Cond Cref
Int32
Printing Example
"String" use
"control" use
{} Int32 {} [
("left=" 42) printList
0
] "main" exportFunction
Expected Output
left=42
UTF-8 helpers
REPLACEMENT_CHARACTER
(-- char) Provides the Unicode replacement character U+FFFD.isHeadUnit
(unit -- cond) Accepts Nat8. Returns TRUE for an ASCII byte or a byte in the 0xC0 through 0xF7 range.- Tests the leading-byte pattern only, not the validity of a UTF-8 sequence.
isValidCodepoint
(codepoint -- cond) Accepts Int32. Returns TRUE for 0 through 0xD7FF or 0xE000 through 0x10FFFF, excluding surrogates.toChar
(source -- char) Converts an Int32 code point or Text to Char. An Int32 input must be a valid Unicode scalar value. Text is decoded in TRUST mode; only the first result is used, trailing characters are ignored, and empty Text returns REPLACEMENT_CHARACTER.- The resulting code point must be in 0 through 0xD7FF or 0xE000 through 0x10FFFF. Assertion checking reports
invalid UTF-8 code pointfor an invalid value; disabling runtime assertions does not remove this precondition.
Utf8DecoderMode
(-- modes) Pushes a namespace object; Utf8DecoderMode.REPORT, Utf8DecoderMode.TRUST, and Utf8DecoderMode.REPLACE yield known Int32 values 0, 1, and 2.decodeUtf8
(source mode -- decoder) Creates a decoder whose next returns one decoded value and a Cond.- Accepts
Text, aListorTupleofNat8units, a byte iterator, or an object whoseitermethod supplies one. modeis a knownInt32selected at compile time.- Advance the decoder through a mutable receiver.
nexthas stack effect(-- value cond). REPORT returnsInt32values; TRUST and REPLACE returnCharvalues. - At exhaustion, REPORT returns
-1with FALSE; TRUST and REPLACE returnREPLACEMENT_CHARACTERwith FALSE. - REPORT returns
-1with TRUE for a detected malformed sequence; later calls continue at the next unread byte. - REPLACE returns
REPLACEMENT_CHARACTERwith TRUE for a detected malformed sequence. Bytes already read, including an offending continuation byte, are consumed rather than retried;C2 41 42produces a replacement followed byB. - TRUST requires well-formed UTF-8. Assertion checking can report
ill-formed UTF-8 sequence; malformed input has no supported behavior with checking disabled.
Known issue: advancing a TRUST decoder over a short source with a known length can fail at compile time with ill-formed UTF-8 sequence even for valid input. This affects Text supplied directly to decodeUtf8 as well as StringView and TextIter. For Text, use decode instead; for a view or iterator, apply dynamic before decoding.
getCodePointAndSize
(data size -- codepoint byteSize) Deprecated helper that decodes the first code point with REPLACE mode and returns its code point and consumed byte count.datais aNat8reference andsizeis a nonnegativeInt32byte count covering readable storage.getCodePointAndSizereturns aNat32code point followed by anInt32count;getCodePointSizereturns only the count. ForgetCodePointAndSize, empty input returns code point65533and count zero; malformed input returns code point65533and the consumed count, not necessarily one.getCodePointSizereturns the same count, including zero for empty input.
getCodePointSize
(data size -- byteSize) Deprecated helper that returns the byte count consumed by the first REPLACE-mode decoded code point.- Accepts the same data reference and size as
getCodePointAndSize. Returns anInt32consumed-byte count, including zero for empty input.
makeStringIter2
(data size -- iter) Creates an iterator over a byte reference and its UTF-8 byte count.datais an immutableNat8reference andsizeis a nonnegativeInt32byte count. The storage must cover that range and outlive the iterator and returned views. Convert a mutable input view withdata const size makeStringIter2.validisTRUEwhile the current REPLACE-mode code point has a nonzero byte size, andgetreturns a non-owningStringViewfor that byte range.nextadvances by the current code-point byte size, decreases the remaining count, and computes the next size.
See also
- Span: Contiguous non-owning view of items of the same schema.
- SpanStatic: Contiguous non-owning view of items of the same schema with a schema-level fixed size.
- ascii: Dynamic ASCII code constants grouped under object ascii.
- windows/unicode: UTF-8 to zero-terminated UTF-16 conversion helper.
- file: File I/O helpers for byte arrays and String values.
- Json: JSON value type, parsing helpers, and serialization helpers.
- Xml: XML document, parser, and serialization helpers.
- algorithm: Collection interfaces, comparison helpers, iteration adapters, and view slicing utilities.