外观
系统库 sys(第 2 部分)
原文: https://finproducts.atlassian.net/wiki/spaces/JIDD3/pages/34793226488/FIN+5.3.1+sys+part+2 中文整理基于 FIN 5.3.1
导读: Slot 表示类型上的成员字段或方法。
以下为 API 参考,保留英文以便对照源码;目录已列出(英文标题便于检索);概述已尽量中译。
目录(导读)
- Slot Details
- doc
- facet
- facets
- find
- findField
- findFunc
- findMethod
- hasFacet
- isAbstract
- isConst
- isCtor
- isField
- isInternal
- isMethod
- isNative
- isOverride
- isPrivate
- isProtected
- isPublic
- isStatic
- isSynthetic
- isVirtual
- name
- parent
- qname
- signature
- toStr
- all
- any
- capitalize
- chars
- compare
- compareIgnoreCase
- contains
- containsChar
- decapitalize
- defVal
- each
- eachWhile
- eachr
- endsWith
- equals
- equalsIgnoreCase
- fromChars
- fromDisplayName
- get
- getRange
- getSafe
- hash
- in
- index
- indexIgnoreCase
- indexr
- indexrIgnoreCase
- intern
- isAlpha
- isAlphaNum
- isAscii
- isEmpty
- isLower
- isSpace
- isUpper
- justl
- justr
- localeCapitalize
- localeCompare
- localeDecapitalize
- localeLower
- localeUpper
- lower
- mult
- numNewlines
- padl
- padr
- plus
- replace
- reverse
- size
- spaces
- split
- splitLines
- startsWith
- toBool
- toBuf
- toCode
- toDecimal
- toDisplayName
- toFloat
- toInt
- toLocale
- toRegex
- toUri
- toXml
- trim
- trimEnd
- trimStart
- trimToNull
- upper
- add
- addChar
- addRange
- capacity
- clear
- insert
- join
- joinNotNull
- make
- out
- remove
- removeRange
- replaceRange
- set
- curTestMethod
- fail
- setup
- teardown
- tempDir
- verify
- verifyEq
- …(其余标题见英文正文)
概述(中译)
抽象常量类 Slot : Obj
Slot 表示类型上的成员字段或方法。
方法
插槽详情
Str? doc()
返回此槽的原始fandoc,如果不可用则返回null。
Facet? facet(类型 type, 布尔 checked := true)
通过类型获取一个面。如果在此槽中未找到,则根据检查标志返回 null 或抛出 UnknownFacetErr。详情请参见 Facets 文档。
API 正文(英文)
facets
Facet[] facets()
Get the list of facets defined on this slot or return an empty list if no facets are defined. If looking up a facet by type, then use the facet method which will provide better performance. See Facets Doc for details.
find
static Slot? find(Str qname, Bool checked := true)
Find a Slot by its qualified name "pod::Type.slot". If the slot doesn't exist and checked is false then return null, otherwise throw UnknownSlotErr.
findField
static Field? findField(Str qname, Bool checked := true)
Convenience for (Field)find(qname, checked)
findFunc
static Func? findFunc(Str qname, Bool checked := true)
Convenience for findMethod(qname, checked).func
findMethod
static Method? findMethod(Str qname, Bool checked := true)
Convenience for (Method)find(qname, checked)
hasFacet
Bool hasFacet(Type type)
Return if this type has the specified facet defined.
isAbstract
Bool isAbstract()
Return if slot is abstract (no implementation provided).
isConst
Bool isConst()
Return if slot is constant and thread safe. A constant field is explicitly marked with the const modifier and guaranteed to always reference the same immutable object for the life of the VM. A const method is guaranteed to not capture any state from its thread, and is safe to execute on other threads. The compiler marks methods as const based on the following analysis:
- static methods are always automatically const
- instance methods are never const
- closures which don't capture any variables from their scope are automatically const
- partial apply methods which only capture const variables from their scope are automatically const
isCtor
Bool isCtor()
Return if slot is constructor method.
isField
Bool isField()
Return true if this is an instance of Field.
isInternal
Bool isInternal()
Return if slot has internal protection scope.
isMethod
Bool isMethod()
Return true if this is an instance of Method.
isNative
Bool isNative()
Return if slot is native.
isOverride
Bool isOverride()
Return if slot is an override (of parent's virtual method).
isPrivate
Bool isPrivate()
Return if slot has private protection scope.
isProtected
Bool isProtected()
Return if slot has protected protection scope.
isPublic
Bool isPublic()
Return if slot has public protection scope.
isStatic
Bool isStatic()
Return if slot is static (class based, rather than instance).
isSynthetic
Bool isSynthetic()
Return if this slot was generated by the compiler.
isVirtual
Bool isVirtual()
Return if slot is virtual (may be overridden in subclasses).
name
Str name()
Simple name of the slot such as "size".
parent
Type parent()
Parent type which defines this slot.
qname
Str qname()
Qualified name such as "sys:Str.size".
signature
virtual Str signature()
Return a string representation of the Fantom code signature.
toStr
virtual override Str toStr()
Always return qname().
Str
const class Str : Obj
Str represents a sequence of Unicode characters.
Fields
| defVal | Default value is "". |
Methods
| all | Return true if c returns true for all of the characters in this string. |
| any | Return true if c returns true for any of the characters in this string. |
| capitalize | Return this string with the first character converted uppercase. |
| chars | Get the characters in this string as a list of integer code points. |
| compare | Compare based on Unicode character values. |
| compareIgnoreCase | Compare two strings without regard to case and return -1, 0, or 1 if this string is less than, equal to, or greater than the specified string. |
| contains | Return if this string contains the specified string. |
| containsChar | Return if this string contains the specified character. |
| decapitalize | Return this string with the first character converted lowercase. |
| each | Call the specified function for every char in the string with index 0 and incrementing up to size-1. |
| eachWhile | Iterate each character in the string until the function returns non-null. |
| eachr | Reverse each - call the specified function for every char in the string starting with index size-1 and decrementing down to 0. |
| endsWith | Return if this Str ends with the specified Str. |
| equals | Return true if a Str with exact same char sequence. |
| equalsIgnoreCase | Convenience for compareIgnoreCase(s) == 0. |
| fromChars | Construct a string from a list of unicode code points. |
| fromDisplayName | Translate a display name like "Foo Bar" to a programmatic name "fooBar". |
| get | Get the character at the zero based index as a Unicode code point. |
| getRange | Return a substring based on the specified range. |
| getSafe | Get the character at the zero based index as a Unicode code point. |
| hash | The hash for a Str is platform dependent. |
| in | Create an input stream to read characters from this string. |
| index | Return the first occurrence of the specified substring searching forward, starting at the specified offset index. |
| indexIgnoreCase | Find the index just like index, but ignoring case for ASCII chars only. |
| indexr | Reverse index - return the first occurrence of the specified substring searching backward, starting at the specified offset index. |
| indexrIgnoreCase | Find the index just like indexr, but ignoring case for ASCII chars only. |
| intern | Internalize this Str such that two strings which are equal via the == operator will have the same reference such that === will be true. |
| isAlpha | Return if every char is an ASCII letter. |
| isAlphaNum | Return if every char is an ASCII alpha-numeric. |
| isAscii | Return if every character in this Str is a US-ASCII character less than 128. |
| isEmpty | Return if size() == 0. |
| isLower | Return if every character in this Str is ASCII lowercase: a-'z'. |
| isSpace | Return if every character in this Str is whitespace: space \t \n \r \f |
| isUpper | Return if every character in this Str is ASCII uppercase: A-'Z'. |
| justl | If size is less than width, then add spaces to the right to create a left justified string. |
| justr | If size is less than width, then add spaces to the left to create a right justified string. |
| localeCapitalize | Return this string with the first character converted to uppercase using the current locale. |
| localeCompare | Compare two strings without regard to case according to the current locale. |
| localeDecapitalize | Return this string with the first character converted to lowercase using the current locale. |
| localeLower | Return this string with all uppercase characters replaced to lowercase using the current locale. |
| localeUpper | Return this string with all lowercase characters replaced to uppercase using the current locale. |
| lower | Return this string with all uppercase characters replaced to lowercase. |
| mult | Duplicate this string the given number of times. |
| numNewlines | Count the number of newline combinations: "\n", "\r", or "\r\n". |
| padl | If size is less than width, then add the given char to the left to achieve the specified width. |
| padr | If size is less than width, then add the given char to the left to achieve the specified width. |
| plus | Concat the value of obj.toStr |
| replace | Replace all occurrences of from with to. |
| reverse | Reverse the contents of this string. |
| size | Return number of characters in this string. |
| spaces | Get a Str containing the specified number of spaces. |
| split | Split a string into a list of substrings using the given separator character. |
| splitLines | Split this string into individual lines where lines are terminated by \n, \r\n, or \r. |
| startsWith | Return if this Str starts with the specified Str. |
| toBool | Convenience for Bool.fromStr using this string. |
| toBuf | Get this string encoded into a buffer of bytes. |
| toCode | Return this string as its Fantom source code and serialization representation surrounded by the specified quote character (which defaults to "). |
| toDecimal | Convenience for Decimal.fromStr using this string. |
| toDisplayName | Translate a programmer name like "fooBar" to "Foo Bar". |
| toFloat | Convenience for Float.fromStr using this string. |
| toInt | Convenience for Int.fromStr using this string. |
| toLocale | Return this. |
| toRegex | Convenience for Regex.fromStr using this string. |
| toStr | Return this. |
| toUri | Convenience for Uri.fromStr using this string. |
| toXml | Return this string as valid XML text. |
| trim | Trim whitespace from the beginning and end of the string. |
| trimEnd | Trim whitespace only from the end of the string. |
| trimStart | Trim whitespace only from the beginning of the string. |
| trimToNull | Trim whitespace from the beginning and end of the string. |
| upper | Return this string with all lowercase characters replaced to uppercase. |
Slot Details
all
Bool all(|Int,Int->Bool| c)
Return true if c returns true for all of the characters in this string. If this string is empty, return true.
Example:
"Bar".all |c| { c.isUpper } => false
"BAR".all |c| { c.isUpper } => trueany
Bool any(|Int,Int->Bool| c)
Return true if c returns true for any of the characters in this string. If this string is empty, return false.
Example:
"Foo".any |c| { c.isUpper } => true
"foo".any |c| { c.isUpper } => falsecapitalize
Str capitalize()
Return this string with the first character converted uppercase. The case conversion is for ASCII only. Also see decapitalize and localeCapitalize.
Example:
"foo".capitalize => "Foo"chars
Int[] chars()
Get the characters in this string as a list of integer code points. Also see fromChars.
compare
virtual override Int compare(Obj obj)
Compare based on Unicode character values. Case is not taken into account - also see compareIgnoreCase and localeCompare.
Examples:
"a".compare("b") => -1
"hi".compare("hi") => 0
"hi".compare("HI") => 1
"b".compare("a") => 1compareIgnoreCase
Int compareIgnoreCase(Str s)
Compare two strings without regard to case and return -1, 0, or 1 if this string is less than, equal to, or greater than the specified string. Only ASCII character case is taken into account. See localeCompare for localized case insensitive comparisions.
Examples:
"a".compareIgnoreCase("b") => -1
"hi".compareIgnoreCase("HI") => 0
"b".compareIgnoreCase("a") => 1contains
Bool contains(Str s)
Return if this string contains the specified string. Convenience for index(s) != null
containsChar
Bool containsChar(Int ch)
Return if this string contains the specified character.
decapitalize
Str decapitalize()
Return this string with the first character converted lowercase. The case conversion is for ASCII only. Also see capitalize and localeDecapitalize.
Example:
"Foo".decapitalize => "foo"defVal
const static Str defVal
Default value is "".
each
Void each(|Int,Int| c)
Call the specified function for every char in the string with index 0 and incrementing up to size-1.
Example:
"abc".each |Int c| { echo(c.toChar) }eachWhile
Obj? eachWhile(|Int,Int->Obj?| c)
Iterate each character in the string until the function returns non-null. If function returns non-null, then break the iteration and return the resulting object. Return null if the function returns null for every item.
eachr
Void eachr(|Int,Int| c)
Reverse each - call the specified function for every char in the string starting with index size-1 and decrementing down to 0.
Example:
"abc".eachr |Int c| { echo(c.toChar) }endsWith
Bool endsWith(Str s)
Return if this Str ends with the specified Str.
equals
virtual override Bool equals(Obj? obj)
Return true if a Str with exact same char sequence.
equalsIgnoreCase
Bool equalsIgnoreCase(Str s)
Convenience for compareIgnoreCase(s) == 0. Only ASCII character case is taken into account. See localeCompare for localized case insensitive comparisions.
fromChars
static Str fromChars(Int[] chars)
Construct a string from a list of unicode code points. Also see chars.
fromDisplayName
Str fromDisplayName()
Translate a display name like "Foo Bar" to a programmatic name "fooBar". This method decapitalizes the first letter, then walks the string removing spaces. Also see toDisplayName.
Examples:
"Foo".fromDisplayName -> "foo"
"Foo Bar".fromDisplayName -> "fooBar"
"Foo Bar Baz".fromDisplayName -> "fooBarBaz"
"Foo 33 Bar".fromDisplayName -> "foo33Bar"
"Foo XML".fromDisplayName -> "fooXML"
"foo bar".fromDisplayName -> "fooBar"get
@Operator Int get(Int index)
Get the character at the zero based index as a Unicode code point. Negative indexes may be used to access from the end of the string. This method is accessed via the [] operator. Throw IndexErr if the index is out of range.
getRange
@Operator Str getRange(Range range)
Return a substring based on the specified range. Negative indexes may be used to access from the end of the string. This method is accessed via the [] operator. Throw IndexErr if range illegal.
Examples:
"abcd"[0..2] => "abc"
"abcd"[3..3] => "d"
"abcd"[-2..-1] => "cd"
"abcd"[0..<2] => "ab"
"abcd"[1..-2] => "bc"
"abcd"[4..-1] => ""getSafe
Int getSafe(Int index, Int def := 0)
Get the character at the zero based index as a Unicode code point. Negative indexes may be used to access from the end of the string. Unlike get, this method does not throw IndexErr when the index is out or range, instead it returns def.
hash
virtual override Int hash()
The hash for a Str is platform dependent.
in
InStream in()
Create an input stream to read characters from this string. The input stream is designed only to read character data. Attempts to perform binary reads will throw UnsupportedErr.
index
Int? index(Str s, Int offset := 0)
Return the first occurrence of the specified substring searching forward, starting at the specified offset index. A negative offset may be used to access from the end of string. Return null if no occurrences are found.
Examples:
"abcabc".index("b") => 1
"abcabc".index("b", 1) => 1
"abcabc".index("b", 3) => 4
"abcabc".index("b", -3) => 4
"abcabc".index("x") => nullindexIgnoreCase
Int? indexIgnoreCase(Str s, Int offset := 0)
Find the index just like index, but ignoring case for ASCII chars only.
indexr
Int? indexr(Str s, Int offset := -1)
Reverse index - return the first occurrence of the specified substring searching backward, starting at the specified offset index. A negative offset may be used to access from the end of string. Return null if no occurrences are found.
Examples:
"abcabc".indexr("b") => 4
"abcabc".indexr("b", -3) => 1
"abcabc".indexr("b", 0) => nullindexrIgnoreCase
Int? indexrIgnoreCase(Str s, Int offset := -1)
Find the index just like indexr, but ignoring case for ASCII chars only.
intern
Str intern()
Internalize this Str such that two strings which are equal via the == operator will have the same reference such that === will be true.
isAlpha
Bool isAlpha()
Return if every char is an ASCII letter.
isAlphaNum
Bool isAlphaNum()
Return if every char is an ASCII alpha-numeric.
isAscii
Bool isAscii()
Return if every character in this Str is a US-ASCII character less than 128.
isEmpty
Bool isEmpty()
Return if size() == 0.
isLower
Bool isLower()
Return if every character in this Str is ASCII lowercase: a-'z'.
isSpace
Bool isSpace()
Return if every character in this Str is whitespace: space \t \n \r \f
isUpper
Bool isUpper()
Return if every character in this Str is ASCII uppercase: A-'Z'.
justl
Str justl(Int width)
If size is less than width, then add spaces to the right to create a left justified string. Also see padr.
Examples:
"xyz".justl(2) => "xyz"
"xyz".justl(4) => "xyz "justr
Str justr(Int width)
If size is less than width, then add spaces to the left to create a right justified string. Also see padl.
Examples:
"xyz".justr(2) => "xyz"
"xyz".justr(4) => " xyz"localeCapitalize
Str localeCapitalize()
Return this string with the first character converted to uppercase using the current locale. Also see localeDecapitalize and capitalize.
localeCompare
Int localeCompare(Str s)
Compare two strings without regard to case according to the current locale. Return -1, 0, or 1 if this string is less than, equal to, or greater than the specified string.
Examples (assuming English locale):
"a".localeCompare("b") => -1
"hi".localeCompare("HI") => 0
"b".localeCompare("A") => 1localeDecapitalize
Str localeDecapitalize()
Return this string with the first character converted to lowercase using the current locale. Also see localeCapitalize and decapitalize.
localeLower
Str localeLower()
Return this string with all uppercase characters replaced to lowercase using the current locale. Also see localeUpper, lower, and Int.localeLower.
localeUpper
Str localeUpper()
Return this string with all lowercase characters replaced to uppercase using the current locale. Also see localeLower, upper, and Int.localeUpper.
lower
Str lower()
Return this string with all uppercase characters replaced to lowercase. The case conversion is for ASCII only. Also see upper, localeLower, Int.lower, Int.localeLower.
Example:
"Apple".lower => "apple"mult
@Operator Str mult(Int times)
Duplicate this string the given number of times. Any integer less than or equal to zero returns an empty string.
Examples:
"x" * 4 => "xxxx"numNewlines
Int numNewlines()
Count the number of newline combinations: "\n", "\r", or "\r\n".
padl
Str padl(Int width, Int char := 32)
If size is less than width, then add the given char to the left to achieve the specified width. Also see justr.
Examples:
"3".padl(3, '0') => "003"
"123".padl(2, '0') => "123"padr
Str padr(Int width, Int char := 32)
If size is less than width, then add the given char to the left to achieve the specified width. Also see justl.
Examples:
"xyz".padr(2, '.') => "xyz"
"xyz".padr(5, '-') => "xyz--"plus
@Operator Str plus(Obj? obj)
Concat the value of obj.toStr
replace
Str replace(Str from, Str to)
Replace all occurrences of from with to.
Examples:
"hello".replace("hell", "t") => "to"
"aababa".replace("ab", "-") => "a--a"reverse
Str reverse()
Reverse the contents of this string.
Example:
"stressed".reverse => "desserts"size
Int size()
Return number of characters in this string.
spaces
static Str spaces(Int n)
Get a Str containing the specified number of spaces. Also see justl and justr to justify an existing string.
Examples:
Str.spaces(1) => " "
Str.spaces(2) => " "split
Str[] split(Int? separator := null, Bool trim := true)
Split a string into a list of substrings using the given separator character. If there are contiguous separators, then they are split into empty strings. If trim is true, then whitespace is trimmed from the beginning and end of the results.
If separator is null, then the string is split according to any sequence of whitespace characters (any character equal to or less than the 0x20 space character including , \r, \n, and \t).
If this is the empty string or there are no splits return a list of one item.
Examples:
// split on whitespace
"".split => [""]
"x".split => ["x"]
"x y".split => ["x", "y"]
" x y ".split => ["x", "y"]
" x \n y \n z ".split => ["x", "y", "z"]
// split on sep with trim
"".split('|') => [""]
"22".split(';') => ["22"]
"22;33".split(';') => ["22","33"]
"22, 33".split(',') => ["22","33"]
" 22 ; 33 ".split(';') => ["22","33"]
// split on sep with no trim
"22#33".split('#', false) => ["22","33"]
" x ; y".split(';', false) => [" x "," y"]splitLines
Str[] splitLines()
Split this string into individual lines where lines are terminated by \n, \r\n, or \r. The returned strings do not contain the newline character.
Examples:
"x\ny".splitLines => ["x", "y"]
"".splitLines => [""]
"x".splitLines => ["x"]
"\r\n".splitLines => ["", ""]
"x\n".splitLines => ["x", ""]startsWith
Bool startsWith(Str s)
Return if this Str starts with the specified Str.
toBool
Bool? toBool(Bool checked := true)
Convenience for Bool.fromStr using this string.
toBuf
Buf toBuf(Charset charset := Charset.utf8())
Get this string encoded into a buffer of bytes.
toCode
Str toCode(Int? quote := 34, Bool escapeUnicode := false)
Return this string as its Fantom source code and serialization representation surrounded by the specified quote character (which defaults to "). If quote is null then the return is unquoted. This method will backslash escape the following characters: \n \r \f \t \\ $. If the quote character is the double quote, single quote, or backtick then it is escaped too. Control chars less than 0x20 are escaped as \uXXXX. If escapeUnicode is true then any char over 0x7F is escaped as \uXXXX.
toDecimal
Decimal? toDecimal(Bool checked := true)
Convenience for Decimal.fromStr using this string.
toDisplayName
Str toDisplayName()
Translate a programmer name like "fooBar" to "Foo Bar". This method capitalizes the first letter, then walks the string looking for ASCII capital letters and inserting a space. Any underbars are replaced with a space. Also see fromDisplayName.
Examples:
"foo".toDisplayName -> "Foo
"fooBar".toDisplayName -> "Foo Bar"
"fooBarBaz".toDisplayName -> "Foo Bar Baz"
"foo33".toDisplayName -> "Foo 33"
"fooXML".toDisplayName -> "Foo XML"
"Foo".toDisplayName -> "Foo"
"foo_bar".toDisplayName -> "Foo Bar"toFloat
Float? toFloat(Bool checked := true)
Convenience for Float.fromStr using this string.
toInt
Int? toInt(Int radix := 10, Bool checked := true)
Convenience for Int.fromStr using this string.
toLocale
Str toLocale()
Return this. This method is used to enable toLocale to be used with duck typing across most built-in types.
toRegex
Regex toRegex()
Convenience for Regex.fromStr using this string.
toStr
virtual override Str toStr()
Return this.
toUri
Uri toUri()
Convenience for Uri.fromStr using this string.
toXml
Str toXml()
Return this string as valid XML text. The special control characters amp, lt, apos and quot are always escaped. The gt char is escaped only if it is the first char or if preceded by the ] char. Also see OutStream.writeXml which is more efficient if streaming.
trim
Str trim()
Trim whitespace from the beginning and end of the string. For the purposes of this method, whitespace is defined as any character equal to or less than the 0x20 space character (including , \r, \n, and \t).
Examples:
"foo".trim => "foo"
" foo".trim => "foo"
" foo ".trim => "foo"
" foo\n".trim => "foo"
" ".trim => ""trimEnd
Str trimEnd()
Trim whitespace only from the end of the string. See trim for definition of whitespace.
Examples:
"foo".trim => "foo"
" foo ".trim => " foo"trimStart
Str trimStart()
Trim whitespace only from the beginning of the string. See trim for definition of whitespace.
Examples:
"foo".trim => "foo"
" foo ".trim => "foo "trimToNull
Str? trimToNull()
Trim whitespace from the beginning and end of the string. Should the resultant string be empty, null is returned.
For the purposes of this method, whitespace is defined as any character equal to or less than the 0x20 space character (including , \r, \n, and \t).
Examples:
"foo".trimToNull => "foo"
" foo ".trimToNull => "foo"
"".trimToNull => null
" ".trimToNull => nullupper
Str upper()
Return this string with all lowercase characters replaced to uppercase. The case conversion is for ASCII only. Also see lower, localeUpper, Int.upper, Int.localeUpper.
Example:
"Foo Bar".upper => "FOO BAR"StrBuf
class StrBuf : Obj
StrBuf is a mutable sequence of Int characters.
Constructors
| make | Create with initial capacity (defaults to 16). |
Fields
| capacity | The number of characters this buffer can hold without allocating more memory. |
Methods
| add | Add x.toStr to the end of this buffer. |
| addChar | Optimized implementation for add(ch.toChar). |
| addRange | Add a substring of the given string to the buffer. |
| clear | Clear the contents of the string buffer so that it has a size of zero. |
| get | Get the character at the zero based index as a Unicode code point. |
| getRange | Return a substring based on the specified range. |
| insert | Insert x.toStr into this buffer at the specified index. |
| isEmpty | Return if size() == 0. |
| join | Add x.toStr to the end of the buffer. |
| joinNotNull | Call join but only if x is non-null. |
| out | Create an output stream to append characters to this string buffer. |
| remove | Remove the char at the specified index. |
| removeRange | Remove a range of indices from this buffer. |
| replaceRange | Replaces a range of indices from this buffer with the specified string. |
| reverse | Reverse the contents of this string buffer. |
| set | Replace the existing character at index in this buffer. |
| size | Return the number of characters in the buffer. |
| toStr | Return the current buffer contents as a Str. |
Slot Details
add
This add(Obj? x)
Add x.toStr to the end of this buffer. If x is null then the string "null" is inserted. Return this.
addChar
This addChar(Int ch)
Optimized implementation for add(ch.toChar). Return this.
addRange
This addRange(Str s, Range r)
Add a substring of the given string to the buffer. Return this.
capacity
Int capacity
The number of characters this buffer can hold without allocating more memory.
clear
This clear()
Clear the contents of the string buffer so that it has a size of zero. Return this.
get
@Operator Int get(Int index)
Get the character at the zero based index as a Unicode code point. Negative indexes may be used to access from the end of the string buffer. This method is accessed via the [] operator.
getRange
@Operator Str getRange(Range range)
Return a substring based on the specified range. Negative indexes may be used to access from the end of the string buffer. This method is accessed via the [] operator. Throw IndexErr if range illegal.
Examples:
"abcd"[0..2] => "abc"
"abcd"[3..3] => "d"
"abcd"[-2..-1] => "cd"
"abcd"[0..<2] => "ab"
"abcd"[1..-2] => "bc"
"abcd"[4..-1] => ""insert
This insert(Int index, Obj? x)
Insert x.toStr into this buffer at the specified index. If x is null then the string "null" is inserted. Negative indexes may be used to access from the end of the string buffer. Throw IndexErr if index is out of range. Return this.
isEmpty
Bool isEmpty()
Return if size() == 0.
join
This join(Obj? x, Str sep := " ")
Add x.toStr to the end of the buffer. If the buffer is not empty, then first add the specified separator which defaults to a space if not specified. Return this.
joinNotNull
This joinNotNull(Obj? x, Str sep := " ")
Call join but only if x is non-null.
make
new make(Int capacity := 16)
Create with initial capacity (defaults to 16).
out
OutStream out()
Create an output stream to append characters to this string buffer. The output stream is designed to write character data, attempts to do binary writes will throw UnsupportedErr.
remove
This remove(Int index)
Remove the char at the specified index. A negative index may be used to access an index from the end of the list. Size is decremented by 1. Return this. Throw IndexErr if index is out of range.
removeRange
This removeRange(Range r)
Remove a range of indices from this buffer. Negative indexes may be used to access from the end of the list. Throw IndexErr if range illegal. Return this.
replaceRange
This replaceRange(Range r, Str str)
Replaces a range of indices from this buffer with the specified string. Negative indexes may be used to access from the end of the buffer. Throw IndexErr if range illegal. Return this.
reverse
This reverse()
Reverse the contents of this string buffer. Return this.
set
@Operator This set(Int index, Int ch)
Replace the existing character at index in this buffer. Negative indexes may be used to access from the end of the string buffer. This method is accessed via the [] operator. Return this.
size
Int size()
Return the number of characters in the buffer.
toStr
virtual override Str toStr()
Return the current buffer contents as a Str.
Test
abstract class Test : Obj
Test is the base for Fantom unit tests.
See Fant.
Constructors
| make | Protected constructor. |
Methods
| curTestMethod | Get the current test method being executed or throw Err if not currently running a test. |
| fail | Throw a test failure exception. |
| setup | Setup is called before running each test method. |
| teardown | Teardown is called after running every test method. |
| tempDir | Return a temporary test directory which may used as a scratch directory. |
| verify | Verify that cond is true, otherwise throw a test failure exception. |
| verifyEq | Verify that a == b, otherwise throw a test failure exception. |
| verifyErr | Verify that the function throws an Err of the exact same type as errType (compare using === operator). |
| verifyErrMsg | Verify that the function throws an Err. |
| verifyFalse | Verify that cond is false, otherwise throw a test failure exception. |
| verifyNotEq | Verify that a != b, otherwise throw a test failure exception. |
| verifyNotNull | Verify that a is not null, otherwise throw a test failure exception. |
| verifyNotSame | Verify that a !== b, otherwise throw a test failure exception. |
| verifyNull | Verify that a is null, otherwise throw a test failure exception. |
| verifySame | Verify that a === b, otherwise throw a test failure exception. |
| verifyTrue | Verify that cond is true, otherwise throw a test failure exception. |
| verifyType | Verify that Type.of(obj) equals the given type. |
Slot Details
curTestMethod
Method curTestMethod()
Get the current test method being executed or throw Err if not currently running a test. This method is available during both setup and teardown as well as during the test itself.
fail
Void fail(Str? msg := null)
Throw a test failure exception. If msg is non-null, include it in the failure exception.
make
new make()
Protected constructor.
setup
virtual Void setup()
Setup is called before running each test method.
teardown
virtual Void teardown()
Teardown is called after running every test method.
tempDir
File tempDir()
Return a temporary test directory which may used as a scratch directory. This directory is guaranteed to be created and empty the first time this method is called for a given test run. The test directory is "{Env.cur.tempDir}/test/".
verify
Void verify(Bool cond, Str? msg := null)
Verify that cond is true, otherwise throw a test failure exception. If msg is non-null, include it in a failure exception. Identical to verifyTrue.
verifyEq
Void verifyEq(Obj? a, Obj? b, Str? msg := null)
Verify that a == b, otherwise throw a test failure exception. If both a and b are nonnull, then this method also ensures that a.hash == b.hash, because any two objects which return true for equals() must also return the same hash code. If msg is non-null, include it in failure exception.
verifyErr
Void verifyErr(Type? errType, |Test| c)
Verify that the function throws an Err of the exact same type as errType (compare using === operator). If the errType parameter is null, then this method tests only that an exception is thrown, not its type.
Example:
verifyErr(ParseErr#) { x := Int.fromStr("@#!") }verifyErrMsg
Void verifyErrMsg(Type errType, Str errMsg, |Test| c)
Verify that the function throws an Err. The Err must be the exact same type as errType and the contained msg must be the same as errMsg.
Example:
verifyErrMsg(ParseErr#, "Invalid Int: 'ABC'")
{
x := Int.fromStr("ABC")
}verifyFalse
Void verifyFalse(Bool cond, Str? msg := null)
Verify that cond is false, otherwise throw a test failure exception. If msg is non-null, include it in a failure exception.
verifyNotEq
Void verifyNotEq(Obj? a, Obj? b, Str? msg := null)
Verify that a != b, otherwise throw a test failure exception. If msg is non-null, include it in failure exception.
verifyNotNull
Void verifyNotNull(Obj? a, Str? msg := null)
Verify that a is not null, otherwise throw a test failure exception. If msg is non-null, include it in a failure exception.
verifyNotSame
Void verifyNotSame(Obj? a, Obj? b, Str? msg := null)
Verify that a !== b, otherwise throw a test failure exception. If msg is non-null, include it in failure exception.
verifyNull
Void verifyNull(Obj? a, Str? msg := null)
Verify that a is null, otherwise throw a test failure exception. If msg is non-null, include it in a failure exception.
verifySame
Void verifySame(Obj? a, Obj? b, Str? msg := null)
Verify that a === b, otherwise throw a test failure exception. If msg is non-null, include it in failure exception.
verifyTrue
Void verifyTrue(Bool cond, Str? msg := null)
Verify that cond is true, otherwise throw a test failure exception. If msg is non-null, include it in a failure exception. Identical to verify.
verifyType
Void verifyType(Obj obj, Type t)
Verify that Type.of(obj) equals the given type.
TestErr
const class TestErr : Err
TestErr is thrown by Test when a test method fails a verify.
Constructors
| make | Construct with specified error message and optional root cause. |
Slot Details
make
new make(Str? msg := null, Err? cause := null)
Construct with specified error message and optional root cause.
This
const class This : Obj
This represents a method return type which is always this type.
Slot Details
Time
@Serializable { simple=true } const class Time : Obj
Time represents a time of day independent of a specific date or timezone.
Constructors
| fromStr | Parse the string into a Time from the programmatic encoding defined by toStr. |
| make | Make for the specified time values |
Fields
| defVal | Default value is "00:00:00". |
Methods
| compare | Compare based on hour, min, sec, and ns values. |
| equals | Two times are equal if have identical hour, min, sec, and ns values. |
| fromDuration | Translate a duration of time which has elapsed since midnight into a Time of day. |
| fromIso | Parse an ISO 8601 time. |
| fromLocale | Parse a string into a Time using the given pattern. |
| hash | Return hash of hour, min, sec, and ns values. |
| hour | Get the hour of the time as a number between 0 and 23. |
| isMidnight | Return if "00:00:00" which is equal to defVal. |
| min | Get the minutes of the time as a number between 0 and 59. |
| minus | Subtract the specified duration to this time. |
| nanoSec | Get the number of nanoseconds (the fraction of seconds) as a number between 0 and 999,999,999. |
| now | Get the current time using the specified timezone. |
| plus | Add the specified duration to this time. |
| sec | Get the whole seconds of the time as a number between 0 and 59. |
| toCode | Get this Time as a Fantom expression suitable for code generation. |
| toDateTime | Combine this Time with the given Date to return a DateTime. |
| toDuration | Return the duration of time which has elapsed since midnight. |
| toIso | Format this instance according to ISO 8601 using the pattern |
| toLocale | Format this date according to the specified pattern. |
| toStr | Return programmatic ISO 8601 string encoding formatted as follows |
Slot Details
compare
virtual override Int compare(Obj obj)
Compare based on hour, min, sec, and ns values.
defVal
const static Time defVal
Default value is "00:00:00".
equals
virtual override Bool equals(Obj? that)
Two times are equal if have identical hour, min, sec, and ns values.
fromDuration
static Time fromDuration(Duration d)
Translate a duration of time which has elapsed since midnight into a Time of day. See toDuration. If the duration is not between 0 and 24hr throw ArgErr.
Example:
Time.fromDuration(150min) => 02:30:00fromIso
static Time? fromIso(Str s, Bool checked := true)
Parse an ISO 8601 time. If invalid format and checked is false return null, otherwise throw ParseErr. The following format is supported:
hh:mm:ss.FFFFFFFFFAlso see toIso and fromStr.
fromLocale
static Time? fromLocale(Str str, Str pattern, Bool checked := true)
Parse a string into a Time using the given pattern. If string is not a valid format then return null or raise ParseErr based on checked flag. See toLocale for pattern syntax.
fromStr
static new fromStr(Str s, Bool checked := true)
Parse the string into a Time from the programmatic encoding defined by toStr. If the string cannot be parsed into a valid Time and checked is false then return null, otherwise throw ParseErr.
hash
virtual override Int hash()
Return hash of hour, min, sec, and ns values.
hour
Int hour()
Get the hour of the time as a number between 0 and 23.
isMidnight
Bool isMidnight()
Return if "00:00:00" which is equal to defVal.
make
static new make(Int hour, Int min, Int sec := 0, Int ns := 0)
Make for the specified time values:
- hour: 0-23
- min: 0-59
- sec: 0-59
- ns: 0-999_999_999
Throw ArgErr if any of the parameters are out of range.
min
Int min()
Get the minutes of the time as a number between 0 and 59.
minus
@Operator Time minus(Duration dur)
Subtract the specified duration to this time. Throw ArgErr if dur is not between 0 and 24hr. Overflows will rollover.
Example:
Time(5,0,0) - 30min => 04:30:00nanoSec
Int nanoSec()
Get the number of nanoseconds (the fraction of seconds) as a number between 0 and 999,999,999.
now
static Time now(TimeZone tz := TimeZone.cur())
Get the current time using the specified timezone. This method may use DateTime.now with the default tolerance 250ms.
plus
@Operator Time plus(Duration dur)
Add the specified duration to this time. Throw ArgErr if dur is not between 0 and 24hr. Overflows will rollover.
Example:
Time(5,0,0) + 30min => 05:30:00sec
Int sec()
Get the whole seconds of the time as a number between 0 and 59.
toCode
Str toCode()
Get this Time as a Fantom expression suitable for code generation.
toDateTime
DateTime toDateTime(Date d, TimeZone tz := TimeZone.cur())
Combine this Time with the given Date to return a DateTime.
toDuration
Duration toDuration()
Return the duration of time which has elapsed since midnight. See fromDuration.
Example:
Time(2, 30).toDuration => 150mintoIso
Str toIso()
Format this instance according to ISO 8601 using the pattern:
hh:mm:ss.FFFFFFFFFAlso see fromIso and toStr.
toLocale
Str toLocale(Str? pattern := null, Locale locale := Locale.cur())
Format this date according to the specified pattern. If pattern is null, then a localized default is used. The pattern format is the same as DateTime.toLocale:
h One digit 24 hour (0-23) 3, 22
hh Two digit 24 hour (0-23) 03, 22
k One digit 12 hour (1-12) 3, 11
kk Two digit 12 hour (1-12) 03, 11
m One digit minutes (0-59) 4, 45
mm Two digit minutes (0-59) 04, 45
s One digit seconds (0-59) 4, 45
ss Two digit seconds (0-59) 04, 45
SS Optional seconds (only if non-zero)
f* Fractional secs trailing zeros
F* Fractional secs no trailing zeros
a Lower case a/p for am/pm a, p
aa Lower case am/pm am, pm
A Upper case A/P for am/pm A, P
AA Upper case AM/PM AM, PM
'xyz' Literal charactersA symbol immediately preceding a "F" pattern with no fraction to print is skipped.
toStr
virtual override Str toStr()
Return programmatic ISO 8601 string encoding formatted as follows:
hh:mm:ss.FFFFFFFFF
12:06:00.0Also see fromStr, toIso, and toLocale.
TimeZone
@Serializable { simple=true } const class TimeZone : Obj
TimeZone represents a region's offset from UTC and its daylight savings time rules. TimeZones are historical - UTC offset and DST rules may change depending on the year. The Fantom implementation of historical time zones is optimized to handle only year boundaries (so some historical changes which don't occur on year boundaries may not be 100% accurate).
The Fantom time zone database and naming model is based on the ZoneInfo database used by UNIX and Java. All time zones have both a simple name and a fullName. The fullName is the full identifier used in the zoneinfo database such as "America/New_York". The simple name is the city name only such as "New_York".
Use cur to get current default timezone for VM.
Also see docLang.
Constructors
| fromStr | Find a time zone by name from the built-in database |
Methods
| cur | Get the current default TimeZone of the VM. |
| defVal | Default value is UTC. |
| dstAbbr | Get the abbreviated name during daylight savings time or null if daylight savings time not observed. |
| dstOffset | Get the duration of time which will be added to local standard time to get wall time during daylight savings time (often 1hr). |
| fullName | Get the full name of this time zone as defined by the zoneinfo database. |
| listFullNames | List all zoneinfo (Olson database) full names of the time zones available in the local time zone database. |
| listNames | List the names of all the time zones available in the local time zone database. |
| name | Get the identifier of this time zone in the time zone database. |
| offset | Get the duration of time added to UTC to compute standard time in this time zone. |
| rel | Relative time zone instance is "Etc/Rel". |
| stdAbbr | Get the abbreviated name during standard time. |
| toStr | Return name. |
| utc | UTC time zone instance is "Etc/Utc". |
Slot Details
cur
static TimeZone cur()
Get the current default TimeZone of the VM. The default timezone is configured by the Java or .NET runtime or it can be manually configured in "etc/sys/config.props" with the key "timezone" and any value accepted by fromStr. Once Fantom is booted, the default timezone cannot be changed.
defVal
static TimeZone defVal()
Default value is UTC.
dstAbbr
Str? dstAbbr(Int year)
Get the abbreviated name during daylight savings time or null if daylight savings time not observed.
dstOffset
Duration? dstOffset(Int year)
Get the duration of time which will be added to local standard time to get wall time during daylight savings time (often 1hr). If daylight savings time is not observed then return null.
fromStr
static new fromStr(Str name, Bool checked := true)
Find a time zone by name from the built-in database:
- First check for simple name like "New_York" or the zoneinfo full name "America/New_York"
- Attempt to match against timezone aliases, if a match is found return the canonical TimeZone instance
- If no matches are found and checked is false then return null, otherwise throw ParseErr.
Also see:
fullName
Str fullName()
Get the full name of this time zone as defined by the zoneinfo database. These names are formatted as "continent/location" where location is a major city within the time zone region. Examples of full names are "America/New_York" and "Europe/London".
listFullNames
static Str[] listFullNames()
List all zoneinfo (Olson database) full names of the time zones available in the local time zone database. This list is the full names only such as "America/New_York" and "Europe/London".
listNames
static Str[] listNames()
List the names of all the time zones available in the local time zone database. This database is stored in "{home}/lib/timezone.ftz" as a binary file. This list contains only the simple names such as "New_York" and "London".
name
Str name()
Get the identifier of this time zone in the time zone database. Name is the city name portion of the zoneinfo fullName identifier such as "New_York" or "London".
offset
Duration offset(Int year)
Get the duration of time added to UTC to compute standard time in this time zone. The offset is independent of daylight savings time - during daylight savings the actual offset is this value plus dstOffset.
rel
static TimeZone rel()
Relative time zone instance is "Etc/Rel". The relative timezone has a zero offset like UTC, but is used to normalize by time of day versus absolute time. See DateTime.toRel and docLang.
stdAbbr
Str stdAbbr(Int year)
Get the abbreviated name during standard time.
toStr
virtual override Str toStr()
Return name.
utc
static TimeZone utc()
UTC time zone instance is "Etc/Utc".
TimeoutErr
const class TimeoutErr : Err
TimeoutErr indicates that a blocking operation timed out before normal completion.
Constructors
| make | Construct with specified error message and optional root cause. |
Slot Details
make
new make(Str msg := "", Err? cause := null)
Construct with specified error message and optional root cause.
Transient
facet class Transient : Obj, Facet
Transient annotates fields which should not be serialized. It is used inside a Serializable type. See the Serialization Doc for details.
Fields
| defVal | Singleton for Transient facet. |
Slot Details
defVal
const static Transient defVal := ...
Singleton for Transient facet.
Type
const class Type : Obj
Type defines the contract of an Obj by the slots it supports. Types model the inheritance relationships and provide a mapping for all the slots both inherited and declared.
Methods
| base | The direct super class of this type (null for Obj). |
| doc | Return the raw fandoc for this type or null if not available. |
| emptyList | Return an immutable empty list of this type. |
| facet | Get a facet by its type. |
| facets | Get the list of facets defined on this type or return an empty list if no facets are defined. |
| field | Convenience for (Field)slot(name, checked) |
| fields | List of all the defined fields (including inherited fields). |
| find | Find a Type by its qualified name "pod::Type". |
| fits | Does this type implement the specified type. |
| hasFacet | Return if this type has the specified facet defined. |
| inheritance | Return a recursive flattened list of all the types this type inherits from. |
| isAbstract | Return if this Type is abstract and cannot be instantiated. |
| isClass | Return if this Type is a class (as opposed to enum or mixin) |
| isConst | Return if this is a const class which means instances of this class are immutable. |
| isEnum | Return if this Type is an Enum type. |
| isFacet | Return if this Type is a Facet type. |
| isFinal | Return if this Type is marked final which means it may not be subclassed. |
| isGeneric | A generic type contains slot signatures which may be parameterized - for example Map's key and value types are generic as K and V. |
| isInternal | Return if this Type has internal protection scope. |
| isMixin | Return if this Type is a mixin type and cannot be instantiated. |
| isNullable | Is this a nullable type. |
| isPublic | Return if this Type has public protection scope. |
| isSynthetic | Return if this Type was generated by the compiler. |
| isVal | Is this a value type. |
| make | Create a new instance of this Type using the following rules |
| method | Convenience for (Method)slot(name, checked) |
| methods | List of all the defined methods (including inherited methods). |
| mixins | Return the mixins directly implemented by this type. |
| name | Simple name of the type such as "Str". |
| of | Get the class Type of the given instance. |
| parameterize | If this is a generic type, then dynamically create a new parameterized type with the specified name to type map. |
| params | If this is a parameterized type, then return the map of names to types. |
| pod | Parent pod which defines this type. |
| qname | Qualified name formatted as "pod::name". |
| signature | Return the formal signature of this type. |
| slot | Lookup a slot by name. |
| slots | List of all the defined slots, both fields and methods (including inherited slots). |
| toListOf | Convenience for List#.parameterize(["V":this]) |
| toLocale | Return signature. |
| toNonNullable | Return this type as a non-nullable type. |
| toNullable | Return this type as a nullable type. |
| toStr | Always return signature(). |
Slot Details
base
Type? base()
The direct super class of this type (null for Obj). Return sys::Obj for all mixin types.
Examples:
Obj#.base => null
Int#.base => sys::Num
OutStream#.base => sys::Objdoc
Str? doc()
Return the raw fandoc for this type or null if not available.
emptyList
Obj[] emptyList()
Return an immutable empty list of this type. Since immutable lists can be used safely everywhere, this allows signficant memory savings instead of allocating new empty lists.
Examples:
Str#.emptyList => Str[,]facet
Facet? facet(Type type, Bool checked := true)
Get a facet by its type. If not found on this type then return null or throw UnknownFacetErr based on check flag. See Facets Doc for details.
facets
Facet[] facets()
Get the list of facets defined on this type or return an empty list if no facets are defined. If looking up a facet by type, then use the facet method which will provide better performance. See Facets Doc for details.
field
Field? field(Str name, Bool checked := true)
Convenience for (Field)slot(name, checked)
fields
Field[] fields()
List of all the defined fields (including inherited fields).
find
static Type? find(Str qname, Bool checked := true)
Find a Type by its qualified name "pod::Type". If the type doesn't exist and checked is false then return null, otherwise throw UnknownTypeErr.
fits
Bool fits(Type t)
Does this type implement the specified type. If true, then this type is assignable to the specified type (although the converse is not necessarily true). This method provides the same semantics as the is operator, but between two types rather than an instance and a type. All types (including mixin types) fit sys::Obj.
This method implicitly ignores the nullability of both this and t such that this method is always equivalent to:
this.toNonNullable.fits(t.toNonNullable)Example:
Float#.fits(Float#) => true
Float#.fits(Num#) => true
Float#.fits(Obj#) => true
Float#.fits(Str#) => false
Obj#.fits(Float#) => falsehasFacet
Bool hasFacet(Type type)
Return if this type has the specified facet defined.
inheritance
Type[] inheritance()
Return a recursive flattened list of all the types this type inherits from. The result list always includes this type itself. The result of this method represents the complete list of types implemented by this type - instances of this type are assignable to any type in this list. All types (including mixins) will include sys::Obj in this list.
Examples:
Obj#.inheritance => [sys::Obj]
Int#.inheritance => [sys::Int, sys::Num, sys::Obj]isAbstract
Bool isAbstract()
Return if this Type is abstract and cannot be instantiated. This method will always return true if the type is a mixin.
isClass
Bool isClass()
Return if this Type is a class (as opposed to enum or mixin)
isConst
Bool isConst()
Return if this is a const class which means instances of this class are immutable.
isEnum
Bool isEnum()
Return if this Type is an Enum type.
isFacet
Bool isFacet()
Return if this Type is a Facet type.
isFinal
Bool isFinal()
Return if this Type is marked final which means it may not be subclassed.
isGeneric
Bool isGeneric()
A generic type contains slot signatures which may be parameterized - for example Map's key and value types are generic as K and V. Fantom supports three built-in generic types: List, Map, and Func. A parameterized type such as Str[] is not a generic type (all of its generic parameters have been filled in). User defined generic types are not supported in Fantom.
Examples:
Str#.isGeneric => false
List#.isGeneric => true
Str[]#.isGeneric => falseisInternal
Bool isInternal()
Return if this Type has internal protection scope.
isMixin
Bool isMixin()
Return if this Type is a mixin type and cannot be instantiated.
isNullable
Bool isNullable()
Is this a nullable type. Nullable types can store the null value, but non-nullables are never null. Null types are indicated with a trailing "?".
isPublic
Bool isPublic()
Return if this Type has public protection scope.
isSynthetic
Bool isSynthetic()
Return if this Type was generated by the compiler.
isVal
Bool isVal()
Is this a value type. Fantom supports three implicit value types: Bool, Int, and Float.
make
Obj make(Obj[]? args := null)
Create a new instance of this Type using the following rules:
- Call public constructor
makewith specified arguments - If no public constructor called
makeor invalid number of of required arguments, then return value ofdefValslot (must be static field or static method with zero params) - If no public
defValfield, then throw Err
method
Method? method(Str name, Bool checked := true)
Convenience for (Method)slot(name, checked)
methods
Method[] methods()
List of all the defined methods (including inherited methods).
mixins
Type[] mixins()
Return the mixins directly implemented by this type.
Examples:
Obj#.mixins => [,]
Buf#.mixins => [sys::InStream, sys::OutStream]
OutStream#.mixins => [,]name
Str name()
Simple name of the type such as "Str". For parameterized types derived from List, Map, or Func, this method always returns "List", "Map", or "Func" respectively.
Examples:
Str#.name => "Str"
acme::Foo#.name => "Foo"
acme::Foo[]#.name => "List"of
static Type of(Obj obj)
Get the class Type of the given instance. Also see Obj.typeof which provides the same functionality.
parameterize
Type parameterize(Str:Type params)
If this is a generic type, then dynamically create a new parameterized type with the specified name to type map. If this type is not generic then throw UnsupportedErr. Throw ArgErr if params fails to specify the required parameters:
List => V required
Map => K, V required
Func => R required, A-H optionalExamples:
List#.parameterize(["V":Bool#]) => Bool[]
Map#.parameterize(["K":Str#, "V":Obj#]) => Str:Objparams
Str:Type params()
If this is a parameterized type, then return the map of names to types. If this is not a parameterized type return an empty map.
Examples:
Str#.params => [:]
Str[]#.params => ["V":Str, "L":Str[]]
Int:Slot#.params => ["K":Int, "V":Slot, "M":Int:Slot]
|Int x, Float y->Bool|#.params => ["A":Int, "B":Float, "R":Bool]Pod? pod()
Parent pod which defines this type. For parameterized types derived from List, Map, or Func, this method always returns the sys pod.
Examples:
Str#.pod => sys
acme::Foo#.pod => acme
acme::Foo[]#.pod => sysqname
Str qname()
Qualified name formatted as "pod::name". For parameterized types derived from List, Map, or Func, this method always returns "sys::List", "sys::Map", or "sys::Func" respectively. If this is a nullable type, the qname does not include the "?".
Examples:
Str#.qname => "sys::Str"
Str?#.qname => "sys::Str"
acme::Foo#.qname => "acme::Foo"
acme::Foo[]#.qname => "sys::List"signature
Str signature()
Return the formal signature of this type. In the case of non-parameterized types the signature is the same as qname. For parameterized types derived from List, Map, or Func the signature uses the following special syntax:
List => V[]
Map => [K:V]
Func => |A,B...->R|If this is a nullable type, the signature ends with "?" such as "sys::Int?".
Examples:
Str#.signature => "sys::Str"
Str?#.signature => "sys::Str?"
Int[]#.signature => "sys::Int[]"
Int:Str#.signature => "[sys::Int:sys::Str]"
Str:Buf[]#.signature => [sys::Str:sys::Buf[]]
|Float x->Bool|#.signature => "|sys::Float->sys::Bool|"
|Float x, Int y|#.signature => |sys::Float,sys::Int->sys::Void|slot
Slot? slot(Str name, Bool checked := true)
Lookup a slot by name. If the slot doesn't exist and checked is false then return null, otherwise throw UnknownSlotErr. Slots are any field or method in this type's scope including those defined directly by this type and those inherited from super class or mixins.
slots
Slot[] slots()
List of all the defined slots, both fields and methods (including inherited slots).
toListOf
Type toListOf()
Convenience for List#.parameterize(["V":this])
Examples:
Int#.toListOf => Int[]
Str[]#.toListOf => Str[][]toLocale
Str toLocale()
Return signature. This method is used to enable toLocale to be used with duck typing across most built-in types. Note: we may change the specification of this method in the future to allow localized type names.
toNonNullable
Type toNonNullable()
Return this type as a non-nullable type. If this type is already non-nullable then return this.
toNullable
Type toNullable()
Return this type as a nullable type. If this type is already nullable then return this.
toStr
virtual override Str toStr()
Always return signature().
Unit
@Serializable { simple=true } const class Unit : Obj
Unit models a unit of measurement. Units are represented as:
- ids: each unit has one or more unique identifiers for the unit within the VM. Units are typically defined in the unit database "etc/sys/units.txt" or can be via by the
definemethod. Every id assigned to a unit must be unique within the VM. - name: the first identifier in the ids list is called the name and should be a descriptive summary of the unit using words separated by underbar such as "miles_per_hour".
- symbol: the last identifier in the ids list should be the abbreviated symbol; for example "kilogram" has the symbol "kg". In units with only one id, the symbol is the same as the name. Units with exponents should use Unicode superscript chars, not ASCII digits.
- dimension: defines the ratio of the seven SI base units: m, kg, sec, A, K, mol, and cd
- scale/factor: defines the normalization equations for unit conversion
A unit identifier is limited to the following characters:
- any Unicode char over 128
- ASCII letters
a-zandA-Z - underbar
_ - division sign
/ - percent sign
% - dollar sign
$
Units with equal dimensions are considered to measure the same physical quantity. This is not always true, but good enough for practice. Conversions with the convertTo method are expressed with the following equations:
unit = dimension * scale + offset
toNormal = scalar * scale + offset
fromNormal = (scalar - offset) / scale
toUnit = fromUnit.fromNormal( toUnit.toNormal(sclar) )As a simple, pragmatic solution for modeling Units, there are some units which don't fit this model including logarithm and angular units. Units which don't cleanly fit this model should be represented as dimensionless (all ratios set to zero).
Fantom's model for units of measurement and the unit database are derived from the OASIS oBIX specification.
Constructors
| fromStr | Find a unit by one of its identifiers if it has been defined in this VM. |
Methods
| A | Ampere (electric current) component of the unit dimension. |
| K | Kelvin (thermodynamic temperature) component of the unit dimension. |
| cd | Candela (luminous intensity) component of the unit dimension. |
| convertTo | Convert a scalar value from this unit to the given unit. |
| define | Define a new Unit definition in the VM's unit database using the following string format |
| definition | Return string format as specified by define. |
| dim | Return the string format of the dimension portion of definition |
| div | Match quotient of this divided by b against current database definitions. |
| equals | Two units are equal if they have reference equality because all units are interned during definition. |
| hash | Return toStr.hash. |
| ids | Return the list of programmatic identifiers for this unit. |
| kg | Kilogram (mass) component of the unit dimension. |
| list | List all the units currently defined in the VM. |
| m | Meter (length) component of the unit dimension. |
| mol | Mole (amount of substance) component of the unit dimension. |
| mult | Match the product of this and b against current database definitions. |
| name | Return the primary name identifier of this unit. |
| offset | Return the offset factor used to convert this unit "from normal". |
| quantities | List the quantity names used to organize the unit database in "etc/sys/units.txt". |
| quantity | Get the units organized under a specific quantity name in the unit database "etc/sys/units.txt". |
| scale | Return the scale factor used to convert this unit "from normal". |
| sec | Second (time) component of the unit dimension. |
| symbol | Return the abbreviated symbol for this unit. |
| toStr | Return symbol. |
Slot Details
A
Int A()
Ampere (electric current) component of the unit dimension.
K
Int K()
Kelvin (thermodynamic temperature) component of the unit dimension.
cd
Int cd()
Candela (luminous intensity) component of the unit dimension.
convertTo
Float convertTo(Float scalar, Unit unit)
Convert a scalar value from this unit to the given unit. If the units do not have the same dimension then throw Err. For example, to convert 3km to meters:
m := Unit("meter")
km := Unit("kilometer")
km.convertTo(3f, m) => 3000fdefine
static Unit define(Str s)
Define a new Unit definition in the VM's unit database using the following string format:
unit := <ids> [";" <dim> [";" <scale> [";" <offset>]]]
names := <ids> ("," <id>)*
id := <idChar>*
idChar := 'a'-'z' | 'A'-'Z' | '_' | '%' | '/' | any char > 128
dim := <ratio> ["*" <ratio>]* // no whitespace allowed
ratio := <base> <exp>
base := "kg" | "m" | "sec" | "K" | "A" | "mol" | "cd"
exp := <int>
scale := <float>
offset := <float>If the format is incorrect or any identifiers are already defined then throw an exception.
definition
Str definition()
Return string format as specified by define.
dim
Str dim()
Return the string format of the dimension portion of definition
div
@Operator Unit div(Unit b)
Match quotient of this divided by b against current database definitions. If an unambiguous match cannot be made then throw Err.
equals
virtual override Bool equals(Obj? that)
Two units are equal if they have reference equality because all units are interned during definition.
fromStr
static new fromStr(Str s, Bool checked := true)
Find a unit by one of its identifiers if it has been defined in this VM. If the unit isn't defined yet and checked is false then return null, otherwise throw Err. Any units declared in "etc/sys/units.txt" are implicitly defined.
hash
virtual override Int hash()
Return toStr.hash.
ids
Str[] ids()
Return the list of programmatic identifiers for this unit. The first item is always name and the last is always symbol.
kg
Int kg()
Kilogram (mass) component of the unit dimension.
list
static Unit[] list()
List all the units currently defined in the VM. Any units declared in "etc/sys/units.txt" are implicitly defined.
m
Int m()
Meter (length) component of the unit dimension.
mol
Int mol()
Mole (amount of substance) component of the unit dimension.
mult
@Operator Unit mult(Unit that)
Match the product of this and b against current database definitions. If an unambiguous match cannot be made then throw Err.
name
Str name()
Return the primary name identifier of this unit. This is always the first item in ids.
offset
Float offset()
Return the offset factor used to convert this unit "from normal". See class header for normalization and conversion equations. Offset is used most commonly with temperature units. The offset for normalized unit is always zero.
quantities
static Str[] quantities()
List the quantity names used to organize the unit database in "etc/sys/units.txt". Quantities are merely a convenient mechanism to organize the unit database - there is no guarantee that they include all current VM definitions.
quantity
static Unit[] quantity(Str quantity)
Get the units organized under a specific quantity name in the unit database "etc/sys/units.txt". Quantities are merely a convenient mechanism to organize the unit database - there is no guarantee that they include all current VM definitions.
scale
Float scale()
Return the scale factor used to convert this unit "from normal". For example the scale factor for kilometer is 1000 because it is defined as a 1000 meters where meter is the normalized unit for length. See class header for normalization and conversion equations. The scale factor for the normalized unit is always one.
sec
Int sec()
Second (time) component of the unit dimension.
symbol
Str symbol()
Return the abbreviated symbol for this unit. This is always the last item in ids.
toStr
virtual override Str toStr()
Return symbol.
UnknownFacetErr
const class UnknownFacetErr : Err
UnknownFacetErr indicates an attempt to access an undefined facet.
Constructors
| make | Construct with specified error message and optional root cause. |
Slot Details
make
new make(Str msg := "", Err? cause := null)
Construct with specified error message and optional root cause.
UnknownKeyErr
const class UnknownKeyErr : Err
UnknownKeyErr indicates an attempt to lookup a non-existent key.
Constructors
| make | Construct with specified error message and optional root cause. |
Slot Details
make
new make(Str msg := "", Err? cause := null)
Construct with specified error message and optional root cause.
UnknownPodErr
const class UnknownPodErr : Err
UnknownPodErr indicates an attempt to access a non-existent pod.
Constructors
| make | Construct with specified error message and optional root cause. |
Slot Details
make
new make(Str msg := "", Err? cause := null)
Construct with specified error message and optional root cause.
UnknownServiceErr
const class UnknownServiceErr : Err
UnknownServiceErr indicates an attempt to lookup a service which is not installed. See Service.find.
Constructors
| make | Construct with specified error message and optional root cause. |
Slot Details
make
new make(Str msg := "", Err? cause := null)
Construct with specified error message and optional root cause.
UnknownSlotErr
const class UnknownSlotErr : Err
UnknownSlotErr indicates an attempt to access a non-existent slot.
Constructors
| make | Construct with specified error message and optional root cause. |
Slot Details
make
new make(Str msg := "", Err? cause := null)
Construct with specified error message and optional root cause.
UnknownTypeErr
const class UnknownTypeErr : Err
UnknownTypeErr indicates an attempt to access a non-existent type.
Constructors
| make | Construct with specified error message and optional root cause. |
Slot Details
make
new make(Str msg := "", Err? cause := null)
Construct with specified error message and optional root cause.
UnresolvedErr
const class UnresolvedErr : Err
UnresolvedErr indicates the failure to resolve a Uri to a resource.
Constructors
| make | Construct with specified error message and optional root cause. |
Slot Details
make
new make(Str msg := "", Err? cause := null)
Construct with specified error message and optional root cause.
Unsafe
const class Unsafe : Obj
Unsafe wraps a mutable object as an immutable reference.
Constructors
| make | Wrap specified object. |
Methods
| val | Get the wrapped object. |
Slot Details
make
new make(Obj? val)
Wrap specified object.
val
Obj? val()
Get the wrapped object.
UnsupportedErr
const class UnsupportedErr : Err
UnsupportedErr indicates a feature which isn't supported.
Constructors
| make | Construct with specified error message and optional root cause. |
Slot Details
make
new make(Str msg := "", Err? cause := null)
Construct with specified error message and optional root cause.
Uri
@Serializable { simple=true } const class Uri : Obj
Uri is used to immutably represent a Universal Resource Identifier according to RFC 3986. The generic format for a URI is:
<uri> := [<scheme> ":"] <body>
<body> := ["//" <auth>] ["/" <path>] ["?" <query>] ["#" <frag>]
<auth> := [<userInfo> "@"] <host> [":" <port>]
<path> := <name> ("/" <name>)*
<name> := <basename> ["." <ext>]
<query> := <queryPair> (<querySep> <queryPair>)*
<querySep> := "&" | ";"
<queryPair> := <queryKey> ["=" <queryVal>]
<gen-delims> := ":" / "/" / "?" / "#" / "[" / "]" / "@"Uris are expressed in the following forms:
- Standard Form: any char allowed, general delimiters are "" escaped
- Encoded Form:
%HHpercent encoded
In standard form the full range of Unicode characters is allowed in all sections except the general delimiters which separate sections. For example ? is barred in any section before the query, but is permissible in the query string itself or the fragment identifier. The scheme must be strictly defined in terms of ASCII alphanumeric, ".", "+", or "-". Any general delimiter used outside of its normal role, must be escaped using the "" backslash character. The backslash itself is escaped as "\". For example a filename with the "#" character is represented as "file #2". Only the path, query, and fragment sections can use escaped general delimiters; the scheme and authority sections cannot use escaped general delimiters.
Encoded form as defined by RFC 3986 uses a stricter set of rules for the characters allowed in each section of the URI (scheme, userInfo, host, path, query, and fragment). Any character outside of the allowed set is UTF-8 encoded into octets and %HH percent encoded. The encoded form should be used when working with external applications such as HTTP, HTML, or XML.
The Uri API is designed to work with the standard form of the Uri. Access methods like host, pathStr, or queryStr all use standard form. To summarize different ways of working with Uri:
Uri.fromStr: parses a string from its standard formUri.toStr: returns the standard formUri.decode: parses a string from percent encoded formUri.encode: translate into percent encoded form
Uri can be used to model either absolute URIs or relative references. The plus and relTo methods can be used to resolve and relativize relative references against a base URI.
Constructors
| fromStr | Parse the specified string into a Uri. |
Fields
| defVal | Default value is ``. |
| sectionFrag | Fragment token section flag |
| sectionPath | Path token section flag |
| sectionQuery | Query token section flag |
Methods
| auth | The authority represents a network endpoint in the format |
| basename | Return file name without the extension (everything up to the last dot) or "" if name is "". |
| checkName | If the specified string is not a valid name according to the isName method, then throw NameErr. |
| decode | Parse an ASCII percent encoded string into a Uri according to RFC 3986. |
| decodeQuery | Decode a map of query parameters which are URL encoded according to the "application/x-www-form-urlencoded" MIME type. |
| decodeToken | Unescape "%xx" percent encoded string to its normalized form for the given section. |
| encode | Return the percent encoded string for this Uri according to RFC 3986. |
| encodeQuery | Encode a map of query parameters into URL percent encoding according to the "application/x-www-form-urlencoded" MIME type. |
| encodeToken | Encode a token so that any invalid character or delimiter for the given section is "%xx" percent encoding. |
| equals | Two Uris are equal if they have same string normalized representation. |
| escapeToken | Escape a token so that any delimiter for the given section is backslash escaped for use in normalized URI form. |
| ext | Return file name extension (everything after the last dot) or null if name is null or name has no dot. |
| frag | Return the fragment component of the Uri which is everything after the "#". |
| get | Resolve this Uri into a Fantom object. |
| getRange | Return a new Uri based on a slice of this Uri's path. |
| getRangeToPathAbs | Return a slice of this Uri's path using the same semantics as getRange. |
| hash | Return a hash code based on the normalized string representation. |
| host | Return the host address of the URI or null if not available. |
| isAbs | Return if an absolute Uri which means it has a non-null scheme. |
| isDir | A Uri represents a directory if it has a non-null path which ends with a "/" slash. |
| isName | Return if the specified string is a valid name segment to use in an unencoded URI. |
| isPathAbs | Return if the path starts with a leading slash. |
| isPathOnly | Return if this Uri contains only a path component. |
| isPathRel | Return logical-not of isPathAbs when path is empty or does not start with a leading slash. |
| isRel | Return if a relative Uri which means it has a null scheme. |
| mimeType | Return the MimeType mapped by the ext or null if no mapping. |
| name | Return simple file name which is path.last or "" if the path is empty. |
| parent | Return the parent directory of this Uri or null if a parent path cannot be computed from this Uri. |
| path | Return the path parsed into a list of simple names or an empty list if the pathStr is "" or "/". |
| pathOnly | Return a new Uri with only a path part. |
| pathStr | Return the path component of the Uri. |
| plus | Return a new Uri with the specified Uri appended to this Uri. |
| plusName | Return a new Uri with a single path name appended to this Uri. |
| plusQuery | Add the specified query key/value pairs to this Uri. |
| plusSlash | Add a trailing slash to the path string of this Uri to make it a directory Uri. |
| port | Return the IP port of the host for the network end point. |
| query | Return the query parsed as a map of key/value pairs. |
| queryStr | Return the query component of the Uri which is everything after the "?" but before the "#" fragment. |
| relTo | Relativize this uri against the specified base. |
| relToAuth | Relativize this uri against its authority. |
| scheme | Return the scheme component or null if not absolute. |
| toCode | Get this Uri as a Fantom code literal. |
| toFile | If scheme is non-null, then this is convenience for get cast to a File. |
| toLocale | Return toStr. |
| toStr | Return normalized string representation. |
| unescapeToken | Unescape all backslash escape sequences. |
| userInfo | User info is string information embedded in the authority using the "@" character. |
Slot Details
auth
Str? auth()
The authority represents a network endpoint in the format:
[<userInfo> "@"] host [":" <port>]Examples:
`http://user@host:99/`.auth => "user@host:99"
`http://host/`.auth => "host"
`/dir/file.txt`.auth => nullbasename
Str basename()
Return file name without the extension (everything up to the last dot) or "" if name is "".
Examples:
`/`.basename => ""
`/a/file.txt`.basename => "file"
`/a/file`.basename => "file"
`/a/file.`.basename => "file"
`..`.basename => ".."checkName
static Void checkName(Str name)
If the specified string is not a valid name according to the isName method, then throw NameErr.
decode
static Uri? decode(Str s, Bool checked := true)
Parse an ASCII percent encoded string into a Uri according to RFC 3986. All %HH escape sequences are translated into octets, and then the octet sequence is UTF-8 decoded into a Str. The + character in the query section is unescaped into a space. If checked is true then throw ParseErr if the string is a malformed URI or if not encoded correctly, otherwise return null. Refer to fromStr for normalization rules.
decodeQuery
static Str:Str decodeQuery(Str s)
Decode a map of query parameters which are URL encoded according to the "application/x-www-form-urlencoded" MIME type. This method will unescape % percent encoding and + into space. The parameters are parsed into map using the same semantics as Uri.query. Throw ArgErr if the string is malformed. See encodeQuery.
decodeToken
static Str decodeToken(Str s, Int section)
Unescape "%xx" percent encoded string to its normalized form for the given section. Any delimiters for the section are backslash escaped. Section must be sectionPath, sectionQuery, or sectionFrag. Also see encodeToken.
Examples:
Uri.decodeToken("a%2Fb%23c", Uri.sectionPath) => "a\/b\#c"
Uri.decodeToken("a%3Db/c", Uri.sectionQuery) => "a\=b/c"defVal
const static Uri defVal
Default value is ``.
encode
Str encode()
Return the percent encoded string for this Uri according to RFC 3986. Each section of the Uri is UTF-8 encoded into octets and then percent encoded according to its valid character set. Spaces in the query section are encoded as +.
encodeQuery
static Str encodeQuery(Str:Str q)
Encode a map of query parameters into URL percent encoding according to the "application/x-www-form-urlencoded" MIME type. See decodeQuery.
encodeToken
static Str encodeToken(Str s, Int section)
Encode a token so that any invalid character or delimiter for the given section is "%xx" percent encoding. Section must be sectionPath, sectionQuery, or sectionFrag. Also see decodeToken.
Examples:
Uri.encodeToken("a/b#c", Uri.sectionPath) => "a%2Fb%23c"
Uri.encodeToken("a=b/c", Uri.sectionQuery) => "a%3Db/c"equals
virtual override Bool equals(Obj? that)
Two Uris are equal if they have same string normalized representation.
escapeToken
static Str escapeToken(Str s, Int section)
Escape a token so that any delimiter for the given section is backslash escaped for use in normalized URI form. Section must be sectionPath, sectionQuery, or sectionFrag.
Examples:
Uri.escapeToken("a/b#c", Uri.sectionPath) => "a\/b\#c"
Uri.escapeToken("a=b/c", Uri.sectionQuery) => "a\=b/c"ext
Str? ext()
Return file name extension (everything after the last dot) or null if name is null or name has no dot.
Examples:
`/`.ext => null
`/a/file.txt`.ext => "txt"
`/Foo.Bar`.ext => "Bar"
`/a/file`.ext => null
`/a/file.`.ext => ""
`..`.ext => nullfrag
Str? frag()
Return the fragment component of the Uri which is everything after the "#". Return null if no fragment specified.
Examples:
`http://host/path?query#frag`.frag => "frag"
`http://host/path` => null
`#h1` => "h1"fromStr
static new fromStr(Str s, Bool checked := true)
Parse the specified string into a Uri. If invalid format and checked is false return null, otherwise throw ParseErr. Parses a standard form Unicode string into its generic parts. It does not unescape % or + and handles normal Unicode characters in the string. If general delimiters such as the "?" or "#" characters are used outside their normal role, then they must be backslash escaped.
All Uris are automatically normalized as follows:
- Replacing "." and ".." segments in the middle of a path
- Scheme always normalizes to lowercase
- If http then port 80 normalizes to null
- If http then a null path normalizes to /
get
Obj? get(Obj? base := null, Bool checked := true)
Resolve this Uri into a Fantom object. See docLang for the resolve process.
getRange
@Operator Uri getRange(Range r)
Return a new Uri based on a slice of this Uri's path. If the range starts at zero, then the authority is included otherwise it is stripped and the result is not path absolute. If the range includes the last name in the path, then the query and fragment are included otherwise they are stripped and the result includes a trailing slash. The range can include negative indices to access from the end of the path. Also see pathOnly to create a slice without the authority, query, or fragment.
Examples:
`http://host/a/b/c?q`[0..-1] => `http://host/a/b/c?q`
`http://host/a/b/c?q`[0..-2] => `http://host/a/b/`
`http://host/a/b/c?q`[0..-3] => `http://host/a/`
`http://host/a/b/c?q`[0..-4] => `http://host/`
`http://host/a/b/c?q`[1..-1] => `b/c?q`
`http://host/a/b/c?q`[2..-1] => `c?q`
`http://host/a/b/c?q`[3..-1] => `?q`
`/a/b/c/`[0..1] => `/a/b/`
`/a/b/c/`[0..0] => `/a/`
`/a/b/c/`[1..2] => `b/c/`
`/a/b/c/`[1..<2] => `b/`
`/a`[0..-2] => `/`getRangeToPathAbs
Uri getRangeToPathAbs(Range r)
Return a slice of this Uri's path using the same semantics as getRange. However this method ensures that the result has a leading slash in the path such that isPathAbs returns true.
Examples:
`/a/b/c/`.getRangeToPathAbs(0..1) => `/a/b/`
`/a/b/c/`.getRangeToPathAbs(1..2) => `/b/c/`
`/a/b/c/`.getRangeToPathAbs(1..<2) => `/b/`hash
virtual override Int hash()
Return a hash code based on the normalized string representation.
host
Str? host()
Return the host address of the URI or null if not available. The host is in the format of a DNS name, IPv4 address, or IPv6 address surrounded by square brackets. Return null if the uri is not absolute.
Examples:
`ftp://there:78/file`.host => "there"
`http://www.cool.com/`.host => "www.cool.com"
`http://user@10.162.255.4/index`.host => "10.162.255.4"
`http://[::192.9.5.5]/`.host => "[::192.9.5.5]"
`//foo/bar`.host => "foo"
`/bar`.host => nullisAbs
Bool isAbs()
Return if an absolute Uri which means it has a non-null scheme.
isDir
Bool isDir()
A Uri represents a directory if it has a non-null path which ends with a "/" slash. Directories are joined with other Uris relative to themselves versus non-directories which are joined relative to their parent.
Examples:
`/a/b`.isDir => false
`/a/b/`.isDir => true
`/a/?q`.isDir => trueisName
static Bool isName(Str name)
Return if the specified string is a valid name segment to use in an unencoded URI. The name must be at least one char long and can never be "." or "..". The legal characters are defined as follows from RFC 3986:
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
ALPHA = %x41-5A / %x61-7A ; A-Z / a-z
DIGIT = %x30-39 ; 0-9Although RFC 3986 does allow path segments to contain other special characters such as sub-delims, Fantom takes a strict approach to names to be used in URIs.
isPathAbs
Bool isPathAbs()
Return if the path starts with a leading slash. If pathStr is empty, then return false.
Examples:
`http://foo/`.isPathAbs => true
`/dir/f.txt`.isPathAbs => true
`dir/f.txt`.isPathAbs => false
`../index.html`.isPathAbs => falseisPathOnly
Bool isPathOnly()
Return if this Uri contains only a path component. The authority (scheme, host, port), query, and fragment must be null.
isPathRel
Bool isPathRel()
Return logical-not of isPathAbs when path is empty or does not start with a leading slash.
isRel
Bool isRel()
Return if a relative Uri which means it has a null scheme.
mimeType
MimeType? mimeType()
Return the MimeType mapped by the ext or null if no mapping. If this uri is to a directory, then "x-directory/normal" is returned.
Examples:
`file.txt` => text/plain
`somefile` => nullname
Str name()
Return simple file name which is path.last or "" if the path is empty.
Examples:
`/`.name => ""
`/a/file.txt`.name => "file.txt"
`/a/file`.name => "file"
`somedir/`.name => "somedir"parent
Uri? parent()
Return the parent directory of this Uri or null if a parent path cannot be computed from this Uri. If the path is not empty, then this method is equivalent to getRange(0..-2).
Examples:
`http://foo/a/b/c?q#f`.parent => `http://foo/a/b/`
`/a/b/c/`.parent => `/a/b/`)
`a/b/c`.parent => `a/b/`
`/a`.parent => `/`
`/`.parent => null
`a.txt`.parent => nullpath
Str[] path()
Return the path parsed into a list of simple names or an empty list if the pathStr is "" or "/". Any general delimiters in the path such "?" or "#" are backslash escaped.
Examples:
`mailto:me@there.com` => ["me@there.com"]
`http://host`.path => Str[,]
`http://foo/`.path => Str[,]
`/`.path => Str[,]
`/a`.path => ["a"]
`/a/b`.path => ["a", "b"]
`../a/b`.path => ["..", "a", "b"]pathOnly
Uri pathOnly()
Return a new Uri with only a path part. If this Uri has an authority, fragment, or query they are stripped off.
Examples:
`http://host/a/b/c?query`.pathOnly => `/a/b/c`
`http://host/a/b/c/`.pathOnly => `/a/b/c/`
`/a/b/c`.pathOnly => `/a/b/c`
`file.txt`.pathOnly => `file.txt`pathStr
Str pathStr()
Return the path component of the Uri. Any general delimiters in the path such "?" or "#" are backslash escaped.
Examples:
`mailto:me@there.com` => "me@there.com"
`http://host` => ""
`http://foo/`.pathStr => "/"
`/a`.pathStr => "/a"
`/a/b`.pathStr => "/a/b"
`../a/b`.pathStr => "../a/b"plus
@Operator Uri plus(Uri toAppend)
Return a new Uri with the specified Uri appended to this Uri.
Examples:
`http://foo/path` + `http://bar/` => `http://bar/`
`http://foo/path?q#f` + `newpath` => `http://foo/newpath`
`http://foo/path/?q#f` + `newpath` => `http://foo/path/newpath`
`a/b/c` + `d` => `a/b/d`
`a/b/c/` + `d` => `a/b/c/d`
`a/b/c` + `../../d` => `d`
`a/b/c/` + `../../d` => `a/d`
`a/b/c` + `../../../d` => `../d`
`a/b/c/` + `../../../d` => `d`plusName
Uri plusName(Str name, Bool asDir := false)
Return a new Uri with a single path name appended to this Uri. If asDir is true, then add a trailing slash to the Uri to make it a directory Uri. This method is potentially much more efficient than using plus when appending a single name.
Examples:
`dir/`.plusName("foo") => `dir/foo`
`dir/`.plusName("foo", true) => `dir/foo/`
`/dir/file`.plusName("foo") => `/dir/foo`
`/dir/#frag`.plusName("foo") => `/dir/foo`plusQuery
Uri plusQuery([Str:Str]? query)
Add the specified query key/value pairs to this Uri. If this uri has an existing query, then it is merged with the given query. The key/value pairs should not be backslash escaped or percent encoded. If the query param is null or empty, return this instance.
Examples:
`http://h/`.plusQuery(["k":"v"]) => `http://h/?k=v`
`http://h/?k=old`.plusQuery(["k":"v"]) => `http://h/?k=v`
`/foo?a=b`.plusQuery(["k":"v"]) => `/foo?a=b&k=v`
`?a=b`.plusQuery(["k1":"v1", "k2":"v2"]) => `?a=b&k1=v1&k2=v2`plusSlash
Uri plusSlash()
Add a trailing slash to the path string of this Uri to make it a directory Uri.
Examples
`http://h/dir`.plusSlash => `http://h/dir/`
`/a`.plusSlash => `/a/`
`/a/`.plusSlash => `/a/`
`/a/b`.plusSlash => `/a/b/`
`/a?q`.plusSlash => `/a/?q`port
Int? port()
Return the IP port of the host for the network end point. It is optionally embedded in the authority using the ":" character. If unspecified then return null.
Examples:
`http://foo:81/`.port => 81
`http://www.cool.com/`.port => nullquery
Str:Str query()
Return the query parsed as a map of key/value pairs. If no query string was specified return an empty map (this method will never return null). The query is parsed such that pairs are separated by the "&" or ";" characters. If a pair contains the "=", then it is split into a key and value, otherwise the value defaults to "true". If delimiters such as "&", "=", or ";" are in the keys or values, then they are not escaped. If duplicate keys are detected, then the values are concatenated together with a comma.
Examples:
`http://host/path?query`.query => ["query":"true"]
`http://host/path`.query => [:]
`?a=b;c=d`.query => ["a":"b", "c":"d"]
`?a=b&c=d`.query => ["a":"b", "c":"d"]
`?a=b;;c=d;`.query => ["a":"b", "c":"d"]
`?a=b;;c`.query => ["a":"b", "c":"true"]
`?x=1&x=2&x=3`.query => ["x":"1,2,3"]queryStr
Str? queryStr()
Return the query component of the Uri which is everything after the "?" but before the "#" fragment. Return null if no query string specified. Any delimiters used in keys or values such as "&", "=", or ";" are backslash escaped.
Examples:
`http://host/path?query#frag`.queryStr => "query"
`http://host/path?query`.queryStr => "query"
`http://host/path`.queryStr => null
`../foo?a=b&c=d`.queryStr => "a=b&c=d"
`?a=b;c;`.queryStr => "a=b;c;"relTo
Uri relTo(Uri base)
Relativize this uri against the specified base.
Examples:
`http://foo/a/b/c`.relTo(`http://foo/a/b/c`) => ``
`http://foo/a/b/c`.relTo(`http://foo/a/b`) => `c`
`/a/b/c`.relTo(`/a`) => `b/c`
`a/b/c`.relTo(`/a`) => `b/c`
`/a/b/c?q`.relTo(`/`) => `a/b/c?q`
`/a/x`.relTo(`/a/b/c`) => `../x`relToAuth
Uri relToAuth()
Relativize this uri against its authority. This method strips the authority if present and keeps the path, query, and fragment segments.
Examples:
`http://host/a/b/c?q#frag`.relToAuth => `/a/b/c?q#frag`
`http://host/a/b/c`.relToAuth => `/a/b/c`
`http://user@host/index`.relToAuth => `/index`
`mailto:bob@bob.net`.relToAuth => `bob@bob.net`
`/a/b/c/`.relToAuth => `/a/b/c/`
`logo.png`.relToAuth => `logo.png`scheme
Str? scheme()
Return the scheme component or null if not absolute. The scheme is always normalized into lowercase.
Examples:
`http://foo/a/b/c`.scheme => "http"
`HTTP://foo/a/b/c`.scheme => "http"
`mailto:who@there.com`.scheme => "mailto"sectionFrag
const static Int sectionFrag
Fragment token section flag
sectionPath
const static Int sectionPath
Path token section flag
sectionQuery
const static Int sectionQuery
Query token section flag
toCode
Str toCode()
Get this Uri as a Fantom code literal. This method will escape the "$" interpolation character.
toFile
File toFile()
If scheme is non-null, then this is convenience for get cast to a File. If scheme is null then is a convenience for File.make(this) which maps to a file on the local file system.
toLocale
Str toLocale()
Return toStr. This method is used to enable toLocale to be used with duck typing across most built-in types.
toStr
virtual override Str toStr()
Return normalized string representation.
unescapeToken
static Str unescapeToken(Str s)
Unescape all backslash escape sequences.
Examples:
Uri.unescapeToken(Str<|a\#b|>) => "a#b"userInfo
Str? userInfo()
User info is string information embedded in the authority using the "@" character. Its use is discouraged for security reasons.
Examples:
`http://brian:pass@host/`.userInfo => "brian:pass"
`http://www.cool.com/`.userInfo => nullUriScheme
abstract const class UriScheme : Obj
UriSchemes are registered to handle a specific Uri scheme such as "file" or "http". Scheme handlers are registered using the pod index key "sys.uriScheme.{scheme}={qname}" where "scheme" is lowercase scheme name and "qname" is the qualified type name of the subclass. See docLang for the details of how scheme handling works.
Methods
| find | Lookup a UriScheme for the specified scheme name. |
| get | Resolve the uri to a Fantom object. |
| toStr | Default implementation returns type qname. |
Slot Details
find
static UriScheme? find(Str scheme, Bool checked := true)
Lookup a UriScheme for the specified scheme name. Scheme name must be lower case - note that Uri.scheme is always normalized to lower case. If the scheme is not mapped and checked is true then throw UnresolvedErr otherwise return null.
get
abstract Obj? get(Uri uri, Obj? base)
Resolve the uri to a Fantom object. If uri cannot be resolved by this scheme then throw UnresolvedErr.
toStr
virtual override Str toStr()
Default implementation returns type qname.
Uuid
@Serializable { simple=true } const class Uuid : Obj
Universally Unique Identifier. UUIDs are 128-bit identifiers which are unique across space and time making them ideal for naming without a central naming authority. Fantom's UUIDs are loosely based on RFC 4122 with the following parts used in the generation:
- 8 bytes: nanosecond ticks since 1 Jan 2000 UTC
- 2 bytes: sequence number
- 6 bytes: node address
The sequence number is initialized from a randomized number, and helps protect against collisions when the system clock is changed. The node address is ideally mapped to the MAC address if available, or the IP address hashed with a random number.
No guarantee is made how the bytes are laid out. Future versions might hash these bytes, or use alternate mechanisms.
The string format for the UUID follows the canonical format of 32 hexadecimal digits displayed in five groups for "8-4-4-4-12". For example:
03f0e2bb-8f1a-c800-e1f8-00623f7473c4Constructors
| fromStr | Parse a UUID according to the string format defined in the class header documentation. |
| make | Generate a new UUID globally unique in space and time. |
Methods
| bitsHi | Get the most significant 64 bits of this 128 bit UUID. |
| bitsLo | Get the least significant 64 bits of this 128 bit UUID. |
| compare | Compare based on the 128 bit value which will naturally result in sorts by created timestamp. |
| equals | Return if the specified object is a Uuid with the same 128 bits. |
| hash | Hashcode is defined as bitsHi ^ bitsLow |
| makeBits | Create a 128-bit UUID from two 64-bit integers. |
| toStr | Return the string representation of this UUID. |
Slot Details
bitsHi
Int bitsHi()
Get the most significant 64 bits of this 128 bit UUID.
bitsLo
Int bitsLo()
Get the least significant 64 bits of this 128 bit UUID.
compare
virtual override Int compare(Obj that)
Compare based on the 128 bit value which will naturally result in sorts by created timestamp.
equals
virtual override Bool equals(Obj? that)
Return if the specified object is a Uuid with the same 128 bits.
fromStr
static new fromStr(Str s, Bool checked := true)
Parse a UUID according to the string format defined in the class header documentation. If invalid format and checked is false return null, otherwise throw ParseErr.
hash
virtual override Int hash()
Hashcode is defined as bitsHi ^ bitsLow
make
static new make()
Generate a new UUID globally unique in space and time.
makeBits
static Uuid makeBits(Int hi, Int lo)
Create a 128-bit UUID from two 64-bit integers.
toStr
virtual override Str toStr()
Return the string representation of this UUID. See class header for string format.
Version
@Serializable { simple=true } const class Version : Obj
Version is defined as a list of decimal digits separated by the dot. Convention for Fantom pods is a four part version format of major.minor.build.patch.
Constructors
| fromStr | Parse a string representation into a Version. |
| make | Construct with list of integer segments. |
Fields
| defVal | Default value is "0". |
Methods
| build | Get the third segment which represents the build number. |
| compare | Compare from from most significant segment to least significant segment. |
| equals | Return true if equal segments. |
| hash | Return toStr.hash |
| major | Get the first, most significant segment which represents the major version. |
| minor | Get the second segment which represents the minor version. |
| patch | Get the fourth segment which represents the patch number. |
| segments | Get a readonly list of the integer segments. |
| toStr | The string format is equivalent to segments.join(".") |
Slot Details
build
Int? build()
Get the third segment which represents the build number. Return null if version has less than three segments.
compare
virtual override Int compare(Obj obj)
Compare from from most significant segment to least significant segment.
Examples:
1.6 > 1.4
2.0 > 1.9
1.2.3 > 1.2
1.11 > 1.9.3defVal
const static Version defVal
Default value is "0".
equals
virtual override Bool equals(Obj? obj)
Return true if equal segments.
fromStr
static new fromStr(Str version, Bool checked := true)
Parse a string representation into a Version. If invalid format and checked is false return null, otherwise throw ParseErr.
hash
virtual override Int hash()
Return toStr.hash
major
Int major()
Get the first, most significant segment which represents the major version.
make
static new make(Int[] segments)
Construct with list of integer segments. Throw ArgErr if segments is empty or contains negative numbers.
minor
Int? minor()
Get the second segment which represents the minor version. Return null if version has less than two segments.
patch
Int? patch()
Get the fourth segment which represents the patch number. Return null if version has less than four segments.
segments
Int[] segments()
Get a readonly list of the integer segments.
toStr
virtual override Str toStr()
The string format is equivalent to segments.join(".")
Void
const class Void : Obj
Void is used to represent the absence of a return value in a Method.
Slot Details
Weekday
@Serializable { simple=true } enum class Weekday : Enum
Enum for seven days of the week.
Enum
| sun | Sunday |
| mon | Monday |
| tue | Tuesday |
| wed | Wednesday |
| thu | Thursday |
| fri | Friday |
| sat | Saturday |
Constructors
| fromStr | Return the Weekday instance for the specified name. |
Fields
| vals | List of Weekday values indexed by ordinal |
Methods
| decrement | Return the day before this weekday. |
| increment | Return the day after this weekday. |
| localeAbbr | Get the abbreviated name for the current locale. |
| localeFull | Get the full name for the current locale. |
| localeStartOfWeek | Get the first day of the week for the current locale. |
| localeVals | Get the days of the week ordered according to the locale's start of the week. |
| toLocale | Return the weekday as a localized string according to the specified pattern. |
Slot Details
decrement
@Operator Weekday decrement()
Return the day before this weekday.
fri
const static Weekday fri := ...
Friday
fromStr
static new fromStr(Str name, Bool checked := true)
Return the Weekday instance for the specified name. If not a valid name and checked is false return null, otherwise throw ParseErr.
increment
@Operator Weekday increment()
Return the day after this weekday.
localeAbbr
Str localeAbbr()
Get the abbreviated name for the current locale. Configured by the sys::<name>Abbr localized property.
localeFull
Str localeFull()
Get the full name for the current locale. Configured by the sys::<name>Full localized property.
localeStartOfWeek
static Weekday localeStartOfWeek()
Get the first day of the week for the current locale. For example in the United States, sun is considered the start of the week. Configured by sys::weekdayStart localized property. Also see localeVals.
localeVals
static Weekday[] localeVals()
Get the days of the week ordered according to the locale's start of the week. Also see localeStartOfWeek.
mon
const static Weekday mon := ...
Monday
sat
const static Weekday sat := ...
Saturday
sun
const static Weekday sun := ...
Sunday
thu
const static Weekday thu := ...
Thursday
toLocale
Str toLocale(Str? pattern := null, Locale locale := Locale.cur())
Return the weekday as a localized string according to the specified pattern. The pattern rules are a subset of the DateTime.toLocale:
WWW Three letter abbr weekday Tue
WWWW Full weekday name TuesdayIf pattern is null it defaults to "WWW". Also see localeAbbr and localeFull.
tue
const static Weekday tue := ...
Tuesday
vals
const static Weekday[] vals := ...
List of Weekday values indexed by ordinal
wed
const static Weekday wed := ...
Wednesday
Zip
class Zip : Obj
Zip is used to read/write compressed zip files and streams. Zip may be used in three modes:
Zip.openis used to read a random access file and provides access to the entire contents with the ability to read select entriesZip.readis used to read a zip file from an input stream. Each entry is pulled off the stream usingreadNextZip.writeis used to write a zip file to an output stream. Each entry is written to the stream usingwriteNext
Methods
| close | Close this zip file for reading and writing. |
| contents | Return the contents of this zip as a map of Files. |
| deflateInStream | Construct a new deflate input stream which wraps the given input stream and inflates data written using the "deflate" compression format. |
| deflateOutStream | Construct a new deflate output stream which wraps the given output stream, and compresses data using the "deflate" compression format. |
| file | Get the underlying file or null if using streams. |
| finish | Finish writing the contents of this zip file, but leave the underlying OutStream open. |
| gzipInStream | Construct a new GZIP input stream which wraps the given input stream. |
| gzipOutStream | Construct a new GZIP output stream which wraps the given output stream. |
| open | Open the specified file as a zip file for reading. |
| read | Create a Zip used to read a zip file from the specified input stream. |
| readEach | Call the specified function for every entry in the zip. |
| readNext | Read the next entry in the zip. |
| toStr | If file is not null then return file.toStr, otherwise return a suitable string representation. |
| unzipInto | Static utility to unzip a zip file to the given directory. |
| write | Create a Zip used to write a zip file to the specified output stream. |
| writeNext | Append a new file to the end of this zip file and return an OutStream which may be used to write the file contents. |
Slot Details
close
Bool close()
Close this zip file for reading and writing. If this zip file is reading or writing a stream, then the underlying stream is also closed. This method is guaranteed to never throw an IOErr. Return true if the close was successful or false if an error occurred.
contents
[Uri:File]? contents()
Return the contents of this zip as a map of Files. The Uri keys will start with a slash and be relative to this zip file. Return null if using streams.
deflateInStream
static InStream deflateInStream(InStream in, [Str:Obj?]? opts := null)
Construct a new deflate input stream which wraps the given input stream and inflates data written using the "deflate" compression format. Options:
- nowrap: Bool false to suppress defalate header and adler checksum
deflateOutStream
static OutStream deflateOutStream(OutStream out, [Str:Obj?]? opts := null)
Construct a new deflate output stream which wraps the given output stream, and compresses data using the "deflate" compression format. Options:
- level: Int between 9 (best compression) to 0 (no compression)
- nowrap: Bool false to suppress defalate header and adler checksum
file
File? file()
Get the underlying file or null if using streams.
finish
Bool finish()
Finish writing the contents of this zip file, but leave the underlying OutStream open. This method is guaranteed to never throw an IOErr. Return true if the stream was finished successfully or false if an error occurred. Throw UnsupportedErr if zip is not writing to an output stream.
gzipInStream
static InStream gzipInStream(InStream in)
Construct a new GZIP input stream which wraps the given input stream.
gzipOutStream
static OutStream gzipOutStream(OutStream out)
Construct a new GZIP output stream which wraps the given output stream.
open
static Zip open(File file)
Open the specified file as a zip file for reading. If the specified file does not exist, is not a valid file, or does not support random access then throw IOErr.
Example:
zip := Zip.open(File(`test.zip`))
txt := zip.contents[`/notice.txt`].readAllStr
zip.closeread
static Zip read(InStream in)
Create a Zip used to read a zip file from the specified input stream.
Example:
zip := Zip.read(File(`test.zip`).in)
File? entry
while ((entry = zip.readNext()) != null)
{
data := entry.readAllBuf
echo("$entry size=$data.size")
}
zip.closereadEach
Void readEach(|File| c)
Call the specified function for every entry in the zip. Use the File's input stream to read the file contents. Some file meta-data such as size may not be available. Throw UnsupportedErr if not reading from an input stream.
readNext
File? readNext()
Read the next entry in the zip. Use the File's input stream to read the file contents. Some file meta-data such as size may not be available. Return null if at end of zip file. Throw UnsupportedErr if not reading from an input stream.
toStr
virtual override Str toStr()
If file is not null then return file.toStr, otherwise return a suitable string representation.
unzipInto
static Int unzipInto(File zip, File dir)
Static utility to unzip a zip file to the given directory. Raise exception if there are any failures. Return number of files unzipped on success.
write
static Zip write(OutStream out)
Create a Zip used to write a zip file to the specified output stream.
Example:
zip := Zip.write(File(`test.zip`).out)
out := zip.writeNext(`/path/hello.txt`)
out.writeLine("hello zip")
out.close
zip.closewriteNext
OutStream writeNext(Uri path, DateTime modifyTime := DateTime.now(), [Str:Obj?]? opts := null)
Append a new file to the end of this zip file and return an OutStream which may be used to write the file contents. The Uri must not contain a query or fragment; it may optionally start with a slash. Closing the OutStream will close only this file entry - use Zip.close() when finished writing the entire zip file. Throw UnsupportedErr if zip is not writing to an output stream.
Next entry options:
- comment: Str entry comment
- crc: Int CRC-32 of the uncompressed data
- extra: Buf for extra bytes data field
- level: Int between 9 (best compression) to 0 (no compression)
- compressedSize: Int for compressed size of data
- uncompressedSize: Int for uncompressed size of data
NOTE: setting level to 0 sets method to STORE, else to DEFLATED.
Examples:
out := zip.writeNext(`/docs/test.txt`)
out.writeLine("test")
out.close