Skip to content

系统库 sys ​

原文: https://finproducts.atlassian.net/wiki/spaces/JIDD3/pages/34793423325/FIN+5.3.1+sys 中文整理基于 FIN 5.3.1

导读: Fantom 系统运行时

以下为 API 参考,保留英文以便对照源码;目录已列出(英文标题便于检索);概述已尽量中译。


目录(导读) ​

  • mixins
  • classes
  • enums
  • facets
  • errs
  • Slot Details
    • make
    • and
    • defVal
    • equals
    • fromStr
    • hash
    • not
    • or
    • toCode
    • toLocale
    • toStr
    • xor
    • bytesEqual
    • capacity
    • charset
    • clear
    • close
    • crc
    • dup
    • eachLine
    • endian
    • fill
    • flip
    • flush
    • fromBase64
    • fromHex
    • get
    • getRange
    • hmac
    • in
    • isEmpty
    • more
    • out
    • pbk
    • peek
    • peekChar
    • pos
    • print
    • printLine
    • random
    • read
    • readAllBuf
    • readAllLines
    • readAllStr
    • readBool
    • readBuf
    • readBufFully
    • readChar
    • readChars
    • readDecimal
    • readF4
    • readF8
    • readLine
    • readObj
    • readProps
    • readS1
    • readS2
    • readS4
    • readS8
    • readStrToken
    • readU1
    • readU2
    • readU4
    • readUtf
    • remaining
    • seek
    • set
    • size
    • sync
    • toBase64
    • toBase64Uri
    • toDigest
    • toFile
    • toHex
    • trim
    • unread
    • unreadChar
    • write
    • writeBool
    • writeBuf
    • writeChar
    • writeChars
    • writeDecimal
    • writeF4
    • writeF8
    • writeI2
    • writeI4
    • writeI8
    • writeObj
    • writeProps
    • writeUtf
    • writeXml
    • name
    • utf16BE
    • utf16LE
    • utf8
    • compare
    • day
    • dayOfYear
    • firstOfMonth
    • firstOfQuarter
    • firstOfYear
    • fromIso
    • fromLocale
    • isAfter
    • isBefore
    • isSameMonth
    • isSameYear
    • isToday
    • isTomorrow
    • isYesterday
    • lastOfMonth
    • lastOfQuarter
    • lastOfYear
  • …(其余标题见英文正文)

API 正文(英文) ​

| Process | Process manages spawning external OS processes. | | Range | Range represents a contiguous range of integers from start to end. | | Regex | Regex represents a regular expression. | | RegexMatcher | RegexMatcher is used in matching operations on a regular expression. | | Slot | Slot represents a member field or method on a Type. | | Str | Str represents a sequence of Unicode characters. | | StrBuf | StrBuf is a mutable sequence of Int characters. | | Test | Test is the base for Fantom unit tests. | | This | This represents a method return type which is always this type. | | Time | Time represents a time of day independent of a specific date or timezone. | | TimeZone | TimeZone represents a region's offset from UTC and its daylight savings time rules. | | Type | Type defines the contract of an Obj by the slots it supports. | | Unit | Unit models a unit of measurement. | | Unsafe | Unsafe wraps a mutable object as an immutable reference. | | Uri | Uri is used to immutably represent a Universal Resource Identifier according to RFC 3986. | | UriScheme | UriSchemes are registered to handle a specific Uri scheme such as "file" or "http". | | Uuid | Universally Unique Identifier. | | Version | Version is defined as a list of decimal digits separated by the dot. | | Void | Void is used to represent the absence of a return value in a Method. | | Zip | Zip is used to read/write compressed zip files and streams. |


enums ​

EndianByte ordering.
LogLevelLogLevel provides a set of discrete levels used to customize logging.
MonthEnum for twelve months of the year.
WeekdayEnum for seven days of the week.

facets ​

DeprecatedIndicates that a type or slot is obsolete
FacetMetaFacet meta-data applied to facet classes.
JsUsed to annoate types which should be compiled into JavaScript.
NoDocAnnotate a type or slot as undocumented.
OperatorUsed on methods to indicate method may be used as an operator.
SerializableSerializable is a facet used to annotate types which can be serialized.
TransientTransient annotates fields which should not be serialized.

errs ​

ArgErrArgErr indicates an invalid argument was passed.
CancelledErrCancelledErr indicates that an operation was cancelled before it completed normally.
CastErrCastErr is a runtime exception raised when invalid cast is performed.
ConstErrConstErr indicates an attempt to set a const field after the object has been constructed.
FieldNotSetErrFieldNotSetErr indicates a non-nullable field was not set by the constructor it-block.
IOErrIOErr indicates an input/output error typically associated with a file system or socket.
IndexErrIndexErr indicates an attempt to access an invalid index in a List.
InterruptedErrInterruptedErr indicates that a thread is interrupted from its normal execution.
NameErrNameErr indicates an attempt to use an invalid name.
NotImmutableErrNotImmutableErr indicates using a mutable Obj where an immutable Obj is required.
NullErrNullErr indicates an attempt to dereference null.
ParseErrParseErr indicates an invalid string format which cannot be parsed.
ReadonlyErrReadonlyErr indicates an attempt to modify a readonly instance.
TestErrTestErr is thrown by Test when a test method fails a verify.
TimeoutErrTimeoutErr indicates that a blocking operation timed out before normal completion.
UnknownFacetErrUnknownFacetErr indicates an attempt to access an undefined facet.
UnknownKeyErrUnknownKeyErr indicates an attempt to lookup a non-existent key.
UnknownPodErrUnknownPodErr indicates an attempt to access a non-existent pod.
UnknownServiceErrUnknownServiceErr indicates an attempt to lookup a service which is not installed.
UnknownSlotErrUnknownSlotErr indicates an attempt to access a non-existent slot.
UnknownTypeErrUnknownTypeErr indicates an attempt to access a non-existent type.
UnresolvedErrUnresolvedErr indicates the failure to resolve a Uri to a resource.
UnsupportedErrUnsupportedErr indicates a feature which isn't supported.

ArgErr ​

const class ArgErr : Err

ArgErr indicates an invalid argument was passed.

Constructors

makeConstruct 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.


Bool ​

@Serializable { simple=true } const class Bool : Obj

Bool represents a boolean condition of true or false.

Constructors

fromStrParse a Str into a Bool.

Fields

defValDefault value is false.

Methods

andBitwise "and" of this and b.
equalsReturn if same boolean value.
hashReturn 1231 for true and 1237 for false.
notReturn the logical not: if true return false; if false return true.
orBitwise "or" of this and b.
toCodeGet this Bool as a Fantom code literal - returns toStr.
toLocaleReturn localized strings for "true" and "false" using current locale.
toStrReturn "true" or "false".
xorBitwise "exclusive-or" of this and b.

Slot Details ​


and ​

Bool and(Bool b)

Bitwise "and" of this and b. Note this method does not short circuit like logical && operator.


defVal ​

const static Bool defVal

Default value is false.


equals ​

virtual override Bool equals(Obj? obj)

Return if same boolean value.


fromStr ​

static new fromStr(Str s, Bool checked := true)

Parse a Str into a Bool. Valid formats are "true" or "false". If invalid format and checked is false return null, otherwise throw ParseErr.


hash ​

virtual override Int hash()

Return 1231 for true and 1237 for false.


not ​

Bool not()

Return the logical not: if true return false; if false return true.


or ​

Bool or(Bool b)

Bitwise "or" of this and b. Note this method does not short circuit like logical || operator.


toCode ​

Str toCode()

Get this Bool as a Fantom code literal - returns toStr.


toLocale ​

Str toLocale()

Return localized strings for "true" and "false" using current locale.


toStr ​

virtual override Str toStr()

Return "true" or "false".


xor ​

Bool xor(Bool b)

Bitwise "exclusive-or" of this and b.


Buf ​

class Buf : Obj

Buf is used to model a block of bytes with random access. Buf is typically backed by a block of memory, but can also be backed by a file:

  • Buf.make: backed by RAM
  • File.open: backed by random access file
  • File.mmap: backed by memory mapped file

Buf provides an InStream and OutStream to read and write into the buffer using a configurable position accessed via Buf.pos and Buf.seek.

When using an InStream, bytes are read starting at pos where pos is advanced after each read. The end of stream is reached when pos reaches size. When using the OutStream, bytes are written starting at pos with pos advanced after each write. If pos is less then size then the existing bytes are rewritten and size is not advanced, otherwise the buffer is automatically grown and size is advanced as bytes are appended. It is common to write bytes into the buffer using the OutStream, then call Buf.flip to prepare the buffer to be used for reading.

Memory bufs may be made immutable by calling Obj.toImmutable. When a buf is made immutable, the original buffer's data is cleared (to avoid copying the backing array). All write operations on an immutable buf will raise a ReadonlyErr. Reads may be performed by acquiring an InStream via the in method. However, read operations which require a mutable Buf pos will raise ReadonlyErr too, including methods such as seek or read. Use dup to copy an immutable buf back into a mutable buf.

Constructors

makeAllocate a byte buffer in RAM with the initial given capacity.

Fields

capacityThe number of bytes this buffer can hold without allocating more memory.
charsetCharacter set for both the OutStream and InStream.
endianByte order mode for both OutStream and InStream.
sizeReturn the total number of bytes in the buffer.

Methods

bytesEqualReturn if the buffer contents are the same size and same bytes.
clearRead the buffer for a fresh read by reseting the buffer's pos and size to zero.
closeIf this buffer is backed by a file, then close it.
crcCompute a cycle redundancy check code using this buffer's contents from 0 to size.
dupCreate a new buffer in memory which deeply clones this buffer.
eachLineConvenience for in.eachLine
equalsBuf equality is based on reference equality using the === operator.
fillWrite the specified byte to the end of the buffer using given count.
flipFlip a buffer from write-mode to read-mode.
flushObsolete call to sync.
fromBase64Decode the specified Base64 string into its binary contents.
fromHexDecode the specified hexadecimal string into its binary contents.
getGet the byte at the specified absolute index.
getRangeReturn a new buffer containing the bytes in the specified absolute range.
hmacGenerate an HMAC message authentication as specified by RFC 2104.
inGet the InStream which reads from this buffer.
isEmptyReturn if size() == 0.
moreReturn if more bytes are available to read: remaining() > 0.
outGet the OutStream which writes to this buffer.
pbkGenerate a password based cryptographic key.
peekConvenience for in.peek
peekCharConvenience for in.peekChar
posReturn the current position for the next read or write.
printConvenience for out.print Return this.
printLineConvenience for out.printLine Return this.
randomGenerate a random series of bytes.
readConvenience for in.read
readAllBufConvenience for in.readAllBuf
readAllLinesConvenience for in.readAllLines
readAllStrConvenience for in.readAllStr
readBoolConvenience for in.readBool
readBufConvenience for in.readBuf
readBufFullyConvenience for in.readBufFully
readCharConvenience for in.readChar
readCharsConvenience for in.readChars
readDecimalConvenience for in.readDecimal
readF4Convenience for in.readF4
readF8Convenience for in.readF8
readLineConvenience for in.readLine
readObjConvenience for in.readObj
readPropsConvenience for in.readProps
readS1Convenience for in.readS1
readS2Convenience for in.readS2
readS4Convenience for in.readS4
readS8Convenience for in.readS8
readStrTokenConvenience for in.readStrToken
readU1Convenience for in.readU1
readU2Convenience for in.readU2
readU4Convenience for in.readU4
readUtfConvenience for in.readUtf
remainingReturn the remaining number of bytes to read: size-pos.
seekSet the current position to the specified byte offset.
setSet is used to overwrite the byte at the specified index.
syncIf this Buf is backed by a file, then fsync all changes to the storage device.
toBase64Encode the buffer contents from 0 to size to a Base64 string as defined by MIME RFC 2045.
toBase64UriEncode the buffer contents from 0 to size to a Uri-safe Base64 string as defined by RFC 4648.
toDigestApply the specified message digest algorithm to this buffer's contents from 0 to size and return the resulting hash.
toFileCreate an in-memory File instance for this buffer with the given file URI.
toHexEncode the buffer contents from 0 to size into a hexadecimal string.
toStrReturn string summary of the buffer.
trimTrim the capacity such that the underlying storage is optimized for the current size.
unreadConvenience for in.unread Memory backed buffers support a stack based pushback model like IO streams.
unreadCharConvenience for in.unreadChar Memory backed buffers support a stack based pushback model like IO streams.
writeConvenience for out.write Return this.
writeBoolConvenience for out.writeBool Return this.
writeBufConvenience for out.writeBuf Return this.
writeCharConvenience for out.writeChar Return this.
writeCharsConvenience for out.writeChars Return this.
writeDecimalConvenience for out.writeDecimal Return this.
writeF4Convenience for out.writeF4 Return this.
writeF8Convenience for out.writeF8 Return this.
writeI2Convenience for out.writeI2 Return this.
writeI4Convenience for out.writeI4 Return this.
writeI8Convenience for out.writeI8 Return this.
writeObjConvenience for out.writeObj Return this.
writePropsConvenience for out.writeProps Return this.
writeUtfConvenience for out.writeUtf Return this.
writeXmlConvenience for out.writeXml Return this.

Slot Details ​


bytesEqual ​

Bool bytesEqual(Buf that)

Return if the buffer contents are the same size and same bytes. Note this could be an extremely expensive call for non-memory buffers.


capacity ​

Int capacity

The number of bytes this buffer can hold without allocating more memory. Capacity is always greater or equal to size. If adding a large number of bytes, it may be more efficient to manually set capacity. See the trim method to automatically set capacity to size. Throw ArgErr if attempting to set capacity less than size. This method is ignored on a file buffer, and unsupported on mmap.


charset ​

Charset charset

Character set for both the OutStream and InStream.


clear ​

This clear()

Read the buffer for a fresh read by reseting the buffer's pos and size to zero. The buffer's capacity remains the same. Return this.


close ​

Bool close()

If this buffer is backed by a file, then close it. If a memory buffer then do nothing. This method is guaranteed to never throw an IOErr. Return true if the buffer was closed successfully or false if closed abnormally.


crc ​

Int crc(Str algorithm)

Compute a cycle redundancy check code using this buffer's contents from 0 to size. The supported algorithm names:

  • "CRC-16": also known as CRC-16-ANSI, CRC-16-IBM; used by USB, ANSI X3.28, and Modbus
  • "CRC-32": used by Ethernet, MPEG-2, PKZIP, Gzip, PNG
  • "CRC-32-Adler": used by Zlib

Raise ArgErr if algorithm is not available. This method is only supported for memory based buffers.


dup ​

Buf dup()

Create a new buffer in memory which deeply clones this buffer. The resulting buf is read/write.


eachLine ​

Void eachLine(|Str| f)

Convenience for in.eachLine


endian ​

Endian endian

Byte order mode for both OutStream and InStream. Default is Endian.big (network byte order).


equals ​

virtual override Bool equals(Obj? that)

Buf equality is based on reference equality using the === operator.


fill ​

This fill(Int byte, Int times)

Write the specified byte to the end of the buffer using given count.

Examples:

Buf().fill(0xff, 4)  =>  0xffffffff

flip ​

This flip()

Flip a buffer from write-mode to read-mode. This method sets total size to current position, and position to 0. Return this.


flush ​

@Deprecated { msg="Use sync" } This flush()

Obsolete call to sync. In the future this method may be relaxed to flush only memory buffers, but not force an fsync.


fromBase64 ​

static Buf fromBase64(Str s)

Decode the specified Base64 string into its binary contents. Both MIME RFC 2045 and URI-safe RFC 4648 encodings are supported. Any characters which are not included in the Base64 character set are safely ignored.

Example:

Buf.make.print("Fan").toBase64    => "RmFu"
Buf.fromBase64("RmFu").readAllStr => "Fan"

fromHex ​

static Buf fromHex(Str s)

Decode the specified hexadecimal string into its binary contents. Any characters which are not included in the set "0-9, a-f, A-F" are ignored as long as they appear between bytes (hi and lo nibbles must be contiguous).

Example:

Buf.make.print("\r\n").toHex   => "0d0a"
Buf.fromHex("0d0a").readAllStr => "\r\n"

get ​

@Operator Int get(Int index)

Get the byte at the specified absolute index. A negative index may be used to access from the end of the buffer. For example get(-1) is translated into get(size-1). This method accesses the buffer absolutely independent of current position. The get method is accessed via the [] shortcut operator. Throw IndexErr if index out of range.


getRange ​

@Operator Buf getRange(Range range)

Return a new buffer containing the bytes in the specified absolute range. Negative indexes may be used to access from the end of the buf. This method accesses the buffer absolutely independent of current position. This method is accessed via the [] operator. Throw IndexErr if range illegal.

Examples:

buf := Buf.make
buf.write(0xaa).write(0xbb).write(0xcc).write(0xdd)
buf[0..2]   => 0x[aabbcc]
buf[3..3]   => 0x[dd]
buf[-2..-1] => 0x[ccdd]
buf[0..<2]  => 0x[aabb]
buf[1..-2]  => 0x[bbcc]

hmac ​

Buf hmac(Str algorithm, Buf key)

Generate an HMAC message authentication as specified by RFC 2104. This buffer is the data input, algorithm specifies the hash digest, and key represents the secret key:

  • H: specified by algorthim parameter - "MD5" or "SHA1"
  • K: secret key specified by key parameter
  • B: fixed at 64
  • text: this instance

The HMAC is computed using:

ipad = the byte 0x36 repeated B times
opad = the byte 0x5C repeated B times
H(K XOR opad, H(K XOR ipad, text))

Throw ArgErr if the algorithm is not available. This method is only supported for memory buffers.

Examples:

"hi there".toBuf.hmac("MD5", "secret".toBuf)

in ​

InStream in()

Get the InStream which reads from this buffer. This method always returns the same instance. If this buffer is backed by a file, then in.close will not close the file - you must use Buf.close.


isEmpty ​

Bool isEmpty()

Return if size() == 0.


make ​

static new make(Int capacity := 1024)

Allocate a byte buffer in RAM with the initial given capacity.


more ​

Bool more()

Return if more bytes are available to read: remaining() > 0.


out ​

OutStream out()

Get the OutStream which writes to this buffer. This method always returns the same instance. If this buffer is backed by a file, then out.close will not close the file - you must use Buf.close.


pbk ​

static Buf pbk(Str algorithm, Str password, Buf salt, Int iterations, Int keyLen)

Generate a password based cryptographic key. Supported algorithms:

  • "PBKDF2WithHmacSHA1"
  • "PBKDF2WithHmacSHA256"

Parameters:

  • password: secret used to generate resulting cryptographic key
  • salt: cryptographic salt
  • iterations: number of iterations (the c term)
  • keyLen: desired length of key in bytes (not bits!)

Throw ArgErr if the algorithm is not available. This method is only supported for memory buffers.


peek ​

Int? peek()

Convenience for in.peek


peekChar ​

Int? peekChar()

Convenience for in.peekChar


pos ​

Int pos()

Return the current position for the next read or write. The position is always between 0 and size. If pos is less than size then future writes will rewrite the existing bytes without growing size. Change the position with seek.


print ​

This print(Obj? s)

Convenience for out.print Return this.


printLine ​

This printLine(Obj? obj := "")

Convenience for out.printLine Return this.


random ​

static Buf random(Int size)

Generate a random series of bytes.

Example:

Buf.random(8).toHex  => "d548b54989028b90"

read ​

Int? read()

Convenience for in.read


readAllBuf ​

Buf readAllBuf()

Convenience for in.readAllBuf


readAllLines ​

Str[] readAllLines()

Convenience for in.readAllLines


readAllStr ​

Str readAllStr(Bool normalizeNewlines := true)

Convenience for in.readAllStr


readBool ​

Bool readBool()

Convenience for in.readBool


readBuf ​

Int? readBuf(Buf buf, Int n)

Convenience for in.readBuf


readBufFully ​

Buf readBufFully(Buf? buf, Int n)

Convenience for in.readBufFully


readChar ​

Int? readChar()

Convenience for in.readChar


readChars ​

Str readChars(Int n)

Convenience for in.readChars


readDecimal ​

Decimal readDecimal()

Convenience for in.readDecimal


readF4 ​

Float readF4()

Convenience for in.readF4


readF8 ​

Float readF8()

Convenience for in.readF8


readLine ​

Str? readLine(Int? max := 4096)

Convenience for in.readLine


readObj ​

Obj? readObj([Str:Obj]? options := null)

Convenience for in.readObj


readProps ​

Str:Str readProps()

Convenience for in.readProps


readS1 ​

Int readS1()

Convenience for in.readS1


readS2 ​

Int readS2()

Convenience for in.readS2


readS4 ​

Int readS4()

Convenience for in.readS4


readS8 ​

Int readS8()

Convenience for in.readS8


readStrToken ​

Str? readStrToken(Int? max := null, |Int->Bool|? c := null)

Convenience for in.readStrToken


readU1 ​

Int readU1()

Convenience for in.readU1


readU2 ​

Int readU2()

Convenience for in.readU2


readU4 ​

Int readU4()

Convenience for in.readU4


readUtf ​

Str readUtf()

Convenience for in.readUtf


remaining ​

Int remaining()

Return the remaining number of bytes to read: size-pos.


seek ​

This seek(Int pos)

Set the current position to the specified byte offset. A negative index may be used to access from the end of the buffer. For example seek(-1) is translated into seek(size-1). Return this.


set ​

@Operator This set(Int index, Int byte)

Set is used to overwrite the byte at the specified index. A negative index may be used to access an index from the end of the buffer. The set method is accessed via the []= shortcut operator. Return this. Throw IndexErr if index is out of range.


size ​

Int size

Return the total number of bytes in the buffer. If the size is set greater than capacity then the buffer's capacity is automatically grown, otherwise capacity remains the same. Setting size does not actually change any bytes in the buffer. A mmap buffer can never be increased from its initial size.


sync ​

This sync()

If this Buf is backed by a file, then fsync all changes to the storage device. Throw IOErr on error. Return this.


toBase64 ​

Str toBase64()

Encode the buffer contents from 0 to size to a Base64 string as defined by MIME RFC 2045. No line breaks are added. This method is only supported by memory-backed buffers; file-backed buffers will throw UnsupportedErr.

Example:

Buf.make.print("Fan").toBase64    => "RmFu"
Buf.fromBase64("RmFu").readAllStr => "Fan"

toBase64Uri ​

Str toBase64Uri()

Encode the buffer contents from 0 to size to a Uri-safe Base64 string as defined by RFC 4648. This means + is encoded as -, and / is encoded as _. Additionally, no padding is applied. This method is only supported by memory-backed buffers; file-backed buffers will throw UnsupportedErr.

Example:

Buf.make.print("safe base64~~").toBase64    => "c2FmZSBiYXNlNjR+fg=="
Buf.make.print("safe base64~~").toBase64Uri => "c2FmZSBiYXNlNjR-fg"

toDigest ​

Buf toDigest(Str algorithm)

Apply the specified message digest algorithm to this buffer's contents from 0 to size and return the resulting hash. Digests are secure one-way hash functions which input an arbitrary sized buffer and return a fixed sized buffer. Common algorithms include: "MD5", "SHA-1", and "SHA-256"; the full list supported is platform dependent. On the Java VM, the algorithm maps to those available via the java.security.MessageDigest API. Throw ArgErr if the algorithm is not available. This method is unsupported for mmap buffers.

Example:

Buf.make.print("password").print("salt").toDigest("MD5").toHex
 =>  "b305cadbb3bce54f3aa59c64fec00dea"

toFile ​

File toFile(Uri uri)

Create an in-memory File instance for this buffer with the given file URI. The buffer must be a RAM based buffer which is converted to an immutable buffer via Obj.toImmutable semantics. The current time is used for the file's modified time.


toHex ​

Str toHex()

Encode the buffer contents from 0 to size into a hexadecimal string. This method is unsupported for mmap buffers.

Example:

Buf.make.print("\r\n").toHex   => "0d0a"
Buf.fromHex("0d0a").readAllStr => "\r\n"

toStr ​

virtual override Str toStr()

Return string summary of the buffer.


trim ​

This trim()

Trim the capacity such that the underlying storage is optimized for the current size. Return this.


unread ​

This unread(Int b)

Convenience for in.unread Memory backed buffers support a stack based pushback model like IO streams. File backed buffers will simply rewrite the last position in the file. Return this.


unreadChar ​

This unreadChar(Int b)

Convenience for in.unreadChar Memory backed buffers support a stack based pushback model like IO streams. File backed buffers will simply rewrite the last position in the file. Return this.


write ​

This write(Int byte)

Convenience for out.write Return this.


writeBool ​

This writeBool(Bool b)

Convenience for out.writeBool Return this.


writeBuf ​

This writeBuf(Buf buf, Int n := buf.remaining())

Convenience for out.writeBuf Return this.


writeChar ​

This writeChar(Int char)

Convenience for out.writeChar Return this.


writeChars ​

This writeChars(Str str, Int off := 0, Int len := str.size() - off)

Convenience for out.writeChars Return this.


writeDecimal ​

This writeDecimal(Decimal d)

Convenience for out.writeDecimal Return this.


writeF4 ​

This writeF4(Float r)

Convenience for out.writeF4 Return this.


writeF8 ​

This writeF8(Float r)

Convenience for out.writeF8 Return this.


writeI2 ​

This writeI2(Int n)

Convenience for out.writeI2 Return this.


writeI4 ​

This writeI4(Int n)

Convenience for out.writeI4 Return this.


writeI8 ​

This writeI8(Int n)

Convenience for out.writeI8 Return this.


writeObj ​

This writeObj(Obj? obj, [Str:Obj]? options := null)

Convenience for out.writeObj Return this.


writeProps ​

This writeProps(Str:Str props)

Convenience for out.writeProps Return this.


writeUtf ​

This writeUtf(Str s)

Convenience for out.writeUtf Return this.


writeXml ​

This writeXml(Str s, Int flags := 0)

Convenience for out.writeXml Return this.


CancelledErr ​

const class CancelledErr : Err

CancelledErr indicates that an operation was cancelled before it completed normally.

Constructors

makeConstruct 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.


CastErr ​

const class CastErr : Err

CastErr is a runtime exception raised when invalid cast is performed.

Constructors

makeConstruct 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.


Charset ​

@Serializable { simple=true } const class Charset : Obj

Charset represents a specific character encoding. It is used to decode bytes to Unicode characters, and encode Unicode characters to bytes.

Constructors

fromStrAttempt to lookup a Charset by name.

Methods

defValDefault value is utf8.
equalsCharset equality is based on the character set name ignoring case (names are not case-sensitive).
hashCompute hash code based on case-insensitive name.
nameGet the name of this character encoding.
toStrReturn name().
utf16BEA charset for "UTF-16BE" format (Sixteen-bit UCS Transformation Format, big-endian byte order).
utf16LEA charset for "UTF-16LE" format (Sixteen-bit UCS Transformation Format, little-endian byte order).
utf8A charset for "UTF-8" format (Eight-bit UCS Transformation Format).

Slot Details ​


defVal ​

static Charset defVal()

Default value is utf8.


equals ​

virtual override Bool equals(Obj? obj)

Charset equality is based on the character set name ignoring case (names are not case-sensitive).


fromStr ​

static new fromStr(Str name, Bool checked := true)

Attempt to lookup a Charset by name. Use one of the predefined methods such as utf8 to get a standard encoding. If charset not found and checked is false return null, otherwise throw ParseErr.


hash ​

virtual override Int hash()

Compute hash code based on case-insensitive name.


name ​

Str name()

Get the name of this character encoding.


toStr ​

virtual override Str toStr()

Return name().


utf16BE ​

static Charset utf16BE()

A charset for "UTF-16BE" format (Sixteen-bit UCS Transformation Format, big-endian byte order).


utf16LE ​

static Charset utf16LE()

A charset for "UTF-16LE" format (Sixteen-bit UCS Transformation Format, little-endian byte order).


utf8 ​

static Charset utf8()

A charset for "UTF-8" format (Eight-bit UCS Transformation Format).


ConstErr ​

const class ConstErr : Err

ConstErr indicates an attempt to set a const field after the object has been constructed.

Constructors

makeConstruct 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.


Date ​

@Serializable { simple=true } const class Date : Obj

Date represents a day in time independent of a timezone.

Constructors

fromStrParse the string into a Date from the programmatic encoding defined by toStr.
makeMake for the specified date values

Fields

defValDefault value is "2000-01-01".

Methods

compareCompare based on year, month, and day.
dayGet the day of the month as a number between 1 and 31.
dayOfYearReturn the day of the year as a number between 1 and 365 (or 1 to 366 if a leap year).
equalsTwo dates are equal if they have the same year, month, and day.
firstOfMonthGet the first day of this Date's current month.
firstOfQuarterGet the beginning of this date's three month quarter
firstOfYearGet the Jan 1st of this Date's current year.
fromIsoParse an ISO 8601 date.
fromLocaleParse a string into a Date using the given pattern.
hashReturn hash of year, month, and day.
isAfterConvenience for this > that
isBeforeConvenience for this < that
isSameMonthReturn if this date is in the same year and month of that
isSameYearReturn if this date is in the same year of that
isTodayReturn is this date equal to today.
isTomorrowReturn is this date equal to today + 1day.
isYesterdayReturn is this date equal to today - 1day.
lastOfMonthGet the last day of this Date's current month.
lastOfQuarterGet the end of this date's three month quarter
lastOfYearGet the Dec 31st of this Date's current year.
midnightReturn a DateTime for the beginning of this day at midnight.
minusSubtract the specified number of days to this date to get a date in the past.
minusDateReturn the delta between this and the given date.
monthGet the month of this date.
plusAdd the specified number of days to this date to get a date in the future.
quarterInteger between 1 and 4 for which of the three month quarters this date falls in.
toCodeGet this Date as a Fantom expression suitable for code generation.
toDateTimeCombine this Date with the given Time to return a DateTime.
toIsoFormat this instance according to ISO 8601 using the pattern
toLocaleFormat this date according to the specified pattern.
toStrReturn programmatic ISO 8601 string encoding formatted as follows
todayGet today's Date using specified timezone.
tomorrowGet tomorrow's Date using specified timezone.
weekOfYearReturn the week number of the year as a number between 1 and 53 using the given weekday as the start of the week (defaults to current locale).
weekdayGet the day of the week for this date.
yearGet the year as a number such as 2009.
yesterdayGet yesterday's Date using specified timezone.

Slot Details ​


compare ​

virtual override Int compare(Obj obj)

Compare based on year, month, and day.


day ​

Int day()

Get the day of the month as a number between 1 and 31.


dayOfYear ​

Int dayOfYear()

Return the day of the year as a number between 1 and 365 (or 1 to 366 if a leap year).


defVal ​

const static Date defVal

Default value is "2000-01-01".


equals ​

virtual override Bool equals(Obj? that)

Two dates are equal if they have the same year, month, and day.


firstOfMonth ​

Date firstOfMonth()

Get the first day of this Date's current month.

Example:

Date("2009-10-28").firstOfMonth  =>  2009-10-01

firstOfQuarter ​

Date firstOfQuarter()

Get the beginning of this date's three month quarter

Example:

Date("2025-04-28").firstOfQuarter  =>  2025-04-01

firstOfYear ​

Date firstOfYear()

Get the Jan 1st of this Date's current year.

Example:

Date("2025-10-28").firstOfYear  =>  2025-01-01

fromIso ​

static Date? fromIso(Str s, Bool checked := true)

Parse an ISO 8601 date. If invalid format and checked is false return null, otherwise throw ParseErr. The following format is supported:

YYYY-MM-DD

Also see toIso and fromStr.


fromLocale ​

static Date? fromLocale(Str str, Str pattern, Bool checked := true)

Parse a string into a Date 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 Date from the programmatic encoding defined by toStr. If the string cannot be parsed into a valid Date and checked is false then return null, otherwise throw ParseErr.


hash ​

virtual override Int hash()

Return hash of year, month, and day.


isAfter ​

Bool isAfter(Date that)

Convenience for this > that


isBefore ​

Bool isBefore(Date that)

Convenience for this < that


isSameMonth ​

Bool isSameMonth(Date that)

Return if this date is in the same year and month of that


isSameYear ​

Bool isSameYear(Date that)

Return if this date is in the same year of that


isToday ​

Bool isToday()

Return is this date equal to today.


isTomorrow ​

Bool isTomorrow()

Return is this date equal to today + 1day.


isYesterday ​

Bool isYesterday()

Return is this date equal to today - 1day.


lastOfMonth ​

Date lastOfMonth()

Get the last day of this Date's current month.

Example:

Date("2009-10-28").lastOfMonth  =>  2009-10-31

lastOfQuarter ​

Date lastOfQuarter()

Get the end of this date's three month quarter

Example:

Date("2025-04-28").lastOfQuarter  =>  2025-06-30

lastOfYear ​

Date lastOfYear()

Get the Dec 31st of this Date's current year.

Example:

Date("2025-10-28").lastOfYear  =>  2025-12-31

make ​

static new make(Int year, Month month, Int day)

Make for the specified date values:

  • year: no restriction (although only 1901-2099 maps to DateTime)
  • month: Month enumeration
  • day: 1-31

Throw ArgErr if any of the parameters are out of range.


midnight ​

DateTime midnight(TimeZone tz := TimeZone.cur())

Return a DateTime for the beginning of this day at midnight.


minus ​

@Operator Date minus(Duration days)

Subtract the specified number of days to this date to get a date in the past. Throw ArgErr if days parameter is not a whole number of days (must be evenly divisible by 24hr).

Example:

Date(2008, Month.feb, 28) - 2day  =>  2008-02-26

minusDate ​

@Operator Duration minusDate(Date days)

Return the delta between this and the given date. The result is always an exact multiple of 24 hour days.

Example:

Date(2009, Month.jan, 5) - Date(2009, Month.jan, 2)  =>  3day

month ​

Month month()

Get the month of this date.


plus ​

@Operator Date plus(Duration days)

Add the specified number of days to this date to get a date in the future. Throw ArgErr if days parameter is not a whole number of days (must be evenly divisible by 24hr).

Example:

Date(2008, Month.feb, 28) + 2day  =>  2008-03-01

quarter ​

Int quarter()

Integer between 1 and 4 for which of the three month quarters this date falls in.


toCode ​

Str toCode()

Get this Date as a Fantom expression suitable for code generation.


toDateTime ​

DateTime toDateTime(Time t, TimeZone tz := TimeZone.cur())

Combine this Date with the given Time to return a DateTime.


toIso ​

Str toIso()

Format this instance according to ISO 8601 using the pattern:

YYYY-MM-DD

Also 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:

YY     Two digit year             07
YYYY   Four digit year            2007
M      One/two digit month        6, 11
MM     Two digit month            06, 11
MMM    Three letter abbr month    Jun, Nov
MMMM   Full month                 June, November
D      One/two digit day          5, 28
DD     Two digit day              05, 28
DDD    Day with suffix            1st, 2nd, 3rd, 24th
WWW    Three letter abbr weekday  Tue
WWWW   Full weekday               Tuesday
Q      Quarter number             3
QQQ    Quarter with suffix        3rd
QQQQ   Quarter spelled out        3rd Quarter
'xyz'  Literal characters

toStr ​

virtual override Str toStr()

Return programmatic ISO 8601 string encoding formatted as follows:

YYYY-MM-DD
2009-01-10

Also fromStr, toIso, and toLocale.


today ​

static Date today(TimeZone tz := TimeZone.cur())

Get today's Date using specified timezone.


tomorrow ​

static Date tomorrow(TimeZone tz := TimeZone.cur())

Get tomorrow's Date using specified timezone.


weekOfYear ​

Int weekOfYear(Weekday startOfWeek := Weekday.localeStartOfWeek())

Return the week number of the year as a number between 1 and 53 using the given weekday as the start of the week (defaults to current locale).


weekday ​

Weekday weekday()

Get the day of the week for this date.


year ​

Int year()

Get the year as a number such as 2009.


yesterday ​

static Date yesterday(TimeZone tz := TimeZone.cur())

Get yesterday's Date using specified timezone.


DateTime ​

@Serializable { simple=true } const class DateTime : Obj

DateTime represents an absolute instance in time. Fantom time is normalized as nanosecond ticks since 1 Jan 2000 UTC with a supported range of 1901 to 2099. Fantom time does not support leap seconds (same as Java and UNIX). An instance of DateTime also models the date and time of an absolute instance against a specific TimeZone.

Also see docLang.

Constructors

fromStrParse the string into a DateTime from the programmatic encoding defined by toStr.
makeMake for the specified date and time values

Fields

defValDefault value is "2000-01-01T00:00:00Z UTC".

Methods

bootGet the boot time of the Fantom VM with TimeZone.cur
compareCompare based on nanosecond ticks.
dateGet the date component of this timestamp.
dayGet the day of the month as a number between 1 and 31.
dayOfYearReturn the day of the year as a number between 1 and 365 (or 1 to 366 if a leap year).
dstReturn if this time is within daylight savings time for its associated time zone.
equalsTwo times are equal if they have identical nanosecond ticks.
floorReturn a new DateTime with this time's nanosecond ticks truncated according to the specified accuracy.
fromHttpStrParse an HTTP date according to the RFC 2616 section 3.3.1.
fromIsoParse an ISO 8601 timestamp.
fromJavaCreate date for Java milliseconds since the epoch of 1 Jan 1970 using the specified timezone (defaults to current).
fromLocaleParse a string into a DateTime using the given pattern.
hashReturn nanosecond ticks for the hashcode.
hourGet the hour of the time as a number between 0 and 23.
hoursInDayReturn the number of hours for this date and this timezone.
isLeapYearReturn if the specified year is a leap year.
isMidnightReturn if the time portion is "00:00:00".
makeTicksMake for nanosecond ticks since 1 Jan 2000 UTC.
midnightReturn a DateTime for the beginning of the current day at midnight.
minGet the minutes of the time as a number between 0 and 59.
minusSubtract a duration to compute a new time.
minusDateTimeReturn the delta between this and the given time.
monthGet the month of this date.
nanoSecGet the number of nanoseconds (the fraction of seconds) as a number between 0 and 999,999,999.
nowReturn the current time using TimeZone.cur.
nowTicksReturn the current time as nanosecond ticks since 1 Jan 2000 UTC.
nowUniqueReturn the current time as nanosecond ticks since 1 Jan 2000 UTC, but with the guarantee that every call returns a unique value for the lifetime of this VM.
nowUtcReturn the current time using TimeZone.utc.
plusAdd a duration to compute a new time.
secGet the whole seconds of the time as a number between 0 and 59.
ticksReturn number of nanosecond ticks since 1 Jan 2000 UTC.
timeGet the time component of this timestamp.
toCodeGet this DateTime as a Fantom expression suitable for code generation.
toHttpStrFormat this time for use in an MIME or HTTP message according to RFC 2616 using the RFC 1123 format
toIsoFormat this instance according to ISO 8601 using the pattern
toJavaGet this date in Java milliseconds since the epoch of 1 Jan 1970.
toLocaleFormat this time according to the specified pattern.
toRelConvenience for toTimeZone(TimeZone.rel).
toStrReturn programmatic string encoding formatted as follows
toTimeZoneConvert this DateTime to the specific timezone.
toUtcConvenience for toTimeZone(TimeZone.utc).
tzGet the time zone associated with this date time.
tzAbbrGet the time zone's abbreviation for this time.
weekOfYearReturn the week number of the year as a number between 1 and 53 using the given weekday as the start of the week (defaults to current locale).
weekdayGet the day of the week for this time.
weekdayInMonthThis method computes the day of month (1-31) for a given weekday.
yearGet the year as a number such as 2007.

Slot Details ​


boot ​

static DateTime boot()

Get the boot time of the Fantom VM with TimeZone.cur


compare ​

virtual override Int compare(Obj obj)

Compare based on nanosecond ticks.


date ​

Date date()

Get the date component of this timestamp.


day ​

Int day()

Get the day of the month as a number between 1 and 31.


dayOfYear ​

Int dayOfYear()

Return the day of the year as a number between 1 and 365 (or 1 to 366 if a leap year).


defVal ​

const static DateTime defVal

Default value is "2000-01-01T00:00:00Z UTC".


dst ​

Bool dst()

Return if this time is within daylight savings time for its associated time zone.


equals ​

virtual override Bool equals(Obj? that)

Two times are equal if they have identical nanosecond ticks.


floor ​

DateTime floor(Duration accuracy)

Return a new DateTime with this time's nanosecond ticks truncated according to the specified accuracy. For example floor(1min) will truncate this time to the minute such that seconds are 0.0. This method is strictly based on absolute ticks, it does not take into account wall-time rollovers.


fromHttpStr ​

static DateTime? fromHttpStr(Str s, Bool checked := true)

Parse an HTTP date according to the RFC 2616 section 3.3.1. If invalid format and checked is false return null, otherwise throw ParseErr. The following date formats are supported:

Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
Sun Nov  6 08:49:37 1994       ; ANSI C's asctime() format

fromIso ​

static DateTime? fromIso(Str s, Bool checked := true)

Parse an ISO 8601 timestamp. If invalid format and checked is false return null, otherwise throw ParseErr. The following formats are supported:

YYYY-MM-DD'T'hh:mm:ss[.FFFFFFFFF]
YYYY-MM-DD'T'hh:mm:ss[.FFFFFFFFF]+HH:MM
YYYY-MM-DD'T'hh:mm:ss[.FFFFFFFFF]-HH:MM

If a timezone offset is specified, then one of the predefined "Etc/GMT+x" timezones are used for the result:

DateTime("2009-01-15T12:00:00Z")       =>  2009-01-15T12:00:00Z UTC
DateTime("2009-01-15T12:00:00-05:00")  =>  2009-01-15T12:00:00-05:00 GMT+5

Also see toIso, fromStr, and fromHttpStr.


fromJava ​

static DateTime? fromJava(Int millis, TimeZone tz := TimeZone.cur(), Bool negIsNull := true)

Create date for Java milliseconds since the epoch of 1 Jan 1970 using the specified timezone (defaults to current). If millis are less than or equal to zero then return null or a date before 1970 depending on the negIsNull flag.


fromLocale ​

static DateTime? fromLocale(Str str, Str pattern, TimeZone tz := TimeZone.cur(), Bool checked := true)

Parse a string into a DateTime 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.

The timezone is inferred from the zone pattern, or else the given tz parameter is used for the timezone. The z pattern will match "hh:mm", "hhmm", or "hh". If only a zone offset is available and it doesn't match the expected tz parameter, then use a "GMT+/-" timezone. Note that if offset is a fractional hour such as GMT-3:30, then result will have ticks, but its tz will be floored hour based GMT timezone such as GMT-3.


fromStr ​

static new fromStr(Str s, Bool checked := true)

Parse the string into a DateTime from the programmatic encoding defined by toStr. If the string cannot be parsed into a valid DateTime and checked is false then return null, otherwise throw ParseErr. Also see fromIso and fromHttpStr.


hash ​

virtual override Int hash()

Return nanosecond ticks for the hashcode.


hour ​

Int hour()

Get the hour of the time as a number between 0 and 23.


hoursInDay ​

Int hoursInDay()

Return the number of hours for this date and this timezone. Days which transition to DST will be 23 hours and days which transition back to standard time will be 25 hours. Note there is one timezone "Lord_Howe" which has a 30min offset which is not handled by this method (WTF).


isLeapYear ​

static Bool isLeapYear(Int year)

Return if the specified year is a leap year.


isMidnight ​

Bool isMidnight()

Return if the time portion is "00:00:00".


make ​

static new make(Int year, Month month, Int day, Int hour, Int min, Int sec := 0, Int ns := 0, TimeZone tz := TimeZone.cur())

Make for the specified date and time values:

  • year: 1901-2099
  • month: Month enumeration
  • day: 1-31
  • hour: 0-23
  • min: 0-59
  • sec: 0-59
  • ns: 0-999_999_999
  • tz: time zone used to map date/time to ns ticks

Throw ArgErr if any of the parameters are out of range.


makeTicks ​

static DateTime makeTicks(Int ticks, TimeZone tz := TimeZone.cur())

Make for nanosecond ticks since 1 Jan 2000 UTC. Throw ArgErr if ticks represent a year out of the range 1901 to 2099.


midnight ​

DateTime midnight()

Return a DateTime for the beginning of the current day at midnight.


min ​

Int min()

Get the minutes of the time as a number between 0 and 59.


minus ​

@Operator DateTime minus(Duration duration)

Subtract a duration to compute a new time. This method works off absolute time, so subtracting 1days means to subtract 24 hours from the ticks. This might be a different time of day if on a DST boundry. Use Date.minus for daily increments.

Example:

prevHour := DateTime.now - 1hr

minusDateTime ​

@Operator Duration minusDateTime(DateTime time)

Return the delta between this and the given time.

Example:

elapsed := DateTime.now - startTime

month ​

Month month()

Get the month of this date.


nanoSec ​

Int nanoSec()

Get the number of nanoseconds (the fraction of seconds) as a number between 0 and 999,999,999.


now ​

static DateTime now(Duration? tolerance := 250ms)

Return the current time using TimeZone.cur. The tolerance parameter specifies that you are willing to use a cached DateTime instance as long as (now - cached <= tolerance). If tolerance is null, then this method always creates a new DateTime instance. Using tolerance can increase performance and save memory. The tolerance default is 250ms.

If you are using time to calculate relative time periods, then use Duration.now instead. Duration is more efficient and won't cause you grief when the system clock is modified.


nowTicks ​

static Int nowTicks()

Return the current time as nanosecond ticks since 1 Jan 2000 UTC.


nowUnique ​

static Int nowUnique()

Return the current time as nanosecond ticks since 1 Jan 2000 UTC, but with the guarantee that every call returns a unique value for the lifetime of this VM. Since most platforms don't actually support nanosecond resolution, the unused nanoseconds are used as a counter to ensure uniqueness. However, bursts of calls may result in a drift from the actual system time. For example, if the platform's clock supports millisecond resolution, then calling this method more than one million times within a millisecond will introduce a millisecond drift (1,000,000ns in a ms).


nowUtc ​

static DateTime nowUtc(Duration? tolerance := 250ms)

Return the current time using TimeZone.utc. See now for a description of the tolerance parameter.


plus ​

@Operator DateTime plus(Duration duration)

Add a duration to compute a new time. This method works off absolute time, so adding 1days means to add 24 hours to the ticks. This might be a different time of day if on a DST boundry. Use Date.plus for daily increments.

Example:

nextHour := DateTime.now + 1hr

sec ​

Int sec()

Get the whole seconds of the time as a number between 0 and 59.


ticks ​

Int ticks()

Return number of nanosecond ticks since 1 Jan 2000 UTC. Dates before this epoch will return a negative integer.


time ​

Time time()

Get the time component of this timestamp.


toCode ​

Str toCode()

Get this DateTime as a Fantom expression suitable for code generation.


toHttpStr ​

Str toHttpStr()

Format this time for use in an MIME or HTTP message according to RFC 2616 using the RFC 1123 format:

Sun, 06 Nov 1994 08:49:37 GMT

toIso ​

Str toIso()

Format this instance according to ISO 8601 using the pattern:

YYYY-MM-DD'T'hh:mm:ss.FFFz

Also see fromIso, toStr, and toHttpStr.


toJava ​

Int toJava()

Get this date in Java milliseconds since the epoch of 1 Jan 1970.


toLocale ​

Str toLocale(Str? pattern := null, Locale locale := Locale.cur())

Format this time according to the specified pattern. If pattern is null, then a localized default is used. Any ASCII letter in the pattern is interpreted as follows:

YY     Two digit year             07
YYYY   Four digit year            2007
M      One/two digit month        6, 11
MM     Two digit month            06, 11
MMM    Three letter abbr month    Jun, Nov
MMMM   Full month                 June, November
D      One/two digit day          5, 28
DD     Two digit day              05, 28
DDD    Day with suffix            1st, 2nd, 3rd, 24th
WWW    Three letter abbr weekday  Tue
WWWW   Full weekday               Tuesday
Q      Quarter number             3
QQQ    Quarter with suffix        3rd
QQQQ   Quarter spelled out        3rd Quarter
V      One/two digit week of year 1,52
VV     Two digit week of year     01,52
VVV    Week of year with suffix   1st,52nd
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
z      Time zone offset           Z, +03:00 (ISO 8601, XML Schema)
zzz    Time zone abbr             EST, EDT
zzzz   Time zone name             New_York
'xyz'  Literal characters
''     Single quote literal

A symbol immediately preceding a "F" pattern with no fraction to print is skipped.

Examples:

YYYY-MM-DD'T'hh:mm:ss.FFFz  =>  2009-01-16T09:57:35.097-05:00
DD MMM YYYY                 =>  06 Jan 2009
DD/MMM/YY                   =>  06/Jan/09
MMMM D, YYYY                =>  January 16, 2009
hh:mm:ss.fff zzzz           =>  09:58:54.845 New_York
k:mma                       =>  9:58a
k:mmAA                      =>  9:58AM

toRel ​

DateTime toRel()

Convenience for toTimeZone(TimeZone.rel). See docLang.


toStr ​

virtual override Str toStr()

Return programmatic string encoding formatted as follows:

"YYYY-MM-DD'T'hh:mm:ss.FFFFFFFFFz zzzz"

See toLocale for the pattern legend. The base of the string encoding conforms to ISO 8601 and XML Schema Part 2. The Fantom format also appends the timezone name to avoid the ambiguities associated with interpreting the time zone offset. Also see toIso and toHttpStr.

Examples:

"2000-04-03T00:00:00.123Z UTC"
"2006-10-31T01:02:03-05:00 New_York"
"2009-03-10T11:33:20Z London"
"2009-03-01T12:00:00+01:00 Amsterdam"

toTimeZone ​

DateTime toTimeZone(TimeZone tz)

Convert this DateTime to the specific timezone. The absolute point time as ticks remains the same, but the date and time fields will be converted to represent the new time zone. However if converting to or from TimeZone.rel then the resulting DateTime has the same day and time. Also see toUtc and toRel.

Example:

dt := DateTime("2010-06-03T10:30:00-04:00 New_York")
dt.toUtc  =>  2010-06-03T14:30:00Z UTC
dt.toRel  =>  2010-06-03T10:30:00Z Rel

toUtc ​

DateTime toUtc()

Convenience for toTimeZone(TimeZone.utc).


tz ​

TimeZone tz()

Get the time zone associated with this date time.


tzAbbr ​

Str tzAbbr()

Get the time zone's abbreviation for this time. See TimeZone.stdAbbr and TimeZone.dstAbbr.


weekOfYear ​

Int weekOfYear(Weekday startOfWeek := Weekday.localeStartOfWeek())

Return the week number of the year as a number between 1 and 53 using the given weekday as the start of the week (defaults to current locale).


weekday ​

Weekday weekday()

Get the day of the week for this time.


weekdayInMonth ​

static Int weekdayInMonth(Int year, Month mon, Weekday weekday, Int pos)

This method computes the day of month (1-31) for a given weekday. The pos parameter specifies the first, second, third, or fourth occurence of the weekday. A negative pos is used to compute the last (or second to last, etc) weekday in the month.

Examples:

// compute the second monday in Apr 2007
weekdayInMonth(2007, Month.apr, Weekday.mon, 2)

// compute the last sunday in Oct 2007
weekdayInMonth(2007, Month.oct, Weekday.sun, -1)

year ​

Int year()

Get the year as a number such as 2007.


Decimal ​

@Serializable { simple=true } const class Decimal : Num

Decimal is used to represent a decimal floating point more precisely than a Float. Decimal is the preferred numeric type for financial applications.

Constructors

fromStrParse a Str into a Decimal.

Fields

defValDefault value is 0.

Methods

absReturn the absolute value of this decimal.
compareCompare based on decimal value, scale is not considered for equality (unlike equals).
decrementDecrement by one.
divDivide this by b.
divFloatDivide this by b.
divIntDivide this by b.
equalsReturn true if same decimal with same scale.
hashReturn platform specific hashcode.
incrementIncrement by one.
maxReturn the larger of this and the specified Decimal values.
minReturn the smaller of this and the specified Decimal values.
minusSubtract b from this.
minusFloatSubtract b from this.
minusIntSubtract b from this.
modReturn remainder of this divided by b.
modFloatReturn remainder of this divided by b.
modIntReturn remainder of this divided by b.
multMultiply this with b.
multFloatMultiply this with b.
multIntMultiply this with b.
negateNegative of this.
plusAdd this with b.
plusFloatAdd this with b.
plusIntAdd this with b.
toCodeGet this Decimal as a Fantom code literal.
toLocaleFormat this decimal number for the current locale.
toStrGet string representation.

Slot Details ​


abs ​

Decimal abs()

Return the absolute value of this decimal. If this value is positive then return this, otherwise return the negation.


compare ​

virtual override Int compare(Obj obj)

Compare based on decimal value, scale is not considered for equality (unlike equals).


decrement ​

@Operator Decimal decrement()

Decrement by one. Shortcut is --a or a--.


defVal ​

const static Decimal defVal

Default value is 0.


div ​

@Operator Decimal div(Decimal b)

Divide this by b. Shortcut is a/b.


divFloat ​

@Operator Decimal divFloat(Float b)

Divide this by b. Shortcut is a/b.


divInt ​

@Operator Decimal divInt(Int b)

Divide this by b. Shortcut is a/b.


equals ​

virtual override Bool equals(Obj? obj)

Return true if same decimal with same scale.


fromStr ​

static new fromStr(Str s, Bool checked := true)

Parse a Str into a Decimal. If invalid format and checked is false return null, otherwise throw ParseErr.


hash ​

virtual override Int hash()

Return platform specific hashcode.


increment ​

@Operator Decimal increment()

Increment by one. Shortcut is ++a or a++.


max ​

Decimal max(Decimal that)

Return the larger of this and the specified Decimal values.


min ​

Decimal min(Decimal that)

Return the smaller of this and the specified Decimal values.


minus ​

@Operator Decimal minus(Decimal b)

Subtract b from this. Shortcut is a-b.


minusFloat ​

@Operator Decimal minusFloat(Float b)

Subtract b from this. Shortcut is a-b.


minusInt ​

@Operator Decimal minusInt(Int b)

Subtract b from this. Shortcut is a-b.


mod ​

@Operator Decimal mod(Decimal b)

Return remainder of this divided by b. Shortcut is a%b.


modFloat ​

@Operator Decimal modFloat(Float b)

Return remainder of this divided by b. Shortcut is a%b.


modInt ​

@Operator Decimal modInt(Int b)

Return remainder of this divided by b. Shortcut is a%b.


mult ​

@Operator Decimal mult(Decimal b)

Multiply this with b. Shortcut is a*b.


multFloat ​

@Operator Decimal multFloat(Float b)

Multiply this with b. Shortcut is a*b.


multInt ​

@Operator Decimal multInt(Int b)

Multiply this with b. Shortcut is a*b.


negate ​

@Operator Decimal negate()

Negative of this. Shortcut is -a.


plus ​

@Operator Decimal plus(Decimal b)

Add this with b. Shortcut is a+b.


plusFloat ​

@Operator Decimal plusFloat(Float b)

Add this with b. Shortcut is a+b.


plusInt ​

@Operator Decimal plusInt(Int b)

Add this with b. Shortcut is a+b.


toCode ​

Str toCode()

Get this Decimal as a Fantom code literal.


toLocale ​

Str toLocale(Str? pattern := null, Locale locale := Locale.cur())

Format this decimal number for the current locale. If pattern is null, then the locale's default pattern is used. See Float.toLocale for pattern language and examples.


toStr ​

virtual override Str toStr()

Get string representation.


Depend ​

@Serializable { simple=true } const class Depend : Obj

Depend models a dependency as a pod name and a version constraint. Convention for Fantom pods is a four part version format of major.minor.build.patch.

The string format for Depend:

<depend>        := <name> space* <constraints>
<constraints>   := <constraint> [space* "," space* <constraint>]*
<constraint>    := <versionSimple> | <versionPlus> | <versionRange>
<versionSimple> := <version>
<versionPlus>   := <version> space* "+"
<versionRange>  := <version> space* "-" space* <version>
<version>       := <digits> ["." <digits>]*
<digits>        := <digit> [<digits>]*
<digit>         := "0" - "9"

Note a simple version constraint such as "foo 1.2" really means "1.2.*" - it will match all build numbers and patch numbers within "1.2". Likewise "foo 1.2.64" will match all patch numbers within the "1.2.64" build. The "+" plus sign is used to specify a given version and anything greater. The "-" dash is used to specify an inclusive range. When using a range, the end version is matched using the same rules as a simple version - for example "4", "4.2", and "4.0.99" are all matches for "foo 1.2-4". You may specify a list of potential constraints separated by commas - a match for the entire dependency is made if any one constraint is matched.

Examples:

"foo 1.2"      Any version of foo 1.2 with any build or patch number
"foo 1.2.64"   Any version of foo 1.2.64 with any patch number
"foo 0+"       Any version of foo - version wildcard
"foo 1.2+"     Any version of foo 1.2 or greater
"foo 1.2-1.4"  Any version between 1.2 and 1.4 inclusive
"foo 1.2,1.4"  Any version of 1.2 or 1.4

Constructors

fromStrParse the string accordingly into a dependency.

Methods

endVersionReturn the ending version if versionRange
equalsTwo Depends are equal if they have same normalized string representation.
hashReturn a hash code based on the normalized string representation.
isPlusReturn if the constraint at the specified index is a versionPlus
isRangeReturn if the constraint at the specified index is a versionRange
isSimpleReturn if the constraint at the specified index is neither a plus nor a range
matchReturn if the specified version is a match against this dependency's constraints.
nameGet the pod name of the dependency.
sizeGet the number of version constraints.
toStrGet the normalized string format of this dependency.
versionGet the version constraint at specified index

Slot Details ​


endVersion ​

Version endVersion(Int index := 0)

Return the ending version if versionRange:

  • versionSimple: returns null
  • versionPlus: returns null
  • versionRange: returns end version

equals ​

virtual override Bool equals(Obj? that)

Two Depends are equal if they have same normalized string representation.


fromStr ​

static new fromStr(Str s, Bool checked := true)

Parse the string accordingly into a dependency. See class header for specification of the format. If invalid format and checked is false return null, otherwise throw ParseErr.


hash ​

virtual override Int hash()

Return a hash code based on the normalized string representation.


isPlus ​

Bool isPlus(Int index := 0)

Return if the constraint at the specified index is a versionPlus:

  • versionSimple: returns false
  • versionPlus: returns true
  • versionRange: returns false

isRange ​

Bool isRange(Int index := 0)

Return if the constraint at the specified index is a versionRange:

  • versionSimple: returns false
  • versionPlus: returns false
  • versionRange: returns true

isSimple ​

Bool isSimple(Int index := 0)

Return if the constraint at the specified index is neither a plus nor a range:

  • versionSimple: returns true
  • versionPlus: returns false
  • versionRange: returns false

match ​

Bool match(Version version)

Return if the specified version is a match against this dependency's constraints. See class header for matching rules.


name ​

Str name()

Get the pod name of the dependency.


size ​

Int size()

Get the number of version constraints. There is always at least one constraint.


toStr ​

virtual override Str toStr()

Get the normalized string format of this dependency. Normalized dependency strings do not contain any optional spaces. See class header for specification of the format.


version ​

Version version(Int index := 0)

Get the version constraint at specified index:

  • versionSimple: returns the version
  • versionPlus: returns the version
  • versionRange: returns the start version

Deprecated ​

@Serializable facet class Deprecated : Obj, Facet

Indicates that a type or slot is obsolete

Fields

msgMessage for compiler output when deprecated type or slot is used.

Slot Details ​


msg ​

const Str msg := ""

Message for compiler output when deprecated type or slot is used.


Duration ​

@Serializable { simple=true } const class Duration : Obj

Duration represents a relative duration of time with nanosecond precision.

Also see docLang.

Constructors

fromStrParse a Str into a Duration according to the Fantom literal format.
makeCreate a Duration which represents the specified number of nanosecond ticks.

Fields

defValDefault value is 0ns.
maxValMax value is equivalent to make(Int.maxVal).
minValMin value is equivalent to make(Int.minVal).

Methods

absAbsolute value - if this is a negative duration, then return its positive value.
bootGet the system timer at boot time of the Fantom VM.
clampClamp this duration between the min and max.
compareCompare based on nanosecond ticks.
divDivide this by b.
divFloatDivide this by b.
equalsReturn true if same number nanosecond ticks.
floorReturn a new Duration with this duration's nanosecond ticks truncated according to the specified accuracy.
fromIsoParse a duration according to ISO 8601.
hashReturn ticks().
maxReturn the maximum duration between this and that.
minReturn the minimum duration between this and that.
minusSubtract b from this.
multMultiply this with b.
multFloatMultiply this with b.
negateNegative of this.
nowGet the current value of the system timer.
nowTicksConvenience for now.ticks.
plusAdd this with b.
ticksReturn number of nanosecond ticks.
toCodeGet this Duration as a Fantom code literal.
toDayGet this duration in 24 hour days.
toHourGet this duration in hours.
toIsoFormat this duration according to ISO 8601.
toLocaleReturn human friendly string representation.
toMillisGet this duration in milliseconds.
toMinGet this duration in minutes.
toSecGet this duration in seconds.
toStrReturn string representation of the duration which is a valid duration literal format suitable for decoding via fromStr.
uptimeGet the duration which has elapsed since the Fantom VM was booted which is now - boot.

Slot Details ​


abs ​

Duration abs()

Absolute value - if this is a negative duration, then return its positive value.


boot ​

static Duration boot()

Get the system timer at boot time of the Fantom VM.


clamp ​

Duration clamp(Duration min, Duration max)

Clamp this duration between the min and max. If it's less than min then return min, if it's greater than max return max, otherwise return this duration itself.


compare ​

virtual override Int compare(Obj obj)

Compare based on nanosecond ticks.


defVal ​

const static Duration defVal

Default value is 0ns.


div ​

@Operator Duration div(Int b)

Divide this by b. Shortcut is a/b.


divFloat ​

@Operator Duration divFloat(Float b)

Divide this by b. Shortcut is a/b.


equals ​

virtual override Bool equals(Obj? obj)

Return true if same number nanosecond ticks.


floor ​

Duration floor(Duration accuracy)

Return a new Duration with this duration's nanosecond ticks truncated according to the specified accuracy. For example floor(1min) will truncate this duration such that its seconds are 0.0.


fromIso ​

static Duration fromIso(Str s, Bool checked := true)

Parse a duration according to ISO 8601. If invalid format and checked is false return null, otherwise throw ParseErr. The following restrictions are enforced:

  • Cannot specify a Y year or M month component since it is ambiguous
  • Only the S seconds component may include a fraction
  • Only nanosecond resolution is supported See toIso for example formats.

fromStr ​

static new fromStr(Str s, Bool checked := true)

Parse a Str into a Duration according to the Fantom literal format. If invalid format and checked is false return null, otherwise throw ParseErr. The following suffixes are supported:

ns:   nanoseconds  (x 1)
ms:   milliseconds (x 1,000,000)
sec:  seconds      (x 1,000,000,000)
min:  minutes      (x 60,000,000,000)
hr:   hours        (x 3,600,000,000,000)
day:  days         (x 86,400,000,000,000)

Examples:

Duration.fromStr("4ns")
Duration.fromStr("100ms")
Duration.fromStr("-0.5hr")

hash ​

virtual override Int hash()

Return ticks().


make ​

static new make(Int ticks)

Create a Duration which represents the specified number of nanosecond ticks.


max ​

Duration max(Duration that)

Return the maximum duration between this and that.


maxVal ​

const static Duration maxVal

Max value is equivalent to make(Int.maxVal).


min ​

Duration min(Duration that)

Return the minimum duration between this and that.


minVal ​

const static Duration minVal

Min value is equivalent to make(Int.minVal).


minus ​

@Operator Duration minus(Duration b)

Subtract b from this. Shortcut is a-b.


mult ​

@Operator Duration mult(Int b)

Multiply this with b. Shortcut is a*b.


multFloat ​

@Operator Duration multFloat(Float b)

Multiply this with b. Shortcut is a*b.


negate ​

@Operator Duration negate()

Negative of this. Shortcut is -a.


now ​

static Duration now()

Get the current value of the system timer. This method returns a relative time unrelated to system or wall-clock time. Typically it is the number of nanosecond ticks which have elapsed since system startup.


nowTicks ​

static Int nowTicks()

Convenience for now.ticks.


plus ​

@Operator Duration plus(Duration b)

Add this with b. Shortcut is a+b.


ticks ​

Int ticks()

Return number of nanosecond ticks.


toCode ​

Str toCode()

Get this Duration as a Fantom code literal.


toDay ​

Int toDay()

Get this duration in 24 hour days. Any fractional days are truncated with a loss of precision.


toHour ​

Int toHour()

Get this duration in hours. Any fractional hours are truncated with a loss of precision.


toIso ​

Str toIso()

Format this duration according to ISO 8601. Also see fromIso.

Examples:

8ns.toIso             =>  PT0.000000008S
100ms.toIso           =>  PT0.1S
(-20sec).toIso        =>  -PT20S
3.5min.toIso          =>  PT3M30S
1day.toIso            =>  PT24H
(1day+2hr+3min).toIso =>  P1DT2H3M

toLocale ​

Str toLocale()

Return human friendly string representation. TODO: enhance this for pattern


toMillis ​

Int toMillis()

Get this duration in milliseconds. Any fractional milliseconds are truncated with a loss of precision.


toMin ​

Int toMin()

Get this duration in minutes. Any fractional minutes are truncated with a loss of precision.


toSec ​

Int toSec()

Get this duration in seconds. Any fractional seconds are truncated with a loss of precision.


toStr ​

virtual override Str toStr()

Return string representation of the duration which is a valid duration literal format suitable for decoding via fromStr.


uptime ​

static Duration uptime()

Get the duration which has elapsed since the Fantom VM was booted which is now - boot.


Endian ​

@Serializable { simple=true } enum class Endian : Enum

Byte ordering.

Enum

bigMost significant byte first (network byte order)
littleLeast significant byte first

Constructors

fromStrReturn the Endian instance for the specified name.

Fields

valsList of Endian values indexed by ordinal

Slot Details ​


big ​

const static Endian big := ...

Most significant byte first (network byte order)


fromStr ​

static new fromStr(Str name, Bool checked := true)

Return the Endian instance for the specified name. If not a valid name and checked is false return null, otherwise throw ParseErr.


little ​

const static Endian little := ...

Least significant byte first


vals ​

const static Endian[] vals := Endian[Endian.big,Endian.little]

List of Endian values indexed by ordinal


Enum ​

abstract const class Enum : Obj

Enum is the base class for enum classes defined using the enum keyword. An enum models a fixed range of discrete values. Each value has an Int ordinal and a Str name.

Every enum class implicitly has the following slots auto-generated by the compiler:

  • a static const field for each name in the enum's range.
  • a static field called "vals" which contains the list of discrete values indexed by ordinal.
  • a static method called "fromStr" which maps an enum name to an enum instance

See Enums for details.

Methods

compareCompare based on ordinal value.
equalsEnums are only equal if same instance using ===.
nameGet the programatic name for this enum.
ordinalReturn ordinal value which is a zero based index into values.
toStrAlways returns name().

Slot Details ​


compare ​

virtual override Int compare(Obj obj)

Compare based on ordinal value.


equals ​

virtual override Bool equals(Obj? obj)

Enums are only equal if same instance using ===.


name ​

Str name()

Get the programatic name for this enum.


ordinal ​

Int ordinal()

Return ordinal value which is a zero based index into values.


toStr ​

virtual override Str toStr()

Always returns name().


Env ​

abstract const class Env : Obj

Env defines a pluggable class used to boot and manage a Fantom runtime environment. Use cur to access the current Env instance.

Constructors

makeSubclasses are constructed from a parent environment.

Methods

addShutdownHookAdd a function to be called on VM shutdown.
archMicroprocessor architecture name as one of the following constants
argsGet the command line arguments used to run the fan process as an immutable List of strings.
compileScriptCompile a script file into a pod and return the first public type declared in the script file.
compileScriptToJsCompile a script file into a pod and return the JS source code of resulting pod.
configLookup a configuration property for given pod/key pair.
curGet the current runtime environment
diagnosticsPoll for a platform dependent map of diagnostics name/value pairs for the current state of the VM.
errStandard error output stream.
exitTerminate the current virtual machine.
findAllFilesFind all the files in the environment which match a relative path such as "etc/foo/config.props".
findAllPodNamesReturn the list of pod names for all the pods currently installed in this environemnt.
findFileFind a file in the environment using a relative path such as "etc/foo/config.props".
findPodFileResolve the pod file for the given pod name.
gcRun the garbage collector.
homeDirGet the home directory of Fantom installation.
hostGet the local host name of the machine running the virtual machine process.
idHashReturn the default hash code of Obj.hash for the specified object regardless of whether the object has overridden the hash method.
inStandard input stream.
indexLookup all the matching values for a pod indexed key.
indexKeysGet listing of all keys mapped by indexed props.
indexPodNamesReturn list of all pod names that define the given key.
javaVersionGet the Java VM Version as a single integer (8, 9, etc.).
localeLookup a localized property for the specified pod/key pair.
mainMethodGet the main method which was used to run this Fantom VM.
osOperating system name as one of the following constants
outStandard output stream.
parentGet the parent environment or null if this is the bootstrap environment.
pathPath used by findFile if this is a PathEnv.
platformName of the host platform as a string formatted as "<os>-<arch>".
promptPrompt the user to enter a command line from standard input.
promptPasswordPrompt the user to enter a password from standard input with echo disabled.
propsReturn a merged key/value map of all the prop files found using the following resolution rules
removeShutdownHookRemove a shutdown hook function which was added by addShutdownHook.
runtimeVirtual machine runtime as one of the following constants
tempDirGet the temp directory to use for scratch files.
userGet the user name of the user account used to run the virtual machine process.
varsGet the environment variables as a case insensitive, immutable map of Str name/value pairs.
workDirGet the working directory to use for saving compiled pods and configuration information.

Slot Details ​


addShutdownHook ​

virtual Void addShutdownHook(|->Void| hook)

Add a function to be called on VM shutdown. Throw NotImmutableErr if the function is not immutable. Default implementation delegates to parent.


arch ​

Str arch()

Microprocessor architecture name as one of the following constants:

  • "x86"
  • "x86_64"
  • "ppc"
  • "sparc"
  • "ia64"
  • "ia64_32"
  • "aarch64"

args ​

virtual Str[] args()

Get the command line arguments used to run the fan process as an immutable List of strings. Default implementation delegates to parent.


compileScript ​

virtual Type compileScript(File f, [Str:Obj]? options := null)

Compile a script file into a pod and return the first public type declared in the script file. If the file has been previously compiled and hasn't changed, then a cached type is returned. If the script contains errors then the first CompilerErr found is thrown. The options available:

  • logLevel: the default LogLevel to use for logging the compilation process and errors
  • log: the CompilerLog to use for logging the compilation process and errors
  • logOut: an output stream to capture logging
  • force: pass true to not use caching, always forces a recompile

compileScriptToJs ​

virtual Str compileScriptToJs(File f, [Str:Obj]? options := null)

Compile a script file into a pod and return the JS source code of resulting pod. If the script contains errors then the first CompilerErr found is thrown. The options available:

  • podName: the name of pod created for script
  • logLevel: the default LogLevel to use for logging the compilation process and errors
  • log: the CompilerLog to use for logging the compilation process and errors
  • logOut: an output stream to capture logging
  • output: The output format of the compile javascript. Use "legacy" for old js format, "js" for CommonJs and "esm" for ES module. The default is "js" if not specified.

config ​

virtual Str? config(Pod pod, Str key, Str? def := null)

Lookup a configuration property for given pod/key pair. If not found then return def. Default implementation routes to props using max age of one minute:

props(pod, `config.props`, 1min).get(key, def)

Also see Pod.config and Env.


cur ​

static Env cur()

Get the current runtime environment


diagnostics ​

virtual Str:Obj diagnostics()

Poll for a platform dependent map of diagnostics name/value pairs for the current state of the VM. Java platforms return key values from the java.lang.management interface. Default implementation delegates to parent.


err ​

virtual OutStream err()

Standard error output stream. Default implementation delegates to parent.


exit ​

virtual Void exit(Int status := 0)

Terminate the current virtual machine. Default implementation delegates to parent.


findAllFiles ​

virtual File[] findAllFiles(Uri uri)

Find all the files in the environment which match a relative path such as "etc/foo/config.props". It is possible to have multiple matches if the environment uses a search path model. If the list contains more than one item, then the first file has the highest priority and the last item has the lowest priority. If the URI is not relative then throw ArgErr. Return empty list if the file is not found in environment. Default implementation delegates to parent.


findAllPodNames ​

virtual Str[] findAllPodNames()

Return the list of pod names for all the pods currently installed in this environemnt. This method is used by Pod.list and for constructing the type database. Each of these names must be resolvable by findPodFile. The default implementation routes to findFile to look in the "lib/fan" directory and assumes a naming convention of "{name}.pod".


findFile ​

virtual File? findFile(Uri uri, Bool checked := true)

Find a file in the environment using a relative path such as "etc/foo/config.props". If the URI is not relative then throw ArgErr. If the file is not found in the environment then throw UnresolvedErr or return null based on checked flag. If findAllFiles would return multiple matches, then this method should always return the file with the highest priority. Default implementation delegates to parent.


findPodFile ​

virtual File? findPodFile(Str podName)

Resolve the pod file for the given pod name. If the name cannot be resolved to a pod, return null. The default implementation routes to findFile to look in "lib/fan" directory.


gc ​

virtual Void gc()

Run the garbage collector. No guarantee is made to what the VM will actually do. Default implementation delegates to parent.


homeDir ​

virtual File homeDir()

Get the home directory of Fantom installation. Default implementation delegates to parent.


host ​

virtual Str host()

Get the local host name of the machine running the virtual machine process. Default implementation delegates to parent.


idHash ​

Int idHash(Obj? obj)

Return the default hash code of Obj.hash for the specified object regardless of whether the object has overridden the hash method. If null then return 0.


in ​

virtual InStream in()

Standard input stream. Default implementation delegates to parent.


index ​

virtual Str[] index(Str key)

Lookup all the matching values for a pod indexed key. If no matches are found return the empty list. Indexed props are declared in your pod's build script, and coalesced into a master index by the current environment. See docLang for details.


indexKeys ​

virtual Str[] indexKeys()

Get listing of all keys mapped by indexed props. The values of each key may be resolved by the index method. See docLang for details. NOTE: Java runtime only


indexPodNames ​

virtual Str[] indexPodNames(Str key)

Return list of all pod names that define the given key. NOTE: Java runtime only


javaVersion ​

Int javaVersion()

Get the Java VM Version as a single integer (8, 9, etc.). If the runtime is not java, return 0.


locale ​

virtual Str? locale(Pod pod, Str key, Str? def := "pod::key", Locale locale := Locale.cur())

Lookup a localized property for the specified pod/key pair. The following rules are used for resolution:

  1. props(pod, `locale/{locale}.props`)
  2. props(pod, `locale/{lang}.props`)
  3. props(pod, `locale/en.props`)
  4. Fallback to pod::key unless def specified

Where {locale} is Locale.toStr and {lang} is Locale.lang. The maxAge parameter is set to Duration.maxVal (cached for life of the VM).

Also see Pod.locale and Localization.


mainMethod ​

virtual Method? mainMethod()

Get the main method which was used to run this Fantom VM. Return null if VM was booted outside of a Fantom main method. Default implementation delegates to parent.


make ​

new make(Env parent := Env.cur())

Subclasses are constructed from a parent environment.


os ​

Str os()

Operating system name as one of the following constants:

  • "win32"
  • "macosx"
  • "linux"
  • "aix"
  • "solaris"
  • "hpux"
  • "qnx"

out ​

virtual OutStream out()

Standard output stream. Default implementation delegates to parent.


parent ​

Env? parent()

Get the parent environment or null if this is the bootstrap environment. Many virtual methods delegate to their parent by default.


path ​

virtual File[] path()

Path used by findFile if this is a PathEnv.


platform ​

Str platform()

Name of the host platform as a string formatted as "<os>-<arch>". See os and arch.


prompt ​

virtual Str? prompt(Str msg := "")

Prompt the user to enter a command line from standard input. This method routes to Console.prompt.


promptPassword ​

virtual Str? promptPassword(Str msg := "")

Prompt the user to enter a password from standard input with echo disabled. This method routes to Console.promptPassword.


props ​

virtual Str:Str props(Pod pod, Uri uri, Duration maxAge)

Return a merged key/value map of all the prop files found using the following resolution rules:

  1. Env.findAllFiles: "etc/{pod}/{uri}"
  2. Pods indexed with sys.envProps: "/{pod}/uri"
  3. Pod.files: "/{uri}"

The uri must be relative. Note that props such as locale files can be bundled into a pod for deployment and searched by adding an indexed prop with the key "sys.envProps" and the pod name as the value. This feature does not support "config.props".

The files are parsed using InStream.readProps and merged according to their priority order. If the file is defined as a resource in the pod itself, then it is treated as lowest priority. The first file returned by findAllFiles is treated as highest priority and overwrites any key-value pairs defined at a lower priority.

The map is cached so that subsequent calls for the same path don't require accessing the file system again. The maxAge parameter specifies the tolerance accepted before a cache refresh is performed to check if any of the files have been modified.

Also see Pod.props and Env.


removeShutdownHook ​

virtual Bool removeShutdownHook(|->Void| hook)

Remove a shutdown hook function which was added by addShutdownHook. Remove true if hook had been previously added and was unregistered, false otherwise. Default implementation delegates to parent.


runtime ​

Str runtime()

Virtual machine runtime as one of the following constants:

  • "java"
  • "dotnet"
  • "js"

tempDir ​

virtual File tempDir()

Get the temp directory to use for scratch files. Default implementation delegates to parent.


user ​

virtual Str user()

Get the user name of the user account used to run the virtual machine process. Default implementation delegates to parent.


vars ​

virtual Str:Str vars()

Get the environment variables as a case insensitive, immutable map of Str name/value pairs. The environment map is initialized from the following sources from lowest priority to highest priority:

  1. shell environment variables
  2. Java system properties (Java VM only obviously)

Default implementation delegates to parent.


workDir ​

virtual File workDir()

Get the working directory to use for saving compiled pods and configuration information. Default implementation delegates to parent.


Err ​

const class Err : Obj

Err is the base class of all exceptions.

Constructors

makeConstruct with specified error message and optional root cause.

Methods

causeGet the underyling cause exception or null.
msgGet the string message passed to the contructor or empty string if a message is not available.
toStrReturn the qualified type name and optional message.
traceDump the stack trace of this exception to the specified output stream (or Env.cur.err by default).
traceToStrDump the stack trace of this exception to a Str.

Slot Details ​


cause ​

Err? cause()

Get the underyling cause exception or null.


make ​

new make(Str msg := "", Err? cause := null)

Construct with specified error message and optional root cause.


msg ​

Str msg()

Get the string message passed to the contructor or empty string if a message is not available.


toStr ​

virtual override Str toStr()

Return the qualified type name and optional message.


trace ​

This trace(OutStream out := Env.cur().err(), [Str:Obj]? options := null)

Dump the stack trace of this exception to the specified output stream (or Env.cur.err by default). Return this.

The options may be used to specify the format of the output:

  • "indent": Int for initial number of indentation spaces

  • "maxDepth": Int specifies how many methods in each

    exception of chain to include.  If unspecified the
    default is configured from the "errTraceMaxDepth" prop
    in etc/sys/config.props.

traceToStr ​

Str traceToStr()

Dump the stack trace of this exception to a Str.


Facet ​

const mixin Facet

Facet is a mixin included into every facet type.

See Facets for details.

Slot Details ​


FacetMeta ​

@Serializable facet class FacetMeta : Obj, Facet

Facet meta-data applied to facet classes.

Fields

inheritedIndicates whether the facet is inherited by sub-types.

Slot Details ​


inherited ​

const Bool inherited := false

Indicates whether the facet is inherited by sub-types. See docLang for additional details.


Field ​

const class Field : Slot

Field is a slot which models the ability to get and set a value.

Methods

getGet the field for the specified instance.
makeSetFuncConstruct a function which sets zero or more fields on a target object.
setSet the field for the specified instance.
typeType stored by the field.

Slot Details ​


get ​

virtual Obj? get(Obj? instance := null)

Get the field for the specified instance. If the field is static, then the instance parameter is ignored. If the getter is non-null, then it is used to get the field.


makeSetFunc ​

static |Obj| makeSetFunc(Field:Obj? vals)

Construct a function which sets zero or more fields on a target object. The function can be passed to a constructor which takes an it-block to reflectively set const fields. Example:

const class Foo
{
  new make(|This|? f := null) { f?.call(this) }
  const Int x
}

f := Field.makeSetFunc([Foo#x: 7])
Foo foo := Foo#.make([f])

set ​

virtual Void set(Obj? instance, Obj? value)

Set the field for the specified instance. If the field is static, then the instance parameter is ignored. If the setter is non-null, then it is used to set the field.


type ​

Type type()

Type stored by the field.


FieldNotSetErr ​

const class FieldNotSetErr : Err

FieldNotSetErr indicates a non-nullable field was not set by the constructor it-block.

Constructors

makeConstruct 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.


File ​

abstract const class File : Obj

File is used to represent a Uri path to a file or directory. See examples.

Constructors

makeMake a File for the Uri which represents a file on the local file system.
makeNewProtected constructor for subclasses.

Fields

modifiedGet time the file was last modified or null if unknown.
pathSepReturn the platform's separator for a list of paths: semicolon on Windows, colon on Unix.
sepReturn the platform's separator for names within a path: backslash on Windows, forward slash on Unix.

Methods

basenameConvenience for uri.basename.
copyIntoCopy this file under the specified directory and return the destination file.
copyToCopy this file or directory to the new specified location.
createCreate a file or directory represented by this Uri.
createDirCreate a sub-directory under this directory.
createFileCreate a file under this directory.
createTempCreate a temporary file which is guaranteed to be a new, empty file with a unique name.
deleteDelete this file.
deleteOnExitRequest that the file or directory represented by this File be deleted when the virtual machine exits.
eachLineConvenience for in.eachLine.
equalsFile equality is based on the un-normalized Uri used to create the File.
existsReturn if this file exists.
extConvenience for uri.ext.
hashReturn uri.hash.
inOpen a new buffered InStream used to read from this file.
isDirConvenience for uri.isDir
isEmptyIf this is a file, return if the file size is zero or null.
isExecutableReturn if this file is executable.
isHiddenReturn if this file should be hidden to users.
isReadableReturn if this file is readable.
isWritableReturn if this file is writable.
listList the files contained by this directory.
listDirsList the child sub-directories contained by this directory.
listFilesList the child files (excludes directories) contained by this directory.
mimeTypeDefault implementation is convenience for uri.mimeType.
mmapMemory map the region of the file specified by pos and size.
moveIntoMove this file under the specified directory and return the destination file.
moveToMove this file to the specified location.
nameConvenience for uri.name.
normalizeNormalize this file path to its canonical representation.
openOpen this file for random access.
osMake a File for the specified operating system specific path on the local file system.
osPathGet this File as an operating system specific path on the local system.
osRootsGet the root directories of the operating system's local file system.
outOpen a new buffered OutStream used to write to this file.
parentGet the parent directory of this file or null.
pathConvenience for uri.path.
pathStrConvenience for uri.pathStr.
plusMake a new File instance by joining this file's Uri together with the specified path.
readAllBufConvenience for in.readAllBuf.
readAllLinesConvenience for in.readAllLines.
readAllStrConvenience for in.readAllStr.
readObjConvenience for in.readObj The input stream is guaranteed to be closed.
readPropsConvenience for in.readProps().
renameRenaming this file within its current directory.
sizeReturn the size of the file in bytes, otherwise null if a directory or unknown.
storeGet the store instance which models the storage pool, device, partition, or volume used to store this file.
toStrReturn uri.toStr.
uriReturn the Uri path used to create this File.
walkRecursively walk this file/directory top down.
withInRead the file's input stream using a callback.
withOutWrite to the file's output stream using a callback.
writeObjConvenience for out.writeObj The output stream is guaranteed to be closed.
writePropsConvenience for out.writeProps().

Slot Details ​


basename ​

Str basename()

Convenience for uri.basename.


copyInto ​

virtual File copyInto(File dir, [Str:Obj]? options := null)

Copy this file under the specified directory and return the destination file. This method is a convenience for:

return this.copyTo(dir + this.name, options)

copyTo ​

virtual File copyTo(File to, [Str:Obj]? options := null)

Copy this file or directory to the new specified location. If this file represents a directory, then it recursively copies the entire directory tree.

The options map is used to customize how the copy is performed. The following summarizes the options:

  • exclude: Regex or |File f->Bool|
  • overwrite: Bool or |File f->Bool|

If the "exclude" option is a Regex - each source file's Uri string is checked for a match to skip. If a directory is skipped, then its children are skipped also. The exclude option can also be a function of type |File f->Bool| to check each file. Exclude processing is performed first before checking for an overwrite.

If during the copy, an existing file of the same name is found, then the "overwrite" option should be true to overwrite or false to skip. The overwrite option can also be a function of type |File to,File from->Bool| which is passed every to/from file to be overwritten. If the overwrite function throws an exception, it is raised to the copyTo caller. If a directory overwrite is skipped, then its children are skipped too. If options are null or overwrite is unspecified then the copy is immediately terminated with an IOErr.

Any IOErr or other error encountered during the file copy immediately terminates the copy and is raised to the caller, which might leave the copy in an unfinished state.

Return the to destination file.


create ​

abstract File create()

Create a file or directory represented by this Uri. If isDir() is false then create an empty file, or if the file already exists overwrite it to empty. If isDir() is true then create a directory, or if the directory already exists do nothing. This method will automatically create any parent directories. Throw IOErr on error. Return this.


createDir ​

File createDir(Str name)

Create a sub-directory under this directory. Convenience for create:

return (this+name/.toUri).create

Throw IOErr if this file is not a directory or if there is an error creating the new directory. Return the directory created.


createFile ​

File createFile(Str name)

Create a file under this directory. Convenience for create:

return (this+name.toUri).create

Throw IOErr if this file is not a directory or if there is an error creating the new file. Return the file created.


createTemp ​

static File createTemp(Str prefix := "fan", Str suffix := ".tmp", File? dir := null)

Create a temporary file which is guaranteed to be a new, empty file with a unique name. The file name will be generated using the specified prefix and suffix. If dir is non-null then it is used as the file's parent directory, otherwise the system's default temporary directory is used. If dir is specified it must be a directory on the local file system. See deleteOnExit if you wish to have the file automatically deleted on exit. Throw IOErr on error.

Examples:

File.createTemp("x", ".txt") => `/tmp/x67392.txt`
File.createTemp.deleteOnExit => `/tmp/fan5284.tmp`

delete ​

abstract Void delete()

Delete this file. If this file represents a directory, then recursively delete it. If the file does not exist, then no action is taken. Throw IOErr on error.


deleteOnExit ​

abstract File deleteOnExit()

Request that the file or directory represented by this File be deleted when the virtual machine exits. Long running applications should use this method with care since each file marked to delete will consume resources. Throw IOErr on error. Return this.


eachLine ​

Void eachLine(|Str| f)

Convenience for in.eachLine. The input stream is guaranteed to be closed.


equals ​

virtual override Bool equals(Obj? that)

File equality is based on the un-normalized Uri used to create the File.


exists ​

abstract Bool exists()

Return if this file exists.


ext ​

Str? ext()

Convenience for uri.ext.


hash ​

virtual override Int hash()

Return uri.hash.


in ​

abstract InStream in(Int? bufferSize := 4096)

Open a new buffered InStream used to read from this file. A bufferSize of null or zero will return an unbuffered input stream. Throw IOErr on error.


isDir ​

Bool isDir()

Convenience for uri.isDir


isEmpty ​

virtual Bool isEmpty()

If this is a file, return if the file size is zero or null. If this is a directory, return if this directory has no files without reading a full listing.


isExecutable ​

virtual Bool isExecutable()

Return if this file is executable.


isHidden ​

virtual Bool isHidden()

Return if this file should be hidden to users. On Unix hidden files start with a dot and on Windows a metadata flag is used.


isReadable ​

virtual Bool isReadable()

Return if this file is readable.


isWritable ​

virtual Bool isWritable()

Return if this file is writable.


list ​

abstract File[] list(Regex? pattern := null)

List the files contained by this directory. This list includes both child sub-directories and normal files. If the directory is empty or this file doesn't represent a directory, then return an empty list. If pattern is non-null then only filenames matched are returned or if null then all filenames.


listDirs ​

virtual File[] listDirs(Regex? pattern := null)

List the child sub-directories contained by this directory. If the directory doesn't contain any sub-directories or this file doesn't represent a directory, then return an empty list. If pattern is non-null then only filenames matched are returned or if null then all filenames.


listFiles ​

virtual File[] listFiles(Regex? pattern := null)

List the child files (excludes directories) contained by this directory. If the directory doesn't contain any child files or this file doesn't represent a directory, then return an empty list. If pattern is non-null then only filenames matched are returned or if null then all filenames.


make ​

static new make(Uri uri, Bool checkSlash := true)

Make a File for the Uri which represents a file on the local file system. If creating a Uri to a directory, then the Uri must end in a trailing "/" slash or IOErr is thrown - or you may pass false for checkSlash in which case the trailing slash is implicitly added. However if a trailing slash is added, then the resulting File's uri will not match the uri passed to this method. If the file doesn't exist, then it is assumed to be to a directory based on a trailing slash (see isDir). If the Uri has a relative path, then it is assumed to be relative to the current working directory. Throw ArgErr if the Uri has a scheme other than null or "file:".


makeNew ​

new makeNew(Uri uri)

Protected constructor for subclasses.


mimeType ​

virtual MimeType? mimeType()

Default implementation is convenience for uri.mimeType.


mmap ​

abstract Buf mmap(Str mode := "rw", Int pos := 0, Int? size := null)

Memory map the region of the file specified by pos and size. If size is null, then use the file's size as a default. The file is paged into virtual memory on demand. Modes are:

  • "r": map the file for reading only. Throws IOErr if file does not exist.
  • "rw": open the file for reading and writing; create if the file does not exist.
  • "p": private read/write mode will not propagate changes to other processes which have mapped the file.

modified ​

abstract DateTime? modified

Get time the file was last modified or null if unknown.


moveInto ​

virtual File moveInto(File dir)

Move this file under the specified directory and return the destination file. This method is a convenience for:

return this.moveTo(dir + this.name)

moveTo ​

abstract File moveTo(File to)

Move this file to the specified location. If this file is a directory, then the entire directory is moved. If the target file already exists or the move fails, then an IOErr is thrown. Return the to destination file.


name ​

Str name()

Convenience for uri.name.


normalize ​

abstract File normalize()

Normalize this file path to its canonical representation. If a file on the local file system, then the uri will include the "file:" scheme. Throw IOErr on error.


open ​

abstract Buf open(Str mode := "rw")

Open this file for random access. Modes are:

  • "r": open the file for reading only. Throws IOErr if file does not exist.
  • "rw": open the file for reading and writing; create if the file does not exist.

The Buf instance returned is backed by a random access file pointer. It provides the same functionality as a memory backed buffer, except for a couple of exceptions such as Buf.unread. The resulting Buf is a raw interface to the random access file, no buffering is provided at the framework level - so use methods which only access a few bytes carefully. However methods which transfer data with other Bufs and IO streams will use an internal buffer for efficiency.


os ​

static File os(Str osPath)

Make a File for the specified operating system specific path on the local file system.


osPath ​

abstract Str? osPath()

Get this File as an operating system specific path on the local system. If this File doesn't represent a path on the local file system then return null.


osRoots ​

static File[] osRoots()

Get the root directories of the operating system's local file system.


out ​

abstract OutStream out(Bool append := false, Int? bufferSize := 4096)

Open a new buffered OutStream used to write to this file. If append is true, then we open the file to append to the end, otherwise it is opened as an empty file. A bufferSize of null or zero will return an unbuffered output stream. Throw IOErr on error.


parent ​

abstract File? parent()

Get the parent directory of this file or null. Also see Uri.parent.


path ​

Str[] path()

Convenience for uri.path.


pathSep ​

const static Str pathSep

Return the platform's separator for a list of paths: semicolon on Windows, colon on Unix.


pathStr ​

Str pathStr()

Convenience for uri.pathStr.


plus ​

@Operator abstract File plus(Uri path, Bool checkSlash := true)

Make a new File instance by joining this file's Uri together with the specified path. If the file maps to a directory and the resulting Uri doesn't end in slash then an IOErr is thrown - or pass false for checkSlash to have the slash implicitly added.

Examples:

File(`a/b/`) + `c` => File(`a/b/c`)
File(`a/b`) + `c`  => File(`a/c`)

readAllBuf ​

Buf readAllBuf()

Convenience for in.readAllBuf. The input stream is guaranteed to be closed.


readAllLines ​

Str[] readAllLines()

Convenience for in.readAllLines. The input stream is guaranteed to be closed.


readAllStr ​

Str readAllStr(Bool normalizeNewlines := true)

Convenience for in.readAllStr. The input stream is guaranteed to be closed.


readObj ​

Obj? readObj([Str:Obj]? options := null)

Convenience for in.readObj The input stream is guaranteed to be closed.


readProps ​

Str:Str readProps()

Convenience for in.readProps(). The input stream is guaranteed to be closed.


rename ​

virtual File rename(Str newName)

Renaming this file within its current directory. This method is a convenience for:

return this.moveTo(parent + newName)

sep ​

const static Str sep

Return the platform's separator for names within a path: backslash on Windows, forward slash on Unix.


size ​

abstract Int? size()

Return the size of the file in bytes, otherwise null if a directory or unknown.


store ​

virtual FileStore store()

Get the store instance which models the storage pool, device, partition, or volume used to store this file. Raise UnsupportedErr if this file is not associated with a store.


toStr ​

virtual override Str toStr()

Return uri.toStr.


uri ​

Uri uri()

Return the Uri path used to create this File. This Uri may be absolute or relative.


walk ​

virtual Void walk(|File| c)

Recursively walk this file/directory top down. If this file is not a directory then the callback is invoked exactly once with this file. If a directory, then the callback is invoked with this file, then recursively for each child file.


withIn ​

virtual Obj? withIn(|InStream->Obj?| f)

Read the file's input stream using a callback. The input stream is guaranteed to be closed when the callback exits.

The method returns the value returned by the callback.


withOut ​

virtual Void withOut(|OutStream| f)

Write to the file's output stream using a callback. The output stream is guaranteed to be closed when the callback exits.


writeObj ​

Void writeObj(Obj? obj, [Str:Obj]? options := null)

Convenience for out.writeObj The output stream is guaranteed to be closed.


writeProps ​

Void writeProps(Str:Str props)

Convenience for out.writeProps(). The output stream is guaranteed to be closed.


FileStore ​

abstract const class FileStore : Obj

FileStore represents the storage pool, device, partition, or volume used to store files.

Methods

availSpaceNumber of bytes available for use by the application or null if unknown.
freeSpaceNumber of bytes unallocated in the store or null if unknown.
totalSpaceTotal number of bytes in the store or null if unknown.

Slot Details ​


availSpace ​

abstract Int? availSpace()

Number of bytes available for use by the application or null if unknown.


freeSpace ​

abstract Int? freeSpace()

Number of bytes unallocated in the store or null if unknown.


totalSpace ​

abstract Int? totalSpace()

Total number of bytes in the store or null if unknown.


Float ​

@Serializable { simple=true } const class Float : Num

Float is used to represent a 64-bit floating point number.

Constructors

fromStrParse a Str into a Float.

Fields

defValDefault value is 0f.
eFloat value for e which is the base of natural logarithms.
nanFloat value for Not-A-Number.
negInfFloat value for negative infinity.
piFloat value for pi which is the ratio of the circumference of a circle to its diameter.
posInfFloat value for positive infinity.

Methods

absReturn the absolute value of this float.
acosReturn the arc cosine.
approxReturn if this Float is approximately equal to the given Float by the specified tolerance.
asinReturn the arc sine.
atanReturn the arc tangent.
atan2Converts rectangular coordinates (x, y) to polar (r, theta).
bitsReturn 64-bit representation according IEEE 754 floating-point double format bit layout.
bits32Return 32-bit representation according IEEE 754 floating-point single format bit layout.
ceilReturns the smallest whole number greater than or equal to this number.
clampClamp this float between the min and max.
compareCompare based on floating point value.
cosReturn the cosine of this angle in radians.
coshReturn the hyperbolic cosine.
decrementDecrement by one.
divDivide this by b.
divDecimalDivide this by b.
divIntDivide this by b.
equalsReturn true if same float value.
expReturn e raised to this power.
floorReturns the largest whole number less than or equal to this number.
hashReturn bits().
incrementIncrement by one.
isNaNReturn if this is Float.nan.
isNegZeroReturn if this is negative zero value.
logReturn natural logarithm of this number.
log10Return base 10 logarithm of this number.
makeBitsMake a Float for the specified 64-bit representation according IEEE 754 floating-point double format bit layout.
makeBits32Make a Float for the specified 32-bit representation according IEEE 754 floating-point single format bit layout.
maxReturn the larger of this and the specified Float values.
minReturn the smaller of this and the specified Float values.
minusSubtract b from this.
minusDecimalSubtract b from this.
minusIntSubtract b from this.
modReturn remainder of this divided by b.
modDecimalReturn remainder of this divided by b.
modIntReturn remainder of this divided by b.
multMultiply this with b.
multDecimalMultiply this with b.
multIntMultiply this with b.
negateNegative of this.
normNegZeroIf this value is negative zero then return normalized zero, otherwise return this value.
plusAdd this with b.
plusDecimalAdd this with b.
plusIntAdd this with b.
powReturn this value raised to the specified power.
randomGenerate a random float between 0.0 inclusive and 1.0 exclusive.
roundReturns the nearest whole number to this number.
sinReturn sine of this angle in radians.
sinhReturn hyperbolic sine.
sqrtReturn square root of this value.
tanReturn tangent of this angle in radians.
tanhReturn hyperbolic tangent.
toCodeGet this Float as a Fantom code literal.
toDegreesConvert this angle in radians to an angle in degrees.
toLocaleFormat this floating point number for the current locale.
toRadiansConvert this angle in degrees to an angle in radians.
toStrGet string representation according to the lexical representation defined by Section 3.2.5 of XML Schema Part 2.

Slot Details ​


abs ​

Float abs()

Return the absolute value of this float. If this value is positive then return this, otherwise return the negation.


acos ​

Float acos()

Return the arc cosine.


approx ​

Bool approx(Float r, Float? tolerance := null)

Return if this Float is approximately equal to the given Float by the specified tolerance. If tolerance is null, then it is computed using the magnitude of the two Floats. It is useful for comparing Floats since often they lose a bit of precision during manipulation. This method is equivalent to:

if (tolerance == null) tolerance = min(abs(this/1e6), abs(r/1e6))
(this - r).abs < tolerance

asin ​

Float asin()

Return the arc sine.


atan ​

Float atan()

Return the arc tangent.


atan2 ​

static Float atan2(Float y, Float x)

Converts rectangular coordinates (x, y) to polar (r, theta).


bits ​

Int bits()

Return 64-bit representation according IEEE 754 floating-point double format bit layout. This method is paired with Float.makeBits.


bits32 ​

Int bits32()

Return 32-bit representation according IEEE 754 floating-point single format bit layout. This method is paired with Float.makeBits32.


ceil ​

Float ceil()

Returns the smallest whole number greater than or equal to this number.


clamp ​

Float clamp(Float min, Float max)

Clamp this float between the min and max. If its less than min then return min, if its greater than max return max, otherwise return this float itself.


compare ​

virtual override Int compare(Obj obj)

Compare based on floating point value.

NaN works as follows:

  • for the <=> operator NaN is always less than other values and equal to itself (so sort works as expected)
  • for all other comparison operators anything compared against NaN is false (normal Java semanatics)

Examples:

Float.nan <=> Float.nan  =>  0
2f <=> Float.nan         =>  1
Float.nan <=> 2f         =>  -1
2f < Float.nan           =>  false
Float.nan < 2f           =>  false
Float.nan <= Float.nan   =>  false

cos ​

Float cos()

Return the cosine of this angle in radians.


cosh ​

Float cosh()

Return the hyperbolic cosine.


decrement ​

@Operator Float decrement()

Decrement by one. Shortcut is --a or a--.


defVal ​

const static Float defVal

Default value is 0f.


div ​

@Operator Float div(Float b)

Divide this by b. Shortcut is a/b.


divDecimal ​

@Operator Decimal divDecimal(Decimal b)

Divide this by b. Shortcut is a/b.


divInt ​

@Operator Float divInt(Int b)

Divide this by b. Shortcut is a/b.


e ​

const static Float e

Float value for e which is the base of natural logarithms.


equals ​

virtual override Bool equals(Obj? obj)

Return true if same float value. Like Java, NaN != NaN. Also see compare.


exp ​

Float exp()

Return e raised to this power.


floor ​

Float floor()

Returns the largest whole number less than or equal to this number.


fromStr ​

static new fromStr(Str s, Bool checked := true)

Parse a Str into a Float. Representations for infinity and not-a-number are "-INF", "INF", "NaN". This string format matches the lexical representation of Section 3.2.5 of XML Schema Part 2. If invalid format and checked is false return null, otherwise throw ParseErr.


hash ​

virtual override Int hash()

Return bits().


increment ​

@Operator Float increment()

Increment by one. Shortcut is ++a or a++.


isNaN ​

Bool isNaN()

Return if this is Float.nan. Also see compare.


isNegZero ​

Bool isNegZero()

Return if this is negative zero value.


log ​

Float log()

Return natural logarithm of this number.


log10 ​

Float log10()

Return base 10 logarithm of this number.


makeBits ​

static Float makeBits(Int bits)

Make a Float for the specified 64-bit representation according IEEE 754 floating-point double format bit layout. This method is paired with Float.bits.


makeBits32 ​

static Float makeBits32(Int bits)

Make a Float for the specified 32-bit representation according IEEE 754 floating-point single format bit layout. This method is paired with Float.bits32.


max ​

Float max(Float that)

Return the larger of this and the specified Float values.


min ​

Float min(Float that)

Return the smaller of this and the specified Float values.


minus ​

@Operator Float minus(Float b)

Subtract b from this. Shortcut is a-b.


minusDecimal ​

@Operator Decimal minusDecimal(Decimal b)

Subtract b from this. Shortcut is a-b.


minusInt ​

@Operator Float minusInt(Int b)

Subtract b from this. Shortcut is a-b.


mod ​

@Operator Float mod(Float b)

Return remainder of this divided by b. Shortcut is a%b.


modDecimal ​

@Operator Decimal modDecimal(Decimal b)

Return remainder of this divided by b. Shortcut is a%b.


modInt ​

@Operator Float modInt(Int b)

Return remainder of this divided by b. Shortcut is a%b.


mult ​

@Operator Float mult(Float b)

Multiply this with b. Shortcut is a*b.


multDecimal ​

@Operator Decimal multDecimal(Decimal b)

Multiply this with b. Shortcut is a*b.


multInt ​

@Operator Float multInt(Int b)

Multiply this with b. Shortcut is a*b.


nan ​

const static Float nan

Float value for Not-A-Number.


negInf ​

const static Float negInf

Float value for negative infinity.


negate ​

@Operator Float negate()

Negative of this. Shortcut is -a.


normNegZero ​

Float normNegZero()

If this value is negative zero then return normalized zero, otherwise return this value.


pi ​

const static Float pi

Float value for pi which is the ratio of the circumference of a circle to its diameter.


plus ​

@Operator Float plus(Float b)

Add this with b. Shortcut is a+b.


plusDecimal ​

@Operator Decimal plusDecimal(Decimal b)

Add this with b. Shortcut is a+b.


plusInt ​

@Operator Float plusInt(Int b)

Add this with b. Shortcut is a+b.


posInf ​

const static Float posInf

Float value for positive infinity.


pow ​

Float pow(Float pow)

Return this value raised to the specified power.


random ​

static Float random()

Generate a random float between 0.0 inclusive and 1.0 exclusive. Also see Int.random, Range.random, List.random, and Random.


round ​

Float round()

Returns the nearest whole number to this number.


sin ​

Float sin()

Return sine of this angle in radians.


sinh ​

Float sinh()

Return hyperbolic sine.


sqrt ​

Float sqrt()

Return square root of this value.


tan ​

Float tan()

Return tangent of this angle in radians.


tanh ​

Float tanh()

Return hyperbolic tangent.


toCode ​

Str toCode()

Get this Float as a Fantom code literal.


toDegrees ​

Float toDegrees()

Convert this angle in radians to an angle in degrees.


toLocale ​

Str toLocale(Str? pattern := null, Locale locale := Locale.cur())

Format this floating point number for the current locale. If pattern is null, then the locale's default pattern is used. Also see Num.localeDecimal, Num.localeGrouping, etc.

The pattern format:

#   optional digit
0   required digit
.   decimal point
,   grouping separator (only last one before decimal matters)

Examples:

12345.786f.toLocale("#,###.0")  =>  12,345.8
7.1234f.toLocale("#.000")       =>  7.123
0.1234f.toLocale("#.000")       =>  .123
0.1234f.toLocale("0.00")        =>  0.12
70.12f.toLocale("0.0000")       =>  70.1200

toRadians ​

Float toRadians()

Convert this angle in degrees to an angle in radians.


toStr ​

virtual override Str toStr()

Get string representation according to the lexical representation defined by Section 3.2.5 of XML Schema Part 2. Representations for infinity and not-a-number are "-INF", "INF", "NaN".


Func ​

class Func : Obj

Func models an executable function. Functions are typed by a formal parameter list and return value (or Void if no return). Functions are typically defined as method slots on a type, but may also be defined via closures.

An immutable function is one proven to be thread safe:

  • Method functions are always immutable - see Method.func
  • Closures which only capture final, const variables are always immutable; toImmutable always returns this
  • Closures which capture non-final or non-const variables are always mutable; toImmutable always throws NotImmutableErr
  • Closures which capture non-final variables which aren't known to be immutable until runtime (such as Obj or List) will return false for isImmutable, but will provide a toImmutable method which attempts to bind to the current variables by calling toImmutable on each one
  • Functions created by Func.bind are immutable if the original function is immutable and every bound argument is immutable

The definition of a final variable is a variable which is never reassigned after it is initialized. Any variable which is reassigned is considered a non-final variable.

See Functions for details.

Methods

arityConvenience for params.size
bindCreate a new function by binding the specified arguments to this function's parameters.
callOptimized convenience for callList for zero to eight parameters.
callListDynamically invoke this function with the specified arguments and return the result.
callOnConvenience for dynamically invoking an instance method with specified target and arguments.
methodReturn the associated method if this function implements a method slot.
paramsGet the formal parameters of the function.
returnsType returned by the function or sys::Void if no return value.
retypeReturn a new function which wraps this function but with a different reflective type signature.

Slot Details ​


arity ​

Int arity()

Convenience for params.size


bind ​

Func bind(Obj?[] args)

Create a new function by binding the specified arguments to this function's parameters. The new function takes the remaining unbound parameters.

The resulting function is immutable if this function is immutable and all the args are immutable.


call ​

virtual R call(A a := null, B b := null, C c := null, D d := null, E e := null, F f := null, G g := null, H h := null)

Optimized convenience for callList for zero to eight parameters.


callList ​

virtual R callList(Obj?[]? args)

Dynamically invoke this function with the specified arguments and return the result. If the function has Void return type, then null is returned. The argument list must match the number and type of required parameters. If this function represents an instance method (not static and not a constructor) then the first argument must be the target object. If the function supports default parameters, omit arguments to use the defaults. It is permissible to pass more arguments then the number of method parameters - the additional arguments are ignored. If no arguments are required, you may pass null for args.


callOn ​

virtual R callOn(Obj? target, Obj?[]? args)

Convenience for dynamically invoking an instance method with specified target and arguments. If this method maps to an instance method, then it is semantically equivalent to callList([target, args[0], args[1] ...]). Throw UnsupportedErr if called on a function which is not an instance method.


method ​

Method? method()

Return the associated method if this function implements a method slot. Otherwise return null.

Examples:

Int#plus.func.method  =>  sys::Int.plus

params ​

Param[] params()

Get the formal parameters of the function.


returns ​

Type returns()

Type returned by the function or sys::Void if no return value.


retype ​

Func retype(Type t)

Return a new function which wraps this function but with a different reflective type signature. No verification is done that this function actually conforms to the new signature. This method implicitly calls Type.toNonNullable on t. Throw ArgErr if t isn't a parameterized function type.

Examples:

f := |a,b->Obj| { "$a, $b" }
g := f.retype(|Int,Int->Str|#)
f.type  =>  |Obj?,Obj?->Obj|
g.type  =>  |Int,Int->Str|

IOErr ​

const class IOErr : Err

IOErr indicates an input/output error typically associated with a file system or socket.

Constructors

makeConstruct 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.


InStream ​

class InStream : Obj

InStream is used to read binary and text stream based input.

Constructors

makeConstructor for an InStream which wraps another stream.

Fields

charsetThe current charset used to decode bytes into Unicode characters.
endianByte order mode for binary reads.

Methods

availReturn the number of bytes available on input stream without blocking.
closeClose the input stream.
eachLineRead the entire stream into Str lines based on the current encoding.
peekPeek at the next byte to be read without actually consuming it.
peekCharPeek at the next char to be read without actually consuming it.
pipePipe bytes from this input stream to the specified output stream.
readRead the next unsigned byte from the input stream.
readAllBufRead the entire contents of the stream into a memory Buf.
readAllLinesRead the entire stream into a list of Str lines based on the configured charset encoding.
readAllStrRead the entire stream into a Str based on the configured charset encoding.
readBitsRead between 0 and 64 bits from the input stream.
readBoolRead the next byte and return true if nonzero.
readBufAttempt to read the next n bytes into the Buf at its current position.
readBufFullyRead the next n bytes from the stream into the Buf at its current position.
readCharRead a single Unicode character from the stream using the current charset encoding.
readCharsRead the next n chars from the stream as a Str using the current charset.
readDecimalRead a decimal string according to readUtf.
readF4Read the next four bytes as a 32-bit floating point number using configured endian according to Float.bits32.
readF8Read the next eight bytes as a 64-bit floating point number using configured endian according to Float.bits.
readLineRead the next line from the input stream as a Str based on the configured charset.
readNullTerminatedStrRead a string terminated by the "\0" character.
readObjRead a serialized object from the stream according to the Fantom serialization format.
readPropsRead the entire stream into a Str:Str of name/value pairs using the Fantom props file format.
readS1Read the next byte as a signed 8-bit number.
readS2Read the next two bytes as a signed 16-bit number using configured endian.
readS4Read the next four bytes as a signed 32-bit number using configured endian.
readS8Read the next eight bytes as a signed 64-bit number using configured endian.
readStrTokenRead a Str token from the input stream which is terminated when the specified function c returns true.
readU1Read the next byte as an unsigned 8-bit number.
readU2Read the next two bytes as an unsigned 16-bit number using configured endian.
readU4Read the next four bytes as an unsigned 32-bit number using configured endian.
readUtfRead a Str in modified UTF-8 format according to the java.io.DataInput specification.
skipAttempt to skip n number of bytes.
unreadPushback a byte so that it is the next byte to be read.
unreadCharPushback a char so that it is the next char to be read.

Slot Details ​


avail ​

virtual Int avail()

Return the number of bytes available on input stream without blocking. Return zero if no bytes available or it is unknown. Throw IOErr on error.


charset ​

Charset charset

The current charset used to decode bytes into Unicode characters. The default charset should always be UTF-8.


close ​

virtual Bool close()

Close the input stream. This method is guaranteed to never throw an IOErr. Return true if the stream was closed successfully or false if the stream was closed abnormally. Default implementation does nothing and returns true.


eachLine ​

Void eachLine(|Str| f)

Read the entire stream into Str lines based on the current encoding. Call the specified function for each line read. Each line is terminated by \n, \r\n, \r, or EOF using the same semantics as readLine with the null default max line length. The Str lines themselves do not contain a trailing newline. Empty lines are returned as the empty Str "". This InStream is guaranteed to be closed upon return.


endian ​

Endian endian

Byte order mode for binary reads. Default is Endian.big (network byte order).


make ​

new make(InStream? in)

Constructor for an InStream which wraps another stream. All reads from this stream will be routed to the specified inner stream.

If in is null, then it is the subclass responsibility to handle reads by overriding the following methods: read, readBuf, and unread.

If in is not null, then this stream will automatically set its own charset to in.charset.


peek ​

Int? peek()

Peek at the next byte to be read without actually consuming it. Peek has the same semantics as a read/unread. Return null if at end of stream.


peekChar ​

Int? peekChar()

Peek at the next char to be read without actually consuming it. Peek has the same semantics as a readChar/unreadChar. Return null if at end of stream.


pipe ​

Int pipe(OutStream out, Int? n := null, Bool close := true)

Pipe bytes from this input stream to the specified output stream. If n is specified, then block until exactly n bytes have been read or throw IOErr if end of stream is reached first. If n is null then the entire contents of this input stream are piped. If close is true, then this input stream is guaranteed to be closed upon return (the OutStream is never closed). Return the number of bytes piped to the output stream.


read ​

virtual Int? read()

Read the next unsigned byte from the input stream. Return null if at end of stream. Throw IOErr on error.


readAllBuf ​

Buf readAllBuf()

Read the entire contents of the stream into a memory Buf. The resulting buffer is automatically positioned at the beginning. This InStream is guaranteed to be closed.


readAllLines ​

Str[] readAllLines()

Read the entire stream into a list of Str lines based on the configured charset encoding. Each Str in the list maps to a line terminated by \n, \r\n, \r, or EOF using the same semantics as readLine with default max line length of null. The Str lines themselves do not contain a trailing newline. Empty lines are returned as the empty Str "". Return an empty list if currently at end of stream (not null). Throw IOErr if there is a problem reading the stream or an invalid character encoding is encountered. This InStream is guaranteed to be closed upon return.


readAllStr ​

Str readAllStr(Bool normalizeNewlines := true)

Read the entire stream into a Str based on the configured charset encoding. If the normalizeNewlines flag is true, then all occurances of \r\n or \r newlines are normalized into \n. Return "" if the stream is empty. Throw IOErr if there is a problem reading the stream or an invalid character encoding is encountered. This InStream is guaranteed to be closed.


readBits ​

Int readBits(Int num)

Read between 0 and 64 bits from the input stream. Bits which are partial bytes are consumed from the input stream one byte at a time. Throw IOErr on error or if end of stream is reached before given number of bits can be read.


readBool ​

Bool readBool()

Read the next byte and return true if nonzero. This method may be paired with OutStream.writeBool. Throw IOErr on error or if the end of stream is reached before one byte can be read.


readBuf ​

virtual Int? readBuf(Buf buf, Int n)

Attempt to read the next n bytes into the Buf at its current position. The buffer will be grown as needed. Return the number of bytes read and increment buf's size and position accordingly. Return null and leave buf's state untouched if end of stream. Note this method may not read the full number of n bytes, use readBufFully if you must block until all n bytes read. Throw IOErr on error.


readBufFully ​

Buf readBufFully(Buf? buf, Int n)

Read the next n bytes from the stream into the Buf at its current position. The buffer will be grown as needed. If the buf parameter is null, then a memory buffer is automatically created with a capacity of n. Block until exactly n bytes have been read or throw IOErr if end of stream is reached first. Return the Buf passed in or the one created automatically if buf is null. The buffer is automatically positioned at zero.


readChar ​

Int? readChar()

Read a single Unicode character from the stream using the current charset encoding. Return null if at end of stream. Throw IOErr if there is a problem reading the stream, or an invalid character encoding is encountered.


readChars ​

Str readChars(Int n)

Read the next n chars from the stream as a Str using the current charset. Block until exactly n chars have been read or throw IOErr if end of stream is reached first.


readDecimal ​

Decimal readDecimal()

Read a decimal string according to readUtf.


readF4 ​

Float readF4()

Read the next four bytes as a 32-bit floating point number using configured endian according to Float.bits32. This method may be paired with OutStream.writeF4. Throw IOErr on error or if the end of stream is reached before four bytes can be read.


readF8 ​

Float readF8()

Read the next eight bytes as a 64-bit floating point number using configured endian according to Float.bits. This method may be paired with OutStream.writeF8. Throw IOErr on error or if the end of stream is reached before four bytes can be read.


readLine ​

Str? readLine(Int? max := null)

Read the next line from the input stream as a Str based on the configured charset. A line is terminated by \n, \r\n, \r, or EOF. The Str returned never contains the trailing newline.

The max parameter specifies the maximum number of Unicode characters (not bytes) to read before truncating the line and returning. If max is null, then no boundary is enforced except of course the end of the stream.

Return null if the end of stream has been reached. Throw IOErr if there is a problem reading the stream or an invalid character encoding is encountered.


readNullTerminatedStr ​

Str readNullTerminatedStr(Int? max := null)

Read a string terminated by the "\0" character. The "\0" character is read from the stream, but not included in the string result.

The max parameter specifies the maximum number of Unicode characters (not bytes) to read before truncating the string and returning. If max is null, then no boundary is enforced except of course the end of the stream.


readObj ​

Obj? readObj([Str:Obj]? options := null)

Read a serialized object from the stream according to the Fantom serialization format. Throw IOErr or ParseErr on error. This method may consume bytes/chars past the end of the serialized object (we may want to add a "full stop" token at some point to support compound object streams).

The options may be used to specify additional decoding logic:

  • "makeArgs": Obj[] arguments to pass to the root object's make constructor via Type.make

readProps ​

Str:Str readProps()

Read the entire stream into a Str:Str of name/value pairs using the Fantom props file format. This format is similar to but different than the Java properties file format:

  • Input must be UTF-8 encoded (current charset is ignored)
  • Name/value pairs formatted as logical line: <name>=<value>
  • Any Unicode character allowed in name or value
  • Leading and trailing whitespace trimmed from both name and value
  • Duplicate name keys within one file is an error condition
  • Lines starting with # are comments
  • Comment to end of line is // if start of line or preceeded by whitespace
  • Block comment is /* */ (may be nested)
  • Use trailing \ to continue logical line to another actual line, any leading whitespace (space or tab char) is trimmed from beginning of continued line
  • Fantom Str literal escape sequences supported: \n \r \t or \uxxxx
  • The $ character is treated as a normal character and should not be escaped, but convention is to indicate a variable in a format string
  • Convention is that name is lower camel case with dot separators

Throw IOErr if there is a problem reading the stream or an invalid props format is encountered. This InStream is guaranteed to be closed.

Also see Env.props.


readS1 ​

Int readS1()

Read the next byte as a signed 8-bit number. This method may be paired with OutStream.write. Throw IOErr on error or if the end of stream is reached before one byte can be read.


readS2 ​

Int readS2()

Read the next two bytes as a signed 16-bit number using configured endian. This method may be paired with OutStream.writeI2. Throw IOErr on error or if the end of stream is reached before two bytes can be read.


readS4 ​

Int readS4()

Read the next four bytes as a signed 32-bit number using configured endian. This method may be paired with OutStream.writeI4. Throw IOErr on error or if the end of stream is reached before four bytes can be read.


readS8 ​

Int readS8()

Read the next eight bytes as a signed 64-bit number using configured endian. This method may be paired with OutStream.writeI8. Throw IOErr on error or if the end of stream is reached before eight bytes can be read. Note there is no readU8 (because Java doesn't support unsigned longs).


readStrToken ​

Str? readStrToken(Int? max := null, |Int->Bool|? c := null)

Read a Str token from the input stream which is terminated when the specified function c returns true. The terminating char is unread and will be the next char read once this method returns. Characters are read based on the currently configured charset.

If c is null then the default implementation tokenizes up until the next character which returns true for Int.isSpace.

The max parameter specifies the maximum number of Unicode characters (not bytes) to read before truncating the line and returning. If max is null, then no boundary is enforced except of course the end of the stream.

Return null if the end of stream has been reached. Throw IOErr if there is a problem reading the stream or an invalid character encoding is encountered.


readU1 ​

Int readU1()

Read the next byte as an unsigned 8-bit number. This method may be paired with OutStream.write. Throw IOErr on error or if the end of stream is reached before one byte can be read. This method differs from read in that it will throw IOErr on end of stream rather than return null.


readU2 ​

Int readU2()

Read the next two bytes as an unsigned 16-bit number using configured endian. This method may be paired with OutStream.writeI2. Throw IOErr on error or if the end of stream is reached before two bytes can be read.


readU4 ​

Int readU4()

Read the next four bytes as an unsigned 32-bit number using configured endian. This method may be paired with OutStream.writeI4. Throw IOErr on error or if the end of stream is reached before four bytes can be read.


readUtf ​

Str readUtf()

Read a Str in modified UTF-8 format according to the java.io.DataInput specification. This method may be paired with OutStream.writeUtf. Throw IOErr on error, invalid UTF encoding, or if the end of stream is reached before the string is fully read.


skip ​

virtual Int skip(Int n)

Attempt to skip n number of bytes. Return the number of bytes actually skipped which may be equal to or less than n.


unread ​

virtual This unread(Int b)

Pushback a byte so that it is the next byte to be read. There is a finite limit to the number of bytes which may be pushed back. Return this.


unreadChar ​

This unreadChar(Int b)

Pushback a char so that it is the next char to be read. This method pushes back one or more bytes depending on the current character encoding. Return this.


IndexErr ​

const class IndexErr : Err

IndexErr indicates an attempt to access an invalid index in a List.

Constructors

makeConstruct 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.


Int ​

@Serializable { simple=true } const class Int : Num

Int is used to represent a signed 64-bit integer.

Constructors

fromStrParse a Str into a Int using the specified radix.

Fields

defValDefault value is zero.
maxValMaximum value which can be stored in a signed 64-bit Int: 9,223,372,036,854,775,807
minValMinimum value which can be stored in a signed 64-bit Int: -9,223,372,036,854,775,808

Methods

absReturn the absolute value of this integer.
andBitwise-and of this and b.
clampClamp this integer between the min and max.
compareCompare based on integer value.
decrementDecrement by one.
divDivide this by b.
divDecimalDivide this by b.
divFloatDivide this by b.
equalsReturn true if same integer value.
equalsIgnoreCaseReturn if the two Unicode chars are equal without regard to ASCII case.
fromDigitConvert a Unicode digit character into a number for the specified radix.
hashReturn this.
incrementIncrement by one.
isAlphaReturn if this Unicode char is an ASCII alpha char: isUpper
isAlphaNumReturn if this Unicode char is an ASCII alpha-numeric char: isAlpha
isDigitReturn if this Unicode char is a digit in the specified radix.
isEvenReturn if this integer is evenly divisible by two.
isLowerReturn if this Unicode char is an ASCII lowercase alphabetic char: a-z
isOddReturn if this integer is not evenly divisible by two.
isSpaceReturn if this Unicode char is whitespace: space \t \n \r \f
isUpperReturn if this Unicode char is an ASCII uppercase alphabetic char: A-Z
localeIsLowerReturn if this Unicode char is a lowercase letter in the current locale.
localeIsUpperReturn if this Unicode char is an uppercase letter in the current locale.
localeLowerIf this Unicode char is an uppercase char, then return it as lowercase according to the current locale.
localeUpperIf this Unicode char is a lowercase char, then return it as uppercase according to the current locale.
lowerIf this Unicode char is an ASCII uppercase char, then return it as lowercase, otherwise return this.
maxReturn the larger of this and the specified Int values.
minReturn the smaller of this and the specified Int values.
minusSubtract b from this.
minusDecimalSubtract b from this.
minusFloatSubtract b from this.
modReturn remainder of this divided by b.
modDecimalReturn remainder of this divided by b.
modFloatReturn remainder of this divided by b.
multMultiply this with b.
multDecimalMultiply this with b.
multFloatMultiply this with b.
negateNegative of this.
notBitwise not/inverse of this.
orBitwise-or of this and b.
plusAdd this with b.
plusDecimalAdd this with b.
plusFloatAdd this with b.
powReturn this value raised to the specified power.
randomGenerate a random number.
shiftaBitwise arithmetic right-shift of this by b.
shiftlBitwise left shift of this by b.
shiftrBitwise right shift of this by b.
timesCall the specified function to this times passing the current counter.
toCharMap as a Unicode code point to a single character Str.
toCodeGet this Int as a Fantom code literal.
toDateTimeConvert nano-seconds ticks since 1-Jan-2000 to a DateTime.
toDigitConvert this number into a Unicode char 0-'9'.
toDurationConvert nano-seconds ticks to a Duration.
toHexReturn hexdecimal string representation.
toLocaleFormat this integer number for the current locale.
toRadixReturn string representation in given radix.
toStrReturn decimal string representation.
upperIf this Unicode char is an ASCII lowercase char, then return it as uppercase, otherwise return this.
xorBitwise-exclusive-or of this and b.

Slot Details ​


abs ​

Int abs()

Return the absolute value of this integer. If this value is positive then return this, otherwise return the negation.


and ​

Int and(Int b)

Bitwise-and of this and b.


clamp ​

Int clamp(Int min, Int max)

Clamp this integer between the min and max. If it's less than min then return min, if it's greater than max return max, otherwise return this integer itself.


compare ​

virtual override Int compare(Obj obj)

Compare based on integer value.


decrement ​

@Operator Int decrement()

Decrement by one. Shortcut is --a or a--.


defVal ​

const static Int defVal

Default value is zero.


div ​

@Operator Int div(Int b)

Divide this by b. Shortcut is a/b.


divDecimal ​

@Operator Decimal divDecimal(Decimal b)

Divide this by b. Shortcut is a/b.


divFloat ​

@Operator Float divFloat(Float b)

Divide this by b. Shortcut is a/b.


equals ​

virtual override Bool equals(Obj? obj)

Return true if same integer value.


equalsIgnoreCase ​

Bool equalsIgnoreCase(Int ch)

Return if the two Unicode chars are equal without regard to ASCII case.


fromDigit ​

Int? fromDigit(Int radix := 10)

Convert a Unicode digit character into a number for the specified radix. Return null if this char is not a valid digit.

Example:

'3'.fromDigit     => 3
'f'.fromDigit(16) => 15
'%'.fromDigit     => null

fromStr ​

static new fromStr(Str s, Int radix := 10, Bool checked := true)

Parse a Str into a Int using the specified radix. Unless the radix is 10, then a leading minus sign is illegal. If invalid format and checked is false return null, otherwise throw ParseErr.


hash ​

virtual override Int hash()

Return this.


increment ​

@Operator Int increment()

Increment by one. Shortcut is ++a or a++.


isAlpha ​

Bool isAlpha()

Return if this Unicode char is an ASCII alpha char: isUpper||isLower


isAlphaNum ​

Bool isAlphaNum()

Return if this Unicode char is an ASCII alpha-numeric char: isAlpha||isDigit


isDigit ​

Bool isDigit(Int radix := 10)

Return if this Unicode char is a digit in the specified radix. A decimal radix of ten returns true for 0-9. A radix of 16 also returns true for a-f and A-F.

Example:

'3'.toDigit     => true
3.toDigit       => false
'B'.toDigit(16) => true

isEven ​

Bool isEven()

Return if this integer is evenly divisible by two.


isLower ​

Bool isLower()

Return if this Unicode char is an ASCII lowercase alphabetic char: a-z


isOdd ​

Bool isOdd()

Return if this integer is not evenly divisible by two.


isSpace ​

Bool isSpace()

Return if this Unicode char is whitespace: space \t \n \r \f


isUpper ​

Bool isUpper()

Return if this Unicode char is an ASCII uppercase alphabetic char: A-Z


localeIsLower ​

Bool localeIsLower()

Return if this Unicode char is a lowercase letter in the current locale. See also localeIsUpper and isLower.


localeIsUpper ​

Bool localeIsUpper()

Return if this Unicode char is an uppercase letter in the current locale. See also localeIsLower and isUpper.


localeLower ​

Int localeLower()

If this Unicode char is an uppercase char, then return it as lowercase according to the current locale. Note that Unicode contains some case conversion rules that don't work correctly on a single character, so Str.localeLower should be preferred. See also localeUpper and lower.


localeUpper ​

Int localeUpper()

If this Unicode char is a lowercase char, then return it as uppercase according to the current locale. Note that Unicode contains some case conversion rules that don't work correctly on a single character, so Str.localeUpper should be preferred. See also localeLower and upper.


lower ​

Int lower()

If this Unicode char is an ASCII uppercase char, then return it as lowercase, otherwise return this.

Example:

'A'.lower => 'a'
'h'.lower => 'h'

max ​

Int max(Int that)

Return the larger of this and the specified Int values.


maxVal ​

const static Int maxVal

Maximum value which can be stored in a signed 64-bit Int: 9,223,372,036,854,775,807


min ​

Int min(Int that)

Return the smaller of this and the specified Int values.


minVal ​

const static Int minVal

Minimum value which can be stored in a signed 64-bit Int: -9,223,372,036,854,775,808


minus ​

@Operator Int minus(Int b)

Subtract b from this. Shortcut is a-b.


minusDecimal ​

@Operator Decimal minusDecimal(Decimal b)

Subtract b from this. Shortcut is a-b.


minusFloat ​

@Operator Float minusFloat(Float b)

Subtract b from this. Shortcut is a-b.


mod ​

@Operator Int mod(Int b)

Return remainder of this divided by b. Shortcut is a%b.


modDecimal ​

@Operator Decimal modDecimal(Decimal b)

Return remainder of this divided by b. Shortcut is a%b.


modFloat ​

@Operator Float modFloat(Float b)

Return remainder of this divided by b. Shortcut is a%b.


mult ​

@Operator Int mult(Int b)

Multiply this with b. Shortcut is a*b.


multDecimal ​

@Operator Decimal multDecimal(Decimal b)

Multiply this with b. Shortcut is a*b.


multFloat ​

@Operator Float multFloat(Float b)

Multiply this with b. Shortcut is a*b.


negate ​

@Operator Int negate()

Negative of this. Shortcut is -a.


not ​

Int not()

Bitwise not/inverse of this.


or ​

Int or(Int b)

Bitwise-or of this and b.


plus ​

@Operator Int plus(Int b)

Add this with b. Shortcut is a+b.


plusDecimal ​

@Operator Decimal plusDecimal(Decimal b)

Add this with b. Shortcut is a+b.


plusFloat ​

@Operator Float plusFloat(Float b)

Add this with b. Shortcut is a+b.


pow ​

Int pow(Int pow)

Return this value raised to the specified power. Throw ArgErr if pow is less than zero.


random ​

static Int random(Range? r := null)

Generate a random number. If range is null then all 2^64 integer values (both negative and positive) are produced with equal probability. If range is non-null, then the result is guaranteed to be inclusive of the range. Also see Float.random , Range.random , List.random , and Random.

Examples:

r := Int.random
r := Int.random(0..100)

shifta ​

Int shifta(Int b)

Bitwise arithmetic right-shift of this by b. The left-most bit is shifted into the highest bits performing like a signed shift. This is equivalent to the Java >> operator.


shiftl ​

Int shiftl(Int b)

Bitwise left shift of this by b.


shiftr ​

Int shiftr(Int b)

Bitwise right shift of this by b. Zero is shifted into the highest bits performing like an unsigned shift. This is equivalent to the Java >>> operator.


times ​

Void times(|Int| c)

Call the specified function to this times passing the current counter. The counter begins at zero. Also see Range.each.

Example:

3.times |i| { echo(i) }  =>  0, 1, 2

toChar ​

Str toChar()

Map as a Unicode code point to a single character Str.


toCode ​

Str toCode(Int base := 10)

Get this Int as a Fantom code literal. Base must be 10 or 16.


toDateTime ​

DateTime toDateTime(TimeZone tz := TimeZone.cur())

Convert nano-seconds ticks since 1-Jan-2000 to a DateTime. Convenience for DateTime.makeTicks.


toDigit ​

Int? toDigit(Int radix := 10)

Convert this number into a Unicode char 0-'9'. If radix is greater than 10, then use a lower case letter. Return null if this number cannot be represented as a single digit character for the specified radix.

Example:

3.toDigit      => '3'
15.toDigit(16) => 'f'
99.toDigit     => null

toDuration ​

Duration toDuration()

Convert nano-seconds ticks to a Duration. Convenience for Duration.make.


toHex ​

Str toHex(Int? width := null)

Return hexdecimal string representation. If width is non-null, then leading zeros are prepended to ensure the specified number of nibble characters.

Examples:

255.toHex     =>  "ff"
255.toHex(4)  =>  "00ff"

toLocale ​

Str toLocale(Str? pattern := null, Locale locale := Locale.cur())

Format this integer number for the current locale. If pattern is null, then the locale's default pattern is used. See Float.toLocale for pattern language. Fractional formatting is not supported for integers.

In addition Int.toLocale supports the "B" pattern which will format a number of bytes with the appropriate B, KB, MB, GB suffix based on the magnitude (1024B == 1KB).

Examples:

3.toLocale("00")             =>  03
3.toLocale("000")            =>  003
123456789.toLocale("#,###")  =>  123,456,789
123.toLocale("B")            =>  123B
1234.toLocale("B")           =>  1.2KB
100_000.toLocale("B")        =>  98KB
(3*1024*1024).toLocale("B")  =>  3MB

toRadix ​

Str toRadix(Int radix, Int? width := null)

Return string representation in given radix. If width is non-null, then leading zeros are prepended to ensure the specified width.

Examples:

255.toRadix(8)    =>  "377"
255.toRadix(8, 5) =>  "00377"

toStr ​

virtual override Str toStr()

Return decimal string representation.


upper ​

Int upper()

If this Unicode char is an ASCII lowercase char, then return it as uppercase, otherwise return this.

Example:

'a'.upper => 'A'
'4'.upper => '4'

xor ​

Int xor(Int b)

Bitwise-exclusive-or of this and b.


InterruptedErr ​

const class InterruptedErr : Err

InterruptedErr indicates that a thread is interrupted from its normal execution.

Constructors

makeConstruct 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.


Js ​

facet class Js : Obj, Facet

Used to annoate types which should be compiled into JavaScript.

Fields

defValSingleton for Js facet.

Slot Details ​


defVal ​

const static Js defVal := ...

Singleton for Js facet.


List ​

@Serializable class List : Obj

List represents a linear sequence of Objects indexed by an Int.

See examples.

Constructors

makeConstructor for of[] with initial capacity.
makeObjConstructor for Obj?[] with initial capacity.

Fields

capacityThe number of items this list can hold without allocating more memory.
sizeThe number of items in the list.

Methods

addAdd the specified item to the end of the list.
addAllAdd all the items in the specified list to the end of this list.
addIfNotNullDeprecated - use addNotNull
addNotNullCall add if item is non-null otherwise do nothing.
allReturn true if c returns true for all of the items in the list.
anyReturn true if c returns true for any of the items in the list.
binaryFindFind an element in the list using a binary search algorithm.
binarySearchSearch the list for the index of the specified key using a binary search algorithm.
clearRemove all items from the list and set size to 0.
containsReturn if this list contains the specified item.
containsAllReturn if this list contains every item in the specified list.
containsAnyReturn if this list contains any one of the items in the specified list.
containsSameReturn if this list contains the specified item.
dupCreate a shallow duplicate copy of this List.
eachCall the specified function for every item in the list starting with index 0 and incrementing up to size-1.
eachNotNullCall the specified function for every non-null item in the list starting with index 0 and incrementing up to size-1.
eachRangeIterate the list using the specified range.
eachWhileIterate every item in the list starting with index 0 up to size-1 until the function returns non-null.
eachrReverse each - call the specified function for every item in the list starting with index size-1 and decrementing down to 0.
eachrWhileReverse eachWhile.
equalsTwo Lists are equal if they have the same type, the same number of items, and all the items at each index return true for equals.
excludeReturn a new list containing the items for which c returns false.
fillAppend a value to the end of the list the given number of times.
findReturn the first item in the list for which c returns true.
findAllReturn a new list containing the items for which c returns true.
findIndexReturn the index of the first item in the list for which c returns true.
findNotNullReturn a new list with all null items removed.
findTypeReturn a new list containing all the items which are an instance of the specified type such that item.type.fits(t) is true.
firstReturn the item at index 0, or if empty return null.
flatMapThis is a combination of map and flatten.
flattenReturn a new list which recursively flattens any list items into a one-dimensional result.
getGet is used to return the item at the specified index.
getRangeReturn a sub-list based on the specified range.
getSafeGet the item at the specified index, but if index is out of range, then return def parameter.
groupByGroup items into buckets keyed by the given function.
groupByIntoGroup by into an existing map.
hashReturn platform dependent hashcode based on a hash of the items of the list.
indexReturn the integer index of the specified item using the == operator (shortcut for equals method) to check for equality.
indexSameReturn integer index just like List.index except use === same operator instead of the == equals operator.
indexrReverse index lookup.
insertInsert the item at the specified index.
insertAllInsert all the items in the specified list into this list at the specified index.
intersectionReturn a new list which is the intersection of this list and the given list.
isEmptyReturn if size == 0.
isROReturn if this List is readonly.
isRWReturn if this List is read-write.
joinReturn a string by concatenating each item's toStr result using the specified separator string.
lastReturn the item at size-1, or if empty return null.
mapCreate a new list which is the result of calling c for every item in this list.
mapNotNullConvenience for map and findNotNull.
maxReturn the maximum value of the list.
minReturn the minimum value of the list.
moveToFind the given item, and move it to the given index.
ofGet the item Type of this List.
peekReturn the item at size-1, or if empty return null.
popRemove the last item and return it, or return null if the list is empty.
pushAdd the specified item to the end of the list.
randomReturn a random item from the list.
reduceReduce is used to iterate through every item in the list to reduce the list into a single value called the reduction.
removeRemove the specified value from the list.
removeAllRemove every item in this list which is found in the toRemove list using same semantics as remove (compare for equality via the == operator).
removeAtRemove the object at the specified index.
removeRangeRemove a range of indices from this list.
removeSameRemove the item just like remove except use the === operator instead of the == equals operator.
reverseReverse the order of the items of this list in-place.
roGet a readonly List instance with the same contents as this List (although the items may be mutable themselves).
rwGet a read-write, mutable List instance with the same contents as this List.
setSet is used to overwrite the item at the specified index.
setNotNullCall set if item is non-null otherwise do nothing.
shuffleShuffle this list's items into a randomized order.
sortPerform an in-place sort on this list.
sortrReverse sort - perform an in-place reverse sort on this list.
swapSwap the items at the two specified indexes.
toCodeGet this list as a Fantom expression suitable for code generation.
toStrReturn a string representation of the list.
trimTrim the capacity such that the underlying storage is optimized for the current size.
unionReturn a new list which is the union of this list and the given list.
uniqueReturns a new list with all duplicate items removed such that the resulting list is a proper set.

Slot Details ​


add ​

@Operator L add(V item)

Add the specified item to the end of the list. The item will have an index of size. Size is incremented by 1. Return this. Throw ReadonlyErr if readonly.


addAll ​

L addAll(L list)

Add all the items in the specified list to the end of this list. Size is incremented by list.size. Return this. Throw ReadonlyErr if readonly.


addIfNotNull ​

@Deprecated { msg="Use addNotNull" } L addIfNotNull(V? item)

Deprecated - use addNotNull


addNotNull ​

L addNotNull(V? item)

Call add if item is non-null otherwise do nothing. Return this.


all ​

Bool all(|V,Int->Bool| c)

Return true if c returns true for all of the items in the list. If the list is empty, return true. This method is readonly safe.

Example:

list := ["ant", "bear"]
list.all |Str v->Bool| { return v.size >= 3 } => true
list.all |Str v->Bool| { return v.size >= 4 } => false

any ​

Bool any(|V,Int->Bool| c)

Return true if c returns true for any of the items in the list. If the list is empty, return false. This method is readonly safe.

Example:

list := ["ant", "bear"]
list.any |Str v->Bool| { return v.size >= 4 } => true
list.any |Str v->Bool| { return v.size >= 5 } => false

binaryFind ​

Int binaryFind(|V,Int->Int| c)

Find an element in the list using a binary search algorithm. The specified comparator function returns a negative integer, zero, or a positive integer if the desired object is less than, equal to, or greater than specified item. The list must be sorted in ascending order according to the specified comparator function. If the key is not found, then return a negative value which is -(insertation point) - 1.

Example:

[1,3,5,7,9].binaryFind |Int item->Int| { return 4 <=> item }
            => -3
[1,3,5,7,9].binaryFind |Int item->Int| { return 3 <=> item }
            => 1

binarySearch ​

Int binarySearch(V key, |V,V->Int|? c := null)

Search the list for the index of the specified key using a binary search algorithm. The list must be sorted in ascending order according to the specified comparator function. If the list contains multiple matches for key, no guarantee is made to which one is returned. If the comparator is null then it is assumed to be the <=> operator (shortcut for the compare method). If the key is not found, then return a negative value which is -(insertation point) - 1.

Example:

[1,3,5,7,9].binarySearch(4)  => -3
[1,3,5,7,9].binarySearch(3)  => 1

capacity ​

Int capacity

The number of items this list can hold without allocating more memory. Capacity is always greater or equal to size. If adding a large number of items, it may be more efficient to manually set capacity. See the trim method to automatically set capacity to size. Throw ArgErr if attempting to set capacity less than size. Getting capacity is readonly safe, setting capacity throws ReadonlyErr if readonly.


clear ​

L clear()

Remove all items from the list and set size to 0. Return this. Throw ReadonlyErr if readonly.


contains ​

Bool contains(V item)

Return if this list contains the specified item. Equality is determined by Obj.equals. This method is readonly safe.


containsAll ​

Bool containsAll(L list)

Return if this list contains every item in the specified list. Equality is determined by Obj.equals. This method is readonly safe.


containsAny ​

Bool containsAny(L list)

Return if this list contains any one of the items in the specified list. Equality is determined by Obj.equals. This method is readonly safe.


containsSame ​

Bool containsSame(V item)

Return if this list contains the specified item. Equality is determined by ===. This method is readonly safe.


dup ​

L dup()

Create a shallow duplicate copy of this List. The items themselves are not duplicated. The resulting list is always read/write. This method is readonly safe.


each ​

Void each(|V,Int| c)

Call the specified function for every item in the list starting with index 0 and incrementing up to size-1. This method is readonly safe.

Example:

["a", "b", "c"].each |Str s| { echo(s) }
=> a
   b
   c

eachNotNull ​

Void eachNotNull(|V,Int| c)

Call the specified function for every non-null item in the list starting with index 0 and incrementing up to size-1. This method is readonly safe.


eachRange ​

Void eachRange(Range r, |V,Int| c)

Iterate the list using the specified range. Negative indexes may be used to access from the end of the list. This method is readonly safe. Throw IndexErr if range is invalid.


eachWhile ​

Obj? eachWhile(|V,Int->Obj?| c)

Iterate every item in the list starting with index 0 up to size-1 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. This method is readonly safe.


eachr ​

Void eachr(|V,Int| c)

Reverse each - call the specified function for every item in the list starting with index size-1 and decrementing down to 0. This method is readonly safe.

Example:

["a", "b", "c"].eachr |Str s| { echo(s) }
=> c
   b
   a

eachrWhile ​

Obj? eachrWhile(|V,Int->Obj?| c)

Reverse eachWhile. Iterate every item in the list starting with size-1 down to 0. If the function returns non-null, then break the iteration and return the resulting object. Return null if the function returns null for every item. This method is readonly safe.


equals ​

virtual override Bool equals(Obj? that)

Two Lists are equal if they have the same type, the same number of items, and all the items at each index return true for equals.

Examples:

[2, 3] == [2, 3]     =>  true
[2, 3] == [3, 2]     =>  false
[2, 3] == Num[2, 3]  =>  false
Str[,] == [,]        =>  false
Str[,] == Str?[,]    =>  false

exclude ​

L exclude(|V,Int->Bool| c)

Return a new list containing the items for which c returns false. If c returns true for every item, then return an empty list. The inverse of this method is findAll(). This method is readonly safe.

Example:

list := [0, 1, 2, 3, 4]
list.exclude |Int v->Bool| { return v%2==0 } => [1, 3]

fill ​

L fill(V val, Int times)

Append a value to the end of the list the given number of times. Return this. Throw ReadonlyErr if readonly.

Example:

Int[,].fill(0, 3)  =>  [0, 0, 0]

find ​

V? find(|V,Int->Bool| c)

Return the first item in the list for which c returns true. If c returns false for every item, then return null. This method is readonly safe.

Example:

list := [0, 1, 2, 3, 4]
list.find |Int v->Bool| { return v.toStr == "3" } => 3
list.find |Int v->Bool| { return v.toStr == "7" } => null

findAll ​

L findAll(|V,Int->Bool| c)

Return a new list containing the items for which c returns true. If c returns false for every item, then return an empty list. The inverse of this method is exclude(). This method is readonly safe.

Example:

list := [0, 1, 2, 3, 4]
list.findAll |Int v->Bool| { return v%2==0 } => [0, 2, 4]

findIndex ​

Int? findIndex(|V,Int->Bool| c)

Return the index of the first item in the list for which c returns true. If c returns false for every item, then return null. This method is readonly safe.

Example:

list := [5, 6, 7]
list.findIndex |Int v->Bool| { return v.toStr == "7" } => 2
list.findIndex |Int v->Bool| { return v.toStr == "9" } => null

findNotNull ​

L findNotNull()

Return a new list with all null items removed. The returned list will be based on this list's type but non-nullable. This method is readonly safe.

Example:

list := Int?[1, null, 2, null, 3]
list.findNotNull => Int[1, 2, 3]

findType ​

L findType(Type t)

Return a new list containing all the items which are an instance of the specified type such that item.type.fits(t) is true. Any null items are automatically excluded. If none of the items is an instance of the specified type, then an empty list is returned. The returned list will be a list of t. This method is readonly safe.

Example:

list := ["a", 3, "foo", 5sec, null]
list.findType(Str#) => Str["a", "foo"]

first ​

V? first()

Return the item at index 0, or if empty return null. This method is readonly safe.


flatMap ​

Obj?[] flatMap(|V,Int->Obj?[]| c)

This is a combination of map and flatten. Each item in this list is mapped to zero or more new items by the given function and the results are returned in a single flattened list. Note unlike flatten only one level of flattening is performed. The new list is typed based on the return type of c. This method is readonly safe.

Example:

list := ["a", "b"]
list.flatMap |v->Str[]| { [v, v.upper] } => ["a", "A", "b", "B"]

flatten ​

Obj?[] flatten()

Return a new list which recursively flattens any list items into a one-dimensional result. This method is readonly safe.

Examples:

[1,2,3].flatten        =>  [1,2,3]
[[1,2],[3]].flatten    =>  [1,2,3]
[1,[2,[3]],4].flatten  =>  [1,2,3,4]

get ​

@Operator V get(Int index)

Get is used to return the item at the specified index. A negative index may be used to access an index from the end of the list. For example get(-1) is translated into get(size()-1). The get method is accessed via the [] shortcut operator. Throw IndexErr if index is out of range. This method is readonly safe.


getRange ​

@Operator L getRange(Range range)

Return a sub-list based on the specified range. Negative indexes may be used to access from the end of the list. This method is accessed via the [] operator. This method is readonly safe. Throw IndexErr if range illegal.

Examples:

list := [0, 1, 2, 3]
list[0..2]   => [0, 1, 2]
list[3..3]   => [3]
list[-2..-1] => [2, 3]
list[0..<2]  => [0, 1]
list[1..-2]  => [1, 2]

getSafe ​

V? getSafe(Int index, V? def := null)

Get the item at the specified index, but if index is out of range, then return def parameter. A negative index may be used according to the same semantics as get. This method is readonly safe.


groupBy ​

Obj:L groupBy(|V,Int->Obj| c)

Group items into buckets keyed by the given function. The result is a map of lists where the map keys are generated by the given function. The map values are the items which share the same key. The resulting map key type is determined by the return type of c.

Example:

// group by string size
list := ["ape", "bear", "cat", "deer"]
list.groupBy |s->Int| { s.size }  =>  [3:[ape, cat], 4:[bear, deer]]

groupByInto ​

Obj:L groupByInto(Obj:L map, |V,Int->Obj| c)

Group by into an existing map. This method shares the same semantics as groupBy except it adds into the given map.


hash ​

virtual override Int hash()

Return platform dependent hashcode based on a hash of the items of the list.


index ​

Int? index(V item, Int offset := 0)

Return the integer index of the specified item using the == operator (shortcut for equals method) to check for equality. Use indexSame to find with === operator. The search starts at the specified offset and returns the first match. The offset may be negative to access from end of list. Throw IndexErr if offset is out of range. If the item is not found return null. This method is readonly safe.


indexSame ​

Int? indexSame(V item, Int offset := 0)

Return integer index just like List.index except use === same operator instead of the == equals operator.


indexr ​

Int? indexr(V item, Int offset := -1)

Reverse index lookup. This method works just like index except that it searches backward from the starting offset.


insert ​

L insert(Int index, V item)

Insert the item at the specified index. A negative index may be used to access an index from the end of the list. Size is incremented by 1. Return this. Throw IndexErr if index is out of range. Throw ReadonlyErr if readonly.


insertAll ​

L insertAll(Int index, L list)

Insert all the items in the specified list into this list at the specified index. A negative index may be used to access an index from the end of the list. Size is incremented by list.size. Return this. Throw IndexErr if index is out of range. Throw ReadonlyErr if readonly.


intersection ​

L intersection(L that)

Return a new list which is the intersection of this list and the given list. The intersection is defined as the unique items which are in both lists. The new list will be ordered according to this list's order. The new list is guaranteed to be unique with no duplicate values. Equality is determined using hash() and the == operator (shortcut for equals method). This method is readonly safe.

Example:

[0, 1, 2, 3].intersection([5, 3, 1]) => [1, 3]
[0, null, 2].intersection([null, 0, 1, 2, 3]) => [0, null, 2]

isEmpty ​

Bool isEmpty()

Return if size == 0. This method is readonly safe.


isRO ​

Bool isRO()

Return if this List is readonly. A readonly List is guaranteed to be immutable (although its items may be mutable themselves). Any attempt to modify a readonly List will result in ReadonlyErr. Use rw to get a read-write List from a readonly List. Methods documented as "readonly safe" may be used safely with a readonly List. This method is readonly safe.


isRW ​

Bool isRW()

Return if this List is read-write. A read-write List is mutable and may be modified. Use ro to get a readonly List from a read-write List. This method is readonly safe.


join ​

Str join(Str separator := "", |V,Int->Str|? c := null)

Return a string by concatenating each item's toStr result using the specified separator string. If c is non-null then it is used to format each item into a string, otherwise Obj.toStr is used. This method is readonly safe.

Example:

["a", "b", "c"].join => "abc"
["a", "b", "c"].join("-") => "a-b-c"
["a", "b", "c"].join("-") |Str s->Str| { return "($s)" } => "(a)-(b)-(c)"

last ​

V? last()

Return the item at size-1, or if empty return null. This method is readonly safe.


make ​

new make(Type of, Int capacity := 0)

Constructor for of[] with initial capacity.


makeObj ​

new makeObj(Int capacity)

Constructor for Obj?[] with initial capacity.


map ​

Obj?[] map(|V,Int->Obj?| c)

Create a new list which is the result of calling c for every item in this list. The new list is typed based on the return type of c. This method is readonly safe.

Example:

list := [3, 4, 5]
list.map |Int v->Int| { return v*2 } => [6, 8, 10]

mapNotNull ​

Obj[] mapNotNull(|V,Int->Obj?| c)

Convenience for map and findNotNull. Each item is mapped by the given function and if null is returned it is excluded from the result. The resulting type is based on the return type of c but non-nullable. This method is readonly safe.

Example:

list := [3, 4, 5]
list.mapIfNotNull |Int v->Int?| { v.isOdd ? 10+v : null } => [13, 15]

max ​

V? max(|V,V->Int|? c := null)

Return the maximum value of the list. If c is provided, then it implements the comparator returning -1, 0, or 1. If c is null then the <=> operator is used (shortcut for compare method). If the list is empty, return null. This method is readonly safe.

Example:

list := ["albatross", "dog", "horse"]
list.max => "horse"
list.max |Str a, Str b->Int| { return a.size <=> b.size } => "albatross"

min ​

V? min(|V,V->Int|? c := null)

Return the minimum value of the list. If c is provided, then it implements the comparator returning -1, 0, or 1. If c is null then the <=> operator is used (shortcut for compare method). If the list is empty, return null. This method is readonly safe.

Example:

list := ["albatross", "dog", "horse"]
list.min => "albatross"
list.min |Str a, Str b->Int| { return a.size <=> b.size } => "dog"

moveTo ​

L moveTo(V? item, Int toIndex)

Find the given item, and move it to the given index. All the other items are shifted accordingly. Negative indexes may used to access an index from the end of the list. If the item is null or not found then this is a no op. Return this. Throw ReadonlyErr if readonly.

Examples:

[10, 11, 12].moveTo(11, 0)  =>  [11, 10, 12]
[10, 11, 12].moveTo(11, -1) =>  [10, 12, 11]

of ​

Type of()

Get the item Type of this List.

Examples:

["hi"].of    =>  Str#
[[2, 3]].of  =>  Int[]#

peek ​

V? peek()

Return the item at size-1, or if empty return null. This method has the same semantics as last(). This method is readonly safe.


pop ​

V? pop()

Remove the last item and return it, or return null if the list is empty. This method has the same semantics as removeAt(-1), with the exception that an empty list is handled. Throw ReadonlyErr if readonly.


push ​

L push(V item)

Add the specified item to the end of the list. Return this. This method has the same semantics as add(item). Throw ReadonlyErr if readonly.


random ​

V? random()

Return a random item from the list. If the list is empty return null. This method is readonly safe. Also see Int.random, Float.random, Range.random, and Random.


reduce ​

Obj? reduce(Obj? init, |Obj?,V,Int->Obj?| c)

Reduce is used to iterate through every item in the list to reduce the list into a single value called the reduction. The initial value of the reduction is passed in as the init parameter, then passed back to the closure along with each item. This method is readonly safe.

Example:

list := [1, 2, 3]
list.reduce(0) |Obj r, Int v->Obj| { return (Int)r + v } => 6

remove ​

V? remove(V item)

Remove the specified value from the list. The value is compared using the == operator (shortcut for equals method). Use removeSame to remove with the === operator. Return the removed value and decrement size by 1. If the value is not found, then return null. Throw ReadonlyErr if readonly.


removeAll ​

L removeAll(L list)

Remove every item in this list which is found in the toRemove list using same semantics as remove (compare for equality via the == operator). If any value is not found, it is ignored. Return this. Throw ReadonlyErr if readonly.


removeAt ​

V removeAt(Int index)

Remove the object 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 the item removed. Throw IndexErr if index is out of range. Throw ReadonlyErr if readonly.


removeRange ​

L removeRange(Range r)

Remove a range of indices from this list. Negative indexes may be used to access from the end of the list. Throw ReadonlyErr if readonly. Throw IndexErr if range illegal. Return this (*not* the removed items).


removeSame ​

V? removeSame(V item)

Remove the item just like remove except use the === operator instead of the == equals operator.


reverse ​

L reverse()

Reverse the order of the items of this list in-place. Return this. Throw ReadonlyErr if readonly.

Example:

[1, 2, 3, 4].reverse  =>  [4, 3, 2, 1]

ro ​

L ro()

Get a readonly List instance with the same contents as this List (although the items may be mutable themselves). If this List is already readonly, then return this. Only methods documented as "readonly safe" may be used safely with a readonly List, all others will throw ReadonlyErr. This method is readonly safe. See Obj.isImmutable and Obj.toImmutable for deep immutability.


rw ​

L rw()

Get a read-write, mutable List instance with the same contents as this List. If this List is already read-write, then return this. This method is readonly safe.


set ​

@Operator L set(Int index, V item)

Set is used to overwrite the item at the specified index. A negative index may be used to access an index from the end of the list. The set method is accessed via the []= shortcut operator. If you wish to use List as a sparse array and set values greater then size, then manually set size larger. Return this. Throw IndexErr if index is out of range. Throw ReadonlyErr if readonly.


setNotNull ​

L setNotNull(Int index, V? item)

Call set if item is non-null otherwise do nothing. Return this.


shuffle ​

L shuffle()

Shuffle this list's items into a randomized order. Return this. Throw ReadonlyErr if readonly.


size ​

Int size

The number of items in the list. Getting size is readonly safe, setting size throws ReadonlyErr if readonly.

If the size is set greater than the current size then the list is automatically grown to be a sparse list with new items defaulting to null. However if this is a non-nullable list, then growing a list will throw ArgErr.

If the size is set less than the current size then any items with indices past the new size are automatically removed. Changing size automatically allocates new storage so that capacity exactly matches the new size.


sort ​

L sort(|V,V->Int|? c := null)

Perform an in-place sort on this list. If a method is provided it implements the comparator returning -1, 0, or 1. If the comparator method is null then sorting is based on the value's <=> operator (shortcut for compare method). Return this. Throw ReadonlyErr if readonly.

Example:

s := ["candy", "ate", "he"]

s.sort
// s now evaluates to [ate, candy, he]

s.sort |Str a, Str b->Int| { return a.size <=> b.size }
// s now evaluates to ["he", "ate", "candy"]

sortr ​

L sortr(|V,V->Int|? c := null)

Reverse sort - perform an in-place reverse sort on this list. If a method is provided it implements the comparator returning -1, 0, or 1. If the comparator method is null then sorting is based on the value's <=> operator (shortcut for compare method). Return this. Throw ReadonlyErr if readonly.

Example:

[3, 2, 4, 1].sortr =>  [4, 3, 2, 1]

swap ​

L swap(Int indexA, Int indexB)

Swap the items at the two specified indexes. Negative indexes may be used to access an index from the end of the list. Return this. Throw ReadonlyErr if readonly.


toCode ​

Str toCode()

Get this list as a Fantom expression suitable for code generation. The individual items must all respond to the toCode method.


toStr ​

virtual override Str toStr()

Return a string representation of the list. This method is readonly safe.


trim ​

L trim()

Trim the capacity such that the underlying storage is optimized for the current size. Return this. Throw ReadonlyErr if readonly.


union ​

L union(L that)

Return a new list which is the union of this list and the given list. The union is defined as the unique items which are in either list. The resulting list is ordered first by this list's order, and secondarily by that's order. The new list is guaranteed to be unique with no duplicate values. Equality is determined using hash() and the == operator (shortcut for equals method). This method is readonly safe.

Example:

[1, 2].union([3, 2]) => [1, 2, 3]

unique ​

L unique()

Returns a new list with all duplicate items removed such that the resulting list is a proper set. Duplicates are detected using hash() and the == operator (shortcut for equals method). This method is readonly safe.

Example:

["a", "a", "b", "c", "b", "b"].unique => ["a", "b", "c"]

Locale ​

@Serializable { simple=true } const class Locale : Obj

Locale models a cultural language and region/country. See Localization for details.

Also see Env.locale and Pod.locale.

Constructors

fromStrParse a locale according to the toStr format.

Fields

enConstant for the English Locale "en"

Methods

countryGet the country/region as an uppercase ISO 3166 two letter code.
curGet the current thread's locale.
equalsEquality is based on the normalized toStr format.
hashCompute hash code based on normalized toStr format.
langGet the language as a lowercase ISO 639 two letter code.
setCurSet the current thread's locale.
toStrReturn string representation
useRun the specified function using this locale as the actor's current locale.

Slot Details ​


country ​

Str? country()

Get the country/region as an uppercase ISO 3166 two letter code. Return null if the country is unspecified.


cur ​

static Locale cur()

Get the current thread's locale.


en ​

const static Locale en

Constant for the English Locale "en"


equals ​

virtual override Bool equals(Obj? obj)

Equality is based on the normalized toStr format.


fromStr ​

static new fromStr(Str s, Bool checked := true)

Parse a locale according to the toStr format. If invalid format and checked is false return null, otherwise throw ParseErr.


hash ​

virtual override Int hash()

Compute hash code based on normalized toStr format.


lang ​

Str lang()

Get the language as a lowercase ISO 639 two letter code.


setCur ​

static Void setCur(Locale locale)

Set the current thread's locale. Throw NullErr if null is passed.


toStr ​

virtual override Str toStr()

Return string representation:

<locale>  := <lang> ["-" <country>]
<lang>    := lowercase ISO 636 two letter code
<country> := uppercase ISO 3166 two letter code

use ​

This use(|This| func)

Run the specified function using this locale as the actor's current locale. This method guarantees that upon return the actor's current locale remains unchanged.


Log ​

const class Log : Obj

Log provides a simple, but standardized mechanism for logging.

See Logging for details and examples.

Constructors

makeCreate a new log by name.

Fields

levelThe log level field defines which log entries are reported versus ignored.

Methods

addHandlerInstall a handler to receive callbacks on logging events.
debugGenerate a LogLevel.debug log entry.
errGenerate a LogLevel.err log entry.
findFind a registered log by name.
getFind an existing registered log by name or if not found then create a new registered Log instance with the given name.
handlersList all the handler functions installed to process log events.
infoGenerate a LogLevel.info log entry.
isDebugReturn if debug level is enabled.
isEnabledReturn if this log is enabled for the specified level.
isErrReturn if error level is enabled.
isInfoReturn if info level is enabled.
isWarnReturn if warn level is enabled.
listReturn a list of all the active logs which have been registered since system startup.
logPublish a log entry.
nameReturn name of the log.
removeHandlerUninstall a log handler.
toStrReturn name.
warnGenerate a LogLevel.warn log entry.

Slot Details ​


addHandler ​

static Void addHandler(|LogRec| handler)

Install a handler to receive callbacks on logging events. If the handler func is not immutable, then throw NotImmutableErr.


debug ​

Void debug(Str msg, Err? err := null)

Generate a LogLevel.debug log entry.


err ​

Void err(Str msg, Err? err := null)

Generate a LogLevel.err log entry.


find ​

static Log? find(Str name, Bool checked := true)

Find a registered log by name. If the log doesn't exist and checked is false then return null, otherwise throw Err.


get ​

static Log get(Str name)

Find an existing registered log by name or if not found then create a new registered Log instance with the given name. Name must be valid according to Uri.isName otherwise NameErr is thrown.


handlers ​

static |LogRec|[] handlers()

List all the handler functions installed to process log events.


info ​

Void info(Str msg, Err? err := null)

Generate a LogLevel.info log entry.


isDebug ​

Bool isDebug()

Return if debug level is enabled.


isEnabled ​

Bool isEnabled(LogLevel level)

Return if this log is enabled for the specified level.


isErr ​

Bool isErr()

Return if error level is enabled.


isInfo ​

Bool isInfo()

Return if info level is enabled.


isWarn ​

Bool isWarn()

Return if warn level is enabled.


level ​

LogLevel level

The log level field defines which log entries are reported versus ignored. Anything which equals or is more severe than the log level is logged. Anything less severe is ignored. If the level is set to silent, then logging is disabled.


list ​

static Log[] list()

Return a list of all the active logs which have been registered since system startup.


log ​

virtual Void log(LogRec rec)

Publish a log entry. The convenience methods err, warn info, and debug all route to this method for centralized handling. The standard implementation is to call each of the installed handlers if the specified level is enabled.


make ​

new make(Str name, Bool register)

Create a new log by name. The log is added to the VM log registry only if register is true. If register is true and a log has already been created for the specified name then throw ArgErr. Name must be valid according to Uri.isName otherwise NameErr is thrown.


name ​

Str name()

Return name of the log.


removeHandler ​

static Void removeHandler(|LogRec| handler)

Uninstall a log handler.


toStr ​

virtual override Str toStr()

Return name.


warn ​

Void warn(Str msg, Err? err := null)

Generate a LogLevel.warn log entry.


LogLevel ​

@Serializable { simple=true } enum class LogLevel : Enum

LogLevel provides a set of discrete levels used to customize logging. See Logging for details.

Enum

debug
info
warn
err
silent

Constructors

fromStrReturn the LogLevel instance for the specified name.

Fields

valsList of LogLevel values indexed by ordinal

Slot Details ​


debug ​

const static LogLevel debug := ...


err ​

const static LogLevel err := ...


fromStr ​

static new fromStr(Str name, Bool checked := true)

Return the LogLevel instance for the specified name. If not a valid name and checked is false return null, otherwise throw ParseErr.


info ​

const static LogLevel info := ...


silent ​

const static LogLevel silent := ...


vals ​

const static LogLevel[] vals := ...

List of LogLevel values indexed by ordinal


warn ​

const static LogLevel warn := ...


LogRec ​

const class LogRec : Obj

LogRec all the information of a single logging event. See Logging for details.

Constructors

makeConstructor with all the fields

Fields

errException if applicable
levelSeverity level of event
logNameName of Log which generated the event
msgMessage text event
timeTimestamp of log event

Methods

printPrint to the specified output stream.
toStrReturn standard log format.

Slot Details ​


err ​

const Err? err

Exception if applicable


level ​

const LogLevel level

Severity level of event


logName ​

const Str logName

Name of Log which generated the event


make ​

new make(DateTime time, LogLevel level, Str logName, Str message, Err? err := null)

Constructor with all the fields


msg ​

const Str msg

Message text event


Void print(OutStream out := Env.cur().out())

Print to the specified output stream.


time ​

const DateTime time

Timestamp of log event


toStr ​

virtual override Str toStr()

Return standard log format.


Map ​

@Serializable class Map : Obj

Map is a hash map of key/value pairs.

See examples.

Constructors

makeConstructor for type (must be Map type).

Fields

caseInsensitiveThis field configures case sensitivity for maps with Str keys.
defThe default value to use for get when a key isn't mapped.
orderedWhen set to true, the map maintains the order in which key/value pairs are added to the map.

Methods

addAdd the specified key/value pair to the map.
addAllAppend the specified map to this map by adding every key/value in m in this map.
addIfNotNullDeprecated - use addNotNull
addListAdd the specified list to this map where the values are the list items and the keys are derived by calling the specified function on each item.
addNotNullCall add if val is non-null otherwise do nothing.
allReturn true if c returns true for all of the key/value pairs in the map.
anyReturn true if c returns true for any of the key/value pairs in the map.
clearRemove all key/value pairs from the map.
containsKeyReturn if the specified key is mapped.
dupCreate a shallow duplicate copy of this map.
eachCall the specified function for every key/value pair in the map.
eachWhileIterate every key/value pair in the map until the function returns non-null.
equalsTwo Maps are equal if they have the same type and same number of equal key/value pairs.
excludeReturn a new map containing the key/value pairs for which c returns false.
findReturn the first value in the map for which c returns true.
findAllReturn a new map containing the key/value pairs for which c returns true.
findNotNullReturn a new map containing all the key/value pairs where value is not null.
getGet the value for the specified key.
getCheckedGet the value for the specified key.
getOrAddGet the value for the specified key, or if it doesn't exist then automatically add it.
getOrThrowGet the value for the specified key or if key is not mapped then raise UnknownKeyErr.
hashReturn platform dependent hashcode based on hash of the keys and values.
isEmptyReturn if size() == 0.
isROReturn if this Map is readonly.
isRWReturn if this Map is read-write.
joinReturn a string by concatenating each key/value pair using the specified separator string.
keysGet a list of all the mapped keys.
mapCreate a new map with the same keys, but apply the specified closure to generate new values.
mapNotNullConvenience for map and findNotNull.
reduceReduce is used to iterate through every key/value pair in the map to reduce the map into a single value called the reduction.
removeRemove the key/value pair identified by the specified key from the map and return the value.
roGet a readonly Map instance with the same contents as this Map (although its values may be mutable themselves).
rwGet a read-write, mutable Map instance with the same contents as this Map.
setSet the value for the specified key.
setAllAppend the specified map to this map by setting every key/value in m in this map.
setListAdd the specified list to this map where the values are the list items and the keys are derived by calling the specified function on each item.
setNotNullCall set if val is non-null otherwise do nothing.
sizeGet the number of key/value pairs in the list.
toCodeGet this map as a Fantom expression suitable for code generation.
toStrReturn a string representation of the Map.
valsGet a list of all the mapped values.

Slot Details ​


add ​

M add(K key, V val)

Add the specified key/value pair to the map. If the key is already mapped, then throw ArgErr. Return this. If key does not return true for Obj.isImmutable, then throw NotImmutableErr. If key is null throw NullErr. Throw ReadonlyErr if readonly.


addAll ​

M addAll(M m)

Append the specified map to this map by adding every key/value in m in this map. If any key in m is already mapped then this method will fail (any previous keys will remain mapped potentially leaving this map in an inconsistent state). Return this. Throw ReadonlyErr if readonly. Also see setAll. This method is semanatically equivalent to:

m.each |v, k| { this.add(k, v) }

addIfNotNull ​

@Deprecated { msg="Use addNotNull" } M addIfNotNull(K key, V? val)

Deprecated - use addNotNull


addList ​

M addList(V[] list, |V,Int->K|? c := null)

Add the specified list to this map where the values are the list items and the keys are derived by calling the specified function on each item. If the function is null, then the items themselves are used as the keys. If any key is already mapped then this method will fail (any previous keys will remain mapped, potentially leaving this map in an inconsistent state). Return this. Throw ReadonlyErr if readonly. Also see setList.

Examples:

m := [0:"0"]
m.addList(["1","2"]) |Str s->Int| { return s.toInt }
m  =>  [0:"0", 1:"1", 2:"2"]

addNotNull ​

M addNotNull(K key, V? val)

Call add if val is non-null otherwise do nothing. Return this.


all ​

Bool all(|V,K->Bool| c)

Return true if c returns true for all of the key/value pairs in the map. If the list is empty, return true. This method is readonly safe.


any ​

Bool any(|V,K->Bool| c)

Return true if c returns true for any of the key/value pairs in the map. If the map is empty, return false. This method is readonly safe.


caseInsensitive ​

Bool caseInsensitive := false

This field configures case sensitivity for maps with Str keys. When set to true, Str keys are compared without regard to case for the following methods: get, containsKey, set, add, setAll, addAll, and remove methods. Only ASCII character case is taken into account. The original case is preserved (keys aren't made all lower or upper case). This field defaults to false.

Getting this field is readonly safe. If you attempt to set this method on a map which is not empty or not typed to use Str keys, then throw UnsupportedOperation. Throw ReadonlyErr if set when readonly. This mode cannot be used concurrently with ordered.


clear ​

M clear()

Remove all key/value pairs from the map. Return this. Throw ReadonlyErr if readonly.


containsKey ​

Bool containsKey(K key)

Return if the specified key is mapped. This method is readonly safe.


def ​

V? def

The default value to use for get when a key isn't mapped. This field defaults to null. The value of def must be immutable or NotImmutableErr is thrown. Getting this field is readonly safe. Throw ReadonlyErr if set when readonly.


dup ​

M dup()

Create a shallow duplicate copy of this map. The keys and values themselves are not duplicated. The resulting map is always read/write. This method is readonly safe.


each ​

Void each(|V,K| c)

Call the specified function for every key/value pair in the map. This method is readonly safe.


eachWhile ​

Obj? eachWhile(|V,K->Obj?| c)

Iterate every key/value pair in the map 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 key/value pair. This method is readonly safe.


equals ​

virtual override Bool equals(Obj? that)

Two Maps are equal if they have the same type and same number of equal key/value pairs.

Examples:

a := Int:Str[1:"one", 2:"two"]
b := Int:Str[2:"two", 1:"one"]
c := Int:Str?[2:"two", 1:"one"]
a == b  =>  true
a == c  =>  false

exclude ​

M exclude(|V,K->Bool| c)

Return a new map containing the key/value pairs for which c returns false. If c returns true for every item, then return an empty map. The inverse of this method is findAll. If this map is ordered or caseInsensitive, then the resulting map is too. This method is readonly safe.

Example:

map := ["off":0, "slow":50, "fast":100]
map.exclude |Int v->Bool| { return v == 0 } => ["slow":50, "fast":100]

find ​

V? find(|V,K->Bool| c)

Return the first value in the map for which c returns true. If c returns false for every pair, then return null. This method is readonly safe.


findAll ​

M findAll(|V,K->Bool| c)

Return a new map containing the key/value pairs for which c returns true. If c returns false for every item, then return an empty map. The inverse of this method is exclude. If this map is ordered or caseInsensitive, then the resulting map is too. This method is readonly safe.


findNotNull ​

M findNotNull()

Return a new map containing all the key/value pairs where value is not null. If this map is ordered or caseInsensitive, then the resulting map is too. This method is readonly safe.


get ​

@Operator V? get(K key, V? def := this.def)

Get the value for the specified key. If key is not mapped, then return the value of the def parameter. If def is omitted it defaults to the def field. This method is readonly safe. Shortcut is a[key].


getChecked ​

V? getChecked(K key, Bool checked := true)

Get the value for the specified key. If the key is not mapped then return null or raise UnknownKeyErr based on checked flag. This method is readonly safe.


getOrAdd ​

V getOrAdd(K key, |K->V| valFunc)

Get the value for the specified key, or if it doesn't exist then automatically add it. The value function is called to get the value to add, it is only called if the key is not mapped. Throw ReadonlyErr if readonly only if add is required.


getOrThrow ​

V getOrThrow(K key)

Get the value for the specified key or if key is not mapped then raise UnknownKeyErr. This method is readonly safe.


hash ​

virtual override Int hash()

Return platform dependent hashcode based on hash of the keys and values.


isEmpty ​

Bool isEmpty()

Return if size() == 0. This method is readonly safe.


isRO ​

Bool isRO()

Return if this Map is readonly. A readonly Map is guaranteed to be immutable (although its values may be mutable themselves). Any attempt to modify a readonly Map will result in ReadonlyErr. Use rw to get a read-write Map from a readonly Map. Methods documented as "readonly safe" may be used safely with a readonly Map. This method is readonly safe.


isRW ​

Bool isRW()

Return if this Map is read-write. A read-write Map is mutable and may be modified. Use ro to get a readonly Map from a read-write Map. This method is readonly safe.


join ​

Str join(Str separator, |V,K->Str|? c := null)

Return a string by concatenating each key/value pair using the specified separator string. If c is non-null then it is used to format each pair into a string, otherwise "$k: $v" is used. This method is readonly safe.

Example:

m := ["a" : 1, "b" : 2]
m.join(" and ") |Int v, Str k->Str| { return "$v from $k" }
  => 1 from a and 2 from b

keys ​

K[] keys()

Get a list of all the mapped keys. This method is readonly safe.


make ​

new make(Type type)

Constructor for type (must be Map type).


map ​

Obj:Obj? map(|V,K->Obj?| c)

Create a new map with the same keys, but apply the specified closure to generate new values. The new map is typed based on the return type of c. If this map is ordered or caseInsensitive, then the resulting map is too. This method is readonly safe.

Example:

m := [2:2, 3:3, 4:4]
x := m.map |Int v->Int| { return v*2 }
x => [2:4, 3:6, 4:8]

mapNotNull ​

Obj:Obj? mapNotNull(|V,K->Obj?| c)

Convenience for map and findNotNull. Each key/value pair is mapped by the given function and if null is returned it is excluded from the result. The resulting type is based on the return type of c but non-nullable. This method is readonly safe.


ordered ​

Bool ordered := false

When set to true, the map maintains the order in which key/value pairs are added to the map. The implementation is based on using a linked list in addition to the normal hashmap. This field defaults to false.

Getting this field is readonly safe. If you attempt to set this method on a map which is not empty, then throw UnsupportedOperation. Throw ReadonlyErr if set when readonly. This mode cannot be used concurrently with caseInsensitive.


reduce ​

Obj? reduce(Obj? init, |Obj?,V,K->Obj?| c)

Reduce is used to iterate through every key/value pair in the map to reduce the map into a single value called the reduction. The initial value of the reduction is passed in as the init parameter, then passed back to the closure along with each key/value pair. This method is readonly safe.

Example:

m := ["2":2, "3":3, "4":4]
m.reduce(100) |Obj r, Int v->Obj| { return (Int)r + v } => 109

remove ​

V? remove(K key)

Remove the key/value pair identified by the specified key from the map and return the value. If the key was not mapped then return null. Throw ReadonlyErr if readonly.


ro ​

M ro()

Get a readonly Map instance with the same contents as this Map (although its values may be mutable themselves). If this Map is already readonly, then return this. Only methods documented as "readonly safe" may be used safely with a readonly Map, all others will throw ReadonlyErr. This method is readonly safe.


rw ​

M rw()

Get a read-write, mutable Map instance with the same contents as this Map. If this Map is already read-write, then return this. This method is readonly safe.


set ​

@Operator M set(K key, V val)

Set the value for the specified key. If the key is already mapped, this overwrites the old value. If key is not yet mapped this adds the key/value pair to the map. Return this. If key does not return true for Obj.isImmutable, then throw NotImmutableErr. If key is null throw NullErr. Throw ReadonlyErr if readonly.


setAll ​

M setAll(M m)

Append the specified map to this map by setting every key/value in m in this map. Keys in m not yet mapped are added and keys already mapped are overwritten. Return this. Throw ReadonlyErr if readonly. Also see addAll. This method is semanatically equivalent to:

m.each |v, k| { this.set(k, v) }

setList ​

M setList(V[] list, |V,Int->K|? c := null)

Add the specified list to this map where the values are the list items and the keys are derived by calling the specified function on each item. If the function is null, then the items themselves are used as the keys. If any key is already mapped then it is overwritten. Return this. Throw ReadonlyErr if readonly. Also see addList.

Examples:

m := [0:"0", 2:"old"]
m.setList(["1","2"]) |Str s->Int| { return s.toInt }
m  =>  [0:"0", 1:"1", 2:"2"]

setNotNull ​

M setNotNull(K key, V? val)

Call set if val is non-null otherwise do nothing. Return this.


size ​

Int size()

Get the number of key/value pairs in the list. This method is readonly safe.


toCode ​

Str toCode()

Get this map as a Fantom expression suitable for code generation. The individual keys and values must all respond to the toCode method.


toStr ​

virtual override Str toStr()

Return a string representation of the Map. This method is readonly safe.


vals ​

V[] vals()

Get a list of all the mapped values. This method is readonly safe.


Method ​

const class Method : Slot

Method models a function with a formal parameter list and return value (or Void if no return).

Methods

callConvenience for func.call
callListConvenience for func.callList
callOnConvenience for func.callOn
funcGet the function body of this method.
paramDefEvaluate the parameter default using reflection.
paramsGet the parameters of the method.
returnsType returned by the method or sys::Void if no return value.

Slot Details ​


call ​

Obj? call(Obj? a := null, Obj? b := null, Obj? c := null, Obj? d := null, Obj? e := null, Obj? f := null, Obj? g := null, Obj? h := null)

Convenience for func.call


callList ​

Obj? callList(Obj?[]? args)

Convenience for func.callList


callOn ​

Obj? callOn(Obj? target, Obj?[]? args)

Convenience for func.callOn


func ​

Func func()

Get the function body of this method.


paramDef ​

Obj? paramDef(Param param, Obj? instance := null)

Evaluate the parameter default using reflection. If this method is static or a constructor, then instance should be null. Raise an exception if the parameter default cannot be evaluated independently (such as using an expression with previous parameters).


params ​

Param[] params()

Get the parameters of the method. Convenience for func.params.


returns ​

Type returns()

Type returned by the method or sys::Void if no return value. Convenience for func.returns.


MimeType ​

@Serializable { simple=true } const class MimeType : Obj

MimeType represents the parsed value of a Content-Type header per RFC 2045 section 5.1.

Constructors

fromStrParse from string format.

Methods

charsetIf a charset parameter is specified, then map it to the Charset instance, otherwise return Charset.utf8.
equalsEquality is based on the case insensitive mediaType and subType, and params (keys are case insensitive and values are case sensitive).
forExtMap a case insensitive file extension to a MimeType.
hashHash code is derived from the mediaType, subType, and params hashes.
isTextReturn if this mime type is known to be text.
mediaTypeThe primary media type always in lowercase
noParamsReturn an instance with this mediaType and subType, but strip any parameters.
paramsAdditional parameters stored in case-insensitive map.
parseParamsParse a set of attribute-value parameters where the values may be tokens or quoted-strings.
subTypeThe subtype always in lowercase
toStrEncode as a MIME message according to RFC 822.

Slot Details ​


charset ​

Charset charset()

If a charset parameter is specified, then map it to the Charset instance, otherwise return Charset.utf8.


equals ​

virtual override Bool equals(Obj? that)

Equality is based on the case insensitive mediaType and subType, and params (keys are case insensitive and values are case sensitive).


forExt ​

static MimeType? forExt(Str ext)

Map a case insensitive file extension to a MimeType. This mapping is configured via "etc/sys/ext2mime.props". If no mapping is available return null.


fromStr ​

static new fromStr(Str s, Bool checked := true)

Parse from string format. If invalid format and checked is false return null, otherwise throw ParseErr. Parenthesis comments are treated as part of the value.


hash ​

virtual override Int hash()

Hash code is derived from the mediaType, subType, and params hashes.


isText ​

Bool isText()

Return if this mime type is known to be text. This includes all "text/*" mime types along with special cases like "application/json".


mediaType ​

Str mediaType()

The primary media type always in lowercase:

text/html  =>  text

noParams ​

MimeType noParams()

Return an instance with this mediaType and subType, but strip any parameters.


params ​

Str:Str params()

Additional parameters stored in case-insensitive map. If no parameters, then this is an empty map.

text/html; charset=utf-8    =>  [charset:utf-8]
text/html; charset="utf-8"  =>  [charset:utf-8]

parseParams ​

static [Str:Str]? parseParams(Str s, Bool checked := true)

Parse a set of attribute-value parameters where the values may be tokens or quoted-strings. The resulting map is case insensitive. If invalid format return null or raise ParseErr based on checked flag. Parenthesis comments are not supported. If a value pair is missing "= value", then the value is defaulted to "".

Examples:

a=b; c="d"       =>  ["a":"b", "c"="d"]
foo=bar; secure  =>  ["foo":"bar", "secure":""]

subType ​

Str subType()

The subtype always in lowercase:

text/html  =>  html

toStr ​

virtual override Str toStr()

Encode as a MIME message according to RFC 822. This is always the exact same string passed to fromStr.


Month ​

@Serializable { simple=true } enum class Month : Enum

Enum for twelve months of the year.

Enum

janJanuary
febFebruary
marMarch
aprApril
mayMay
junJune
julJuly
augAugust
sepSeptember
octOctober
novNovember
decDecember

Constructors

fromStrReturn the Month instance for the specified name.

Fields

valsList of Month values indexed by ordinal

Methods

decrementReturn the month before this month.
incrementReturn the month after this month.
localeAbbrGet the abbreviated name for the current locale.
localeFullGet the full name for the current locale.
numDaysReturn the number of days in this month for the specified year.
toLocaleReturn the month as a localized string according to the specified pattern.

Slot Details ​


apr ​

const static Month apr := ...

April


aug ​

const static Month aug := ...

August


dec ​

const static Month dec := ...

December


decrement ​

@Operator Month decrement()

Return the month before this month.


feb ​

const static Month feb := ...

February


fromStr ​

static new fromStr(Str name, Bool checked := true)

Return the Month instance for the specified name. If not a valid name and checked is false return null, otherwise throw ParseErr.


increment ​

@Operator Month increment()

Return the month after this month.


jan ​

const static Month jan := ...

January


jul ​

const static Month jul := ...

July


jun ​

const static Month jun := ...

June


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.


mar ​

const static Month mar := ...

March


may ​

const static Month may := ...

May


nov ​

const static Month nov := ...

November


numDays ​

Int numDays(Int year)

Return the number of days in this month for the specified year.


oct ​

const static Month oct := ...

October


sep ​

const static Month sep := ...

September


toLocale ​

Str toLocale(Str? pattern := null, Locale locale := Locale.cur())

Return the month as a localized string according to the specified pattern. The pattern rules are a subset of the DateTime.toLocale:

M      One/two digit month        6, 11
MM     Two digit month            06, 11
MMM    Three letter abbr month    Jun, Nov
MMMM   Full month name            June, November

If pattern is null it defaults to "MMM". Also see localeAbbr and localeFull.


vals ​

const static Month[] vals := ...

List of Month values indexed by ordinal


NameErr ​

const class NameErr : Err

NameErr indicates an attempt to use an invalid name. See Uri.isName and Uri.checkName.

Constructors

makeConstruct 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.


NoDoc ​

facet class NoDoc : Obj, Facet

Annotate a type or slot as undocumented. This facet indicates an API should not be documented with automated tools such as Fandoc. As a developer you should avoid using these types and slots since they are explicitly marked as not part of the public API.

Fields

defValSingleton for NoDoc facet.

Slot Details ​


defVal ​

const static NoDoc defVal := ...

Singleton for NoDoc facet.


NotImmutableErr ​

const class NotImmutableErr : Err

NotImmutableErr indicates using a mutable Obj where an immutable Obj is required. See Obj.isImmutable for the definition of immutability.

Constructors

makeConstruct 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.


NullErr ​

const class NullErr : Err

NullErr indicates an attempt to dereference null. It is often raised when attempting to access an instance field or method on a null reference. It may also be thrown when a parameter is expecting a non-nullable argument and null is passed.

Constructors

makeConstruct 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.


Num ​

abstract const class Num : Obj

Num is the base class for number classes: Int, Float, and Decimal.

Methods

localeDecimalGet the current locale's decimal separator.
localeGroupingGet the current locale's separator for grouping thousands together.
localeMinusGet the current locale's minus sign used to represent a negative number.
localeNaNGet the current locale's string representation for not-a-number.
localeNegInfGet the current locale's string representation for negative infinity.
localePercentGet the current locale's symbol for the percent sign.
localePosInfGet the current locale's string representation for positive infinity.
toDecimalConvert this number to a Decimal.
toFloatConvert this number to a Float.
toIntConvert this number to an Int.

Slot Details ​


localeDecimal ​

static Str localeDecimal()

Get the current locale's decimal separator. For example in the the US this is a dot.


localeGrouping ​

static Str localeGrouping()

Get the current locale's separator for grouping thousands together. For example in the US this is a comma.


localeMinus ​

static Str localeMinus()

Get the current locale's minus sign used to represent a negative number.


localeNaN ​

static Str localeNaN()

Get the current locale's string representation for not-a-number.


localeNegInf ​

static Str localeNegInf()

Get the current locale's string representation for negative infinity.


localePercent ​

static Str localePercent()

Get the current locale's symbol for the percent sign.


localePosInf ​

static Str localePosInf()

Get the current locale's string representation for positive infinity.


toDecimal ​

Decimal toDecimal()

Convert this number to a Decimal.


toFloat ​

Float toFloat()

Convert this number to a Float.


toInt ​

Int toInt()

Convert this number to an Int.


Obj ​

abstract class Obj

Obj is the root class of all classes.

Constructors

makeObj constructor for subclasses.

Methods

compareReturn a negative integer, zero, or a positive integer if this object is less than, equal to, or greater than the specified object
echoWrite x.toStr to standard output followed by newline.
equalsCompare this object to the specified for equality.
hashReturn a unique hashcode for this object.
isImmutableReturn if this Obj is immutable and safe to share between threads
toImmutableGet an immutable representation of this instance or throw NotImmutableErr if this object cannot be represented as an immutable
toStrReturn a string representation of this object.
trapTrap a dynamic call for handling.
typeofGet the Type instance which represents this object's class.
withThis method called whenever an it-block is applied to an object.

Slot Details ​


compare ​

virtual Int compare(Obj that)

Return a negative integer, zero, or a positive integer if this object is less than, equal to, or greater than the specified object:

this < that   =>  <0
this == that  =>  0
this > that   =>  >0

This method may also be accessed via the < <= <=> >= and > shortcut operators. If not overridden the default implementation compares the toStr representations. Also see docLang.

Examples:

3.compare(8)  =>  -1
8.compare(3)  =>  1
8.compare(8)  =>  0
3 <=> 8       =>  -1  // shortcut for 3.compare(8)

echo ​

static Void echo(Obj? x := "")

Write x.toStr to standard output followed by newline. If x is null then print "null". If no argument is provided then print an empty line.


equals ​

virtual Bool equals(Obj? that)

Compare this object to the specified for equality. This method may be accessed via the == and != shortcut operators. If not overridden the default implementation compares for reference equality using the === operator. If this method is overridden, then hash() must also be overridden such that any two objects which return true for equals() must return the same value for hash(). This method must accept null and return false.


hash ​

virtual Int hash()

Return a unique hashcode for this object. If a class overrides hash() then it must ensure if equals() returns true for any two objects then they have same hash code.


isImmutable ​

Bool isImmutable()

Return if this Obj is immutable and safe to share between threads:

  • an instance of a const class
  • the result of toImmutable on List, Map, or Buf
  • a Func object may or may not be immutable - see Func.
  • other instances are assumed mutable and return false

make ​

new make()

Obj constructor for subclasses.


toImmutable ​

This toImmutable()

Get an immutable representation of this instance or throw NotImmutableErr if this object cannot be represented as an immutable:

  • if type is const, return this
  • if already an immutable List, Map, Buf, or Func return this
  • if a List, then attempt to perform a deep clone by calling toImmutable on all items
  • if a Map, then attempt to perform a deep clone by calling toImmutable on all values (keys are already immutable)
  • some Funcs can be made immutable - see Func
  • if a Buf create immutable copy, see Buf
  • any other object throws NotImmutableErr

toStr ​

virtual Str toStr()

Return a string representation of this object.


trap ​

virtual Obj? trap(Str name, Obj?[]? args := null)

Trap a dynamic call for handling. Dynamic calls are invoked with the -> shortcut operator:

a->x        a.trap("x", null)
a->x()      a.trap("x", null)
a->x = b    a.trap("x", [b])
a->x(b)     a.trap("x", [b])
a->x(b, c)  a.trap("x", [b, c])

The default implementation provided by Obj attempts to use reflection. If name maps to a method, it is invoked with the specified arguments. If name maps to a field and args.size is zero, get the field. If name maps to a field and args.size is one, set the field and return args[0]. Otherwise throw UnknownSlotErr.


typeof ​

Type typeof()

Get the Type instance which represents this object's class. Also seeType.of or Pod.of.


with ​

virtual This with(|This| f)

This method called whenever an it-block is applied to an object. The default implementation calls the function with this, and then returns this.


Operator ​

facet class Operator : Obj, Facet

Used on methods to indicate method may be used as an operator. The operator symbol is determined by the method name:

prefix     symbol    degree
------     ------    ------
negate     -a        unary
increment  ++a       unary
decrement  --a       unary
plus       a + b     binary
minus      a - b     binary
mult       a * b     binary
div        a / b     binary
mod        a % b     binary
get        a[b]      binary
set        a[b] = c  ternary
add        a { b, }

In the case of binary operators multiple methods may be declared for a given symbol as long as every method starts with correct name, for example "plus" and "plusInt". For unary/ternary operators there can only be one method and it must be named exactly "negate", "increment", "decrement", or "set".

See docLang for additional details.

Fields

defValSingleton for Operator facet.

Slot Details ​


defVal ​

const static Operator defVal := ...

Singleton for Operator facet.


OutStream ​

class OutStream : Obj

OutStream is used to write binary and text data to an output stream.

Constructors

makeConstructor for an OutStream which wraps another stream.

Fields

charsetThe current charset used to encode Unicode characters into bytes.
endianByte order mode for binary writes.
xmlEscNewlinesXML escape newline characters.
xmlEscQuotesXML escape single and double quotes.
xmlEscUnicodeXML escape any character greater then 0x7f.

Methods

closeClose the output stream.
flushFlush the stream so any buffered bytes are written out.
printConvenience for writeChars(obj.toStr).
printLineConvenience for writeChars(obj.toStr + "\n").
syncIf this output stream is mapped to a file device, then synchronize all memory buffers to the physical storage device.
writeWrite a byte to the output stream.
writeBitsWrite between 0 and 64 bits of the given integer value.
writeBoolWrite one byte, one if true or zero if false.
writeBufWrite n bytes from the specified Buf at its current position to this output stream.
writeCharWrite one or more bytes to the stream for the specified Unicode character based on the current charset encoding.
writeCharsWrite the Unicode characters in the specified string to the stream using the current charset encoding.
writeDecimalWrite a decimal as a string according to writeUtf.
writeF4Write four bytes as a 32-bit floating point number using configured endian order according to Float.bits32.
writeF8Write eight bytes as a 64-bit floating point number using configured endian order according to Float.bits.
writeI2Write two bytes as a 16-bit number using configured endian.
writeI4Write four bytes as a 32-bit number using configured endian.
writeI8Write eight bytes as a 64-bit number using configured endian.
writeObjWrite a serialized object from the stream according to the Fantom serialization format.
writePropsWrite the given map of Str name/value pairs to the output stream according to the Fantom props file format (see InStream.readProps for full specification).
writeUtfWrite a Str in modified UTF-8 format according to the java.io.DataOutput specification.
writeXmlWrite a string to this output stream using XML escape sequences.

Slot Details ​


charset ​

Charset charset

The current charset used to encode Unicode characters into bytes. The default charset should always be UTF-8.


close ​

virtual Bool close()

Close the output stream. This method is guaranteed to never throw an IOErr. Return true if the stream was closed successfully or false if the stream was closed abnormally. Default implementation does nothing and returns true.


endian ​

Endian endian

Byte order mode for binary writes. Default is Endian.big (network byte order).


flush ​

virtual This flush()

Flush the stream so any buffered bytes are written out. Default implementation does nothing. Throw IOErr on error. Return this.


make ​

new make(OutStream? out)

Constructor for an OutStream which wraps another stream. All writes to this stream will be routed to the specified inner stream.

If out is null, then it is the subclass responsibility to handle writes by overriding the following methods: write and writeBuf.


This print(Obj? s)

Convenience for writeChars(obj.toStr). If obj is null, then print the string "null". Return this.


printLine ​

This printLine(Obj? obj := "")

Convenience for writeChars(obj.toStr + "\n"). If obj is null then print the string "null\n". Return this.


sync ​

virtual This sync()

If this output stream is mapped to a file device, then synchronize all memory buffers to the physical storage device. Throw IOErr on error. Return this.


write ​

virtual This write(Int byte)

Write a byte to the output stream. Throw IOErr on error. Return this.


writeBits ​

This writeBits(Int val, Int num)

Write between 0 and 64 bits of the given integer value. Bits which are only a partial byte are bufferred in RAM until flush.


writeBool ​

This writeBool(Bool b)

Write one byte, one if true or zero if false. This method is paired with InStream.readBool. Throw IOErr on error. Return this.


writeBuf ​

virtual This writeBuf(Buf buf, Int n := buf.remaining())

Write n bytes from the specified Buf at its current position to this output stream. If n is defaulted to buf.remaining(), then everything left in the buffer is drained to this output stream. The buf's position is advanced n bytes upon return. Throw IOErr on error. Return this.


writeChar ​

This writeChar(Int char)

Write one or more bytes to the stream for the specified Unicode character based on the current charset encoding. Return this.


writeChars ​

This writeChars(Str str, Int off := 0, Int len := str.size() - off)

Write the Unicode characters in the specified string to the stream using the current charset encoding. The off arg specifies the index offset to start writing characters and len the number of characters in str to write. Return this.


writeDecimal ​

This writeDecimal(Decimal d)

Write a decimal as a string according to writeUtf.


writeF4 ​

This writeF4(Float r)

Write four bytes as a 32-bit floating point number using configured endian order according to Float.bits32. This is paired with InStream.readF4. Throw IOErr on error. Return this.


writeF8 ​

This writeF8(Float r)

Write eight bytes as a 64-bit floating point number using configured endian order according to Float.bits. This is paired with InStream.readF8. Throw IOErr on error. Return this.


writeI2 ​

This writeI2(Int n)

Write two bytes as a 16-bit number using configured endian. This method may be paired with InStream.readU2 or InStream.readS2. Throw IOErr on error. Return this.


writeI4 ​

This writeI4(Int n)

Write four bytes as a 32-bit number using configured endian. This method may be paired with InStream.readU4 or InStream.readS4. Throw IOErr on error. Return this.


writeI8 ​

This writeI8(Int n)

Write eight bytes as a 64-bit number using configured endian. This is paired with InStream.readS8. Throw IOErr on error. Return this.


writeObj ​

This writeObj(Obj? obj, [Str:Obj]? options := null)

Write a serialized object from the stream according to the Fantom serialization format. Throw IOErr on error. Return this.

The options may be used to specify the format of the output:

  • "indent": Int specifies how many spaces to indent each level. Default is 0.
  • "skipDefaults": Bool specifies if we should skip fields at their default values. Field values are compared according to the equals method. Default is false.
  • "skipErrors": Bool specifies if we should skip objects which aren't serializable. If true then we output null and a comment. Default is false.

writeProps ​

This writeProps(Str:Str props, Bool close := true)

Write the given map of Str name/value pairs to the output stream according to the Fantom props file format (see InStream.readProps for full specification). The props are written using UTF-8 regardless of this stream's current charset. If close argument is true, then automatically close the stream. Return this.


writeUtf ​

This writeUtf(Str s)

Write a Str in modified UTF-8 format according to the java.io.DataOutput specification. This method is paired with InStream.readUtf. Throw IOErr on error. Return this.


writeXml ​

This writeXml(Str str, Int mode := 0)

Write a string to this output stream using XML escape sequences. By default only the < > & characters are escaped. You can use the following flags to escape additional characters:

  • xmlEscNewlines: escape the \n and \r characters
  • xmlEscQuotes: escape the single and double quote characters
  • xmlEscUnicode: escape any character greater than 0x7f

Any control character less than 0x20 which is not \t, \n or \r is always escaped with a numeric reference. Return this.


xmlEscNewlines ​

const static Int xmlEscNewlines := 1

XML escape newline characters. See writeXml.


xmlEscQuotes ​

const static Int xmlEscQuotes := 2

XML escape single and double quotes. See writeXml.


xmlEscUnicode ​

const static Int xmlEscUnicode := 4

XML escape any character greater then 0x7f. See writeXml.


Param ​

const class Param : Obj

Param represents one parameter definition of a Func (or Method).

Methods

hasDefaultReturn if this parameter has a default value.
nameName of the parameter.
toStrReturn "$type $name"
typeType of the parameter.

Slot Details ​


hasDefault ​

Bool hasDefault()

Return if this parameter has a default value. If true, then callers are not required to specify an argument.


name ​

Str name()

Name of the parameter.


toStr ​

virtual override Str toStr()

Return "$type $name"


type ​

Type type()

Type of the parameter.


ParseErr ​

const class ParseErr : Err

ParseErr indicates an invalid string format which cannot be parsed. It is often used with fromStr and fromLocale methods.

Constructors

makeConstruct 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.


Pod ​

const class Pod : Obj

Pod represents a module of Types. Pods serve as a type namespace as well as unit of deployment and versioning.

Methods

configConvenience for Env.config.
dependsGet the declared list of dependencies for this pod.
docReturn the fandoc chapter for this pod or null if not available.
fileLook up a resource file in this pod.
filesList all the resource files contained by this pod.
findFind a pod by name.
flattenDependsExpand a set of pods to include all their recursive dependencies.
listGet a list of all the pods installed.
loadLoad a pod into memory from the specified input stream.
localeConvenience for Env.locale using Locale.cur.
logReturn the log for this pod's name.
metaGet the meta name/value pairs for this pod.
nameSimple name of the pod such as "sys".
ofGet the pod of the given instance which is convenience for Type.of(obj).pod.
orderByDependsOrder a list of pods by their dependencies.
propsConvenience for Env.props.
toStrAlways return name().
typeFind a type by name.
typesList of all the defined types.
uriUri for this pod which is always "fan://{name}".
versionVersion number for this pod.

Slot Details ​


config ​

Str? config(Str name, Str? def := null)

Convenience for Env.config.


depends ​

Depend[] depends()

Get the declared list of dependencies for this pod.


doc ​

Str? doc()

Return the fandoc chapter for this pod or null if not available. To get the summary string for the pod use:

pod.meta["pod.summary"]

file ​

File? file(Uri uri, Bool checked := true)

Look up a resource file in this pod. The URI must start with the Pod's uri or be path absolute. If the file cannot be found then return null or throw UnresolvedErr based on checked flag.

Examples:

Pod.find("icons").file(`/x16/cut.png`)
Pod.find("icons").file(`fan://icons/x16/cut.png`)
`fan://icons/x16/cut.png`.get

files ​

File[] files()

List all the resource files contained by this pod. Resources are any files included in the pod's zip file excluding fcode files. The URI of these files is rooted by uri. Use file or Uri.get to lookup a resource file.


find ​

static Pod? find(Str name, Bool checked := true)

Find a pod by name. If the pod doesn't exist and checked is false then return null, otherwise throw UnknownPodErr.


flattenDepends ​

static Pod[] flattenDepends(Pod[] pods)

Expand a set of pods to include all their recursive dependencies. This method does not order them; see orderByDepends.


list ​

static Pod[] list()

Get a list of all the pods installed. Note that currently this method will load all of the pods into memory, so it is an expensive operation.


load ​

static Pod load(InStream in)

Load a pod into memory from the specified input stream. The stream must contain a valid pod zip file with all the definitions. The pod is completely loaded into memory and the input stream is closed. The pod cannot have resources. The pod name as defined by /pod.def must be uniquely named or Err is thrown.


locale ​

Str? locale(Str name, Str? def := "pod::name")

Convenience for Env.locale using Locale.cur.


log ​

Log log()

Return the log for this pod's name. This is a convenience for Log.get(name).


meta ​

Str:Str meta()

Get the meta name/value pairs for this pod. See docLang.


name ​

Str name()

Simple name of the pod such as "sys".


of ​

static Pod? of(Obj obj)

Get the pod of the given instance which is convenience for Type.of(obj).pod. See Type.pod.


orderByDepends ​

static Pod[] orderByDepends(Pod[] pods)

Order a list of pods by their dependencies. This method does not flatten dependencies - see flattenDepends.


props ​

Str:Str props(Uri uri, Duration maxAge)

Convenience for Env.props.


toStr ​

virtual override Str toStr()

Always return name().


type ​

Type? type(Str name, Bool checked := true)

Find a type by name. If the type doesn't exist and checked is false then return null, otherwise throw UnknownTypeErr.


types ​

Type[] types()

List of all the defined types.


uri ​

Uri uri()

Uri for this pod which is always "fan://{name}".


version ​

Version version()

Version number for this pod.


Process ​

class Process : Obj

Process manages spawning external OS processes.

Constructors

makeConstruct a Process instance used to launch an external OS process with the specified command arguments.

Fields

commandCommand argument list used to launch process.
dirWorking directory of process.
errThe output stream used to sink the process stderr.
inThe input stream used to source the process stdin.
mergeErrIf true, then stderr is redirected to the output stream configured via the out field, and the err field is ignored.
outThe output stream used to sink the process stdout.

Methods

envEnvironment variables to pass to new process as a mutable map of string key/value pairs.
joinWait for this process to exit and return the exit code.
killKill this process.
runSpawn this process.

Slot Details ​


command ​

Str[] command

Command argument list used to launch process. The first item is the executable itself, then rest are the parameters.


dir ​

File? dir

Working directory of process.


env ​

Str:Str env()

Environment variables to pass to new process as a mutable map of string key/value pairs. This map is initialized with the current process environment.


err ​

OutStream? err := Env.cur().err

The output stream used to sink the process stderr. Default is to send to Env.err. If set to null, then output is silently consumed like /dev/null. Note this field is ignored if mergeErr is set true, in which case stderr goes to the stream configured via out.


in ​

InStream? in := null

The input stream used to source the process stdin. If null, then the new process will block if it attempts to read stdin. Default is null.


join ​

Int join()

Wait for this process to exit and return the exit code. This method may only be called once after run.


kill ​

This kill()

Kill this process. Returns this.


make ​

new make(Str[] cmd := Str[,], File? dir := null)

Construct a Process instance used to launch an external OS process with the specified command arguments. The first item in the cmd list is the executable itself, then rest are the parameters.


mergeErr ​

Bool mergeErr := true

If true, then stderr is redirected to the output stream configured via the out field, and the err field is ignored. The default is true.


out ​

OutStream? out := Env.cur().out

The output stream used to sink the process stdout. Default is to send to Env.out. If set to null, then output is silently consumed like /dev/null.


run ​

This run()

Spawn this process. See join to wait until the process finishes and to get the exit code. Return this.


Range ​

@Serializable { simple=true } const class Range : Obj

Range represents a contiguous range of integers from start to end. Ranges may be represented as literals in Fantom source code as "start..end" for an inclusive end or "start..<end" for an exclusive range.

Constructors

fromStrParse from string format - inclusive is "start..end", or exclusive is "start..<end".
makeConstructor with start, end, and exclusive flag (all must be non-null).
makeExclusiveConvenience for make(start, end, true).
makeInclusiveConvenience for make(start, end, false).

Methods

containsReturn if this range contains the specified integer.
eachCall the specified function for each integer in the range.
eachWhileIterate every integer in the range until the function returns non-null.
endReturn end index.
equalsReturn true if same start, end, and exclusive.
exclusiveIs the end index exclusive.
firstGet the first value of the range.
hashReturn start ^ end.
inclusiveIs the end index inclusive.
isEmptyReturn if this range contains no integer values.
lastGet the last value of the range.
mapCreate a new list which is the result of calling c for every integer in the range.
maxGet the maximum value of the range.
minGet the minimum value of the range.
offsetCreate a new range by adding offset to this range's start and end values.
randomConvenience for Int.random(this).
startReturn start index.
toListConvert this range into a list of Ints.
toStrIf inclusive return "start..end", if exclusive return "start..<end".

Slot Details ​


contains ​

Bool contains(Int i)

Return if this range contains the specified integer.

Example:

(1..3).contains(2)  =>  true
(1..3).contains(4)  =>  false

each ​

Void each(|Int| c)

Call the specified function for each integer in the range. Also see Int.times.

Example:

(1..3).each |i| { echo(i) }          =>  1, 2, 3
(1..<3).each |i| { echo(i) }         => 1, 2
('a'..'z').each |Int i| { echo(i) }  => 'a', 'b', ... 'z'

eachWhile ​

Obj? eachWhile(|Int->Obj?| c)

Iterate every integer in the range 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 integer in the range.


end ​

Int end()

Return end index.

Example:

(1..3).end  =>  3

equals ​

virtual override Bool equals(Obj? obj)

Return true if same start, end, and exclusive.


exclusive ​

Bool exclusive()

Is the end index exclusive.

Example:

(1..3).exclusive   =>  false
(1..<3).exclusive  =>  true

first ​

Int? first()

Get the first value of the range. If range contains no values then return null. Equivalent to toList.first.


fromStr ​

static new fromStr(Str s, Bool checked := true)

Parse from string format - inclusive is "start..end", or exclusive is "start..<end". If invalid format then throw ParseErr or return null based on checked flag.


hash ​

virtual override Int hash()

Return start ^ end.


inclusive ​

Bool inclusive()

Is the end index inclusive.

Example:

(1..3).inclusive   =>  true
(1..<3).inclusive  =>  false

isEmpty ​

Bool isEmpty()

Return if this range contains no integer values. Equivalent to toList.isEmpty.


last ​

Int? last()

Get the last value of the range. If range contains no values then return null. Equivalent to toList.last.


make ​

new make(Int start, Int end, Bool exclusive)

Constructor with start, end, and exclusive flag (all must be non-null).


makeExclusive ​

new makeExclusive(Int start, Int end)

Convenience for make(start, end, true).


makeInclusive ​

new makeInclusive(Int start, Int end)

Convenience for make(start, end, false).


map ​

Obj?[] map(|Int->Obj?| c)

Create a new list which is the result of calling c for every integer in the range. The new list is typed based on the return type of c.

Example:

(10..15).map |i->Str| { i.toHex }  =>  Str[a, b, c, d, e, f]

max ​

Int? max()

Get the maximum value of the range. If range contains no values then return null. Equivalent to toList.max.


min ​

Int? min()

Get the minimum value of the range. If range contains no values then return null. Equivalent to toList.min.


offset ​

Range offset(Int offset)

Create a new range by adding offset to this range's start and end values.

Example:

(3..5).offset(2)   =>  5..7
(3..<5).offset(-2) =>  1..<3

random ​

Int random()

Convenience for Int.random(this). Also see Int.random, Float.random, List.random, and Random.


start ​

Int start()

Return start index.

Example:

(1..3).start  =>  1

toList ​

Int[] toList()

Convert this range into a list of Ints.

Example:

(2..4).toList   =>  [2,3,4]
(2..<4).toList  =>  [2,3]
(10..8).toList  =>  [10,9,8]

toStr ​

virtual override Str toStr()

If inclusive return "start..end", if exclusive return "start..<end".


ReadonlyErr ​

const class ReadonlyErr : Err

ReadonlyErr indicates an attempt to modify a readonly instance. It is commonly used with List and Map.

Constructors

makeConstruct 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.


Regex ​

@Serializable { simple=true } const class Regex : Obj

Regex represents a regular expression.

Constructors

fromStrCompile a regular expression pattern string.

Fields

defValDefault value is Regex("").

Methods

equalsEquality is based on pattern string and flags.
flagsReturn flags string
globMake a Regex which will match a glob pattern
hashReturn toStr.hash.
matcherReturn a RegexMatcher instance to use for matching operations against the specified string.
matchesConvenience for matcher(s).matches.
quoteMake a Regex that matches the given string exactly.
splitSplit the specified string around matches of this pattern.
toStrReturn the regular expression pattern string.

Slot Details ​


defVal ​

const static Regex defVal

Default value is Regex("").


equals ​

virtual override Bool equals(Obj? obj)

Equality is based on pattern string and flags.


flags ​

Str flags()

Return flags string


fromStr ​

static new fromStr(Str pattern, Str flags := "")

Compile a regular expression pattern string. Flags is a string of ASCII chars. In JavaScript the flags are passed directly to RegExp. In Java the flags are matched against known constants or ignored. The following cross-platform flags are supported:

  • i: case insensitive
  • m: multi-line support for start/end matching
  • s: dot all to allow "." to match newlines

glob ​

static Regex glob(Str pattern)

Make a Regex which will match a glob pattern:

  • "?": match one unknown char (maps to "." in regex)
  • "*": match zero or more unknown char (maps to ".*" in regex)
  • any other character is matched exactly

hash ​

virtual override Int hash()

Return toStr.hash.


matcher ​

RegexMatcher matcher(Str s)

Return a RegexMatcher instance to use for matching operations against the specified string.


matches ​

Bool matches(Str s)

Convenience for matcher(s).matches.


quote ​

static Regex quote(Str str)

Make a Regex that matches the given string exactly. All non-alpha numeric characters are escaped.


split ​

Str[] split(Str s, Int limit := 0)

Split the specified string around matches of this pattern. The limit parameter specifies how many times to apply the pattern:

  • If limit is greater than zero, the pattern is applied at most limit-1 times and any remaining input will be returned as the list's last item.
  • If limit is less than zero, then the pattern is matched as many times as possible.
  • If limit is zero, then the pattern is matched as many times as possible, but trailing empty strings are discarded.

toStr ​

virtual override Str toStr()

Return the regular expression pattern string.


RegexMatcher ​

class RegexMatcher : Obj

RegexMatcher is used in matching operations on a regular expression.

Methods

endReturn end index+1 of the given group.
findAttempt to find the next match.
groupReturn the substring captured by the matching operation.
groupCountReturn the number of capturing groups or zero if no match.
matchesMatch the entire region against the pattern.
replaceAllReplace every sequence which matches the pattern with the given replacement string.
replaceFirstReplace the first sequence which matches the pattern with the given replacment string.
startReturn the start index of the given group.

Slot Details ​


end ​

Int end(Int group := 0)

Return end index+1 of the given group. Throw exception if failed to match input or group index is invalid.


find ​

Bool find()

Attempt to find the next match. If a match is made then return true - additional info is available via the group, start, and end methods. Return false if a match cannot be made.


group ​

Str? group(Int group := 0)

Return the substring captured by the matching operation. Group index zero denotes the entire pattern and capturing groups are indexed from left to right starting at one. Return null if group failed to match part of the input. Throw exception if failed to match input or group index is invalid.


groupCount ​

Int groupCount()

Return the number of capturing groups or zero if no match. Group zero is not included.


matches ​

Bool matches()

Match the entire region against the pattern. If a match is made then return true - additional info is available via the group, start, and end methods. Return false if a match cannot be made.


replaceAll ​

Str replaceAll(Str replacement)

Replace every sequence which matches the pattern with the given replacement string.


replaceFirst ​

Str replaceFirst(Str replacement)

Replace the first sequence which matches the pattern with the given replacment string.


start ​

Int start(Int group := 0)

Return the start index of the given group. Throw exception if failed to match input or group index is invalid.


Serializable ​

@FacetMeta { inherited=true } @Serializable facet class Serializable : Obj, Facet

Serializable is a facet used to annotate types which can be serialized. Objects are serialized via OutStream.writeObj and deserialized via InStream.readObj.

See the Serialization Doc for details.

Fields

collectionCollections are serialized with a collection of child objects using the following rules where Item is the item type
simpleSimples are serialized atomically via a customized string representation using the following rules

Slot Details ​


collection ​

const Bool collection := false

Collections are serialized with a collection of child objects using the following rules where Item is the item type:

  • Provide an add(Item) method to add child items during readObj
  • Provide an each(|Item| f) method to iterate child items during writeObj

simple ​

const Bool simple := false

Simples are serialized atomically via a customized string representation using the following rules:

  • Override Obj.toStr to return a suitable string representation of the object.
  • Must declare a static method called fromStr which takes one Str parameter and returns an instance of the declaring type. The fromStr method may contain additional parameters if they declare defaults.

Service ​

const mixin Service

Services are used to publish functionality in a VM for use by other software components. The service registry for the VM is keyed by public types each service implements.

The following table illustrates the service lifecycle:

Method        isInstalled  isRunning
-----------   -----------  ----------
constructed   false        false
install       true         false
start         true         true
stop          true         false
uninstall     false        false

While the service is installed, it may be looked up in the registry via find and findAll. The running state is used to invoke the onStart and onStop callbacks which gives the service a chance to setup/shutdown its actors and associated resources.

Methods

equalsServices are required to implement equality by reference.
findFind an installed service by type.
findAllFind all services installed for the given type.
hashServices are required to implement equality by reference.
installInstall this service into the VM's service registry.
isInstalledIs the service in the installed state.
isRunningIs the service in the running state.
listList all the installed services.
onStartCallback when service transitions into running state.
onStopCallback when service transitions out of the running state.
startStart this service.
stopStop this service.
uninstallUninstall this service from the VM's service registry.

Slot Details ​


equals ​

override Bool equals(Obj? that)

Services are required to implement equality by reference.


find ​

static Service? find(Type t, Bool checked := true)

Find an installed service by type. If not found and checked is false return null, otherwise throw UnknownServiceErr. If multiple services are registered for the given type then return the first one registered.


findAll ​

static Service[] findAll(Type t)

Find all services installed for the given type. If no services are found then return an empty list.


hash ​

override Int hash()

Services are required to implement equality by reference.


install ​

This install()

Install this service into the VM's service registry. If already installed, do nothing. Return this.


isInstalled ​

Bool isInstalled()

Is the service in the installed state. Note this method requires accessing a global hash table, so it should not be heavily polled in a concurrent environment.


isRunning ​

Bool isRunning()

Is the service in the running state. Note this method requires accessing a global hash table, so it should not be heavily polled in a concurrent environment.


list ​

static Service[] list()

List all the installed services.


onStart ​

protected virtual Void onStart()

Callback when service transitions into running state. If this callback raises an exception, then the service fails to transition to the running state.


onStop ​

protected virtual Void onStop()

Callback when service transitions out of the running state. If this callback raises an exception, then the service is still transitioned to the non-running state.


start ​

This start()

Start this service. If not installed, this method automatically calls install. If already running, do nothing. Return this.


stop ​

This stop()

Stop this service. If not running, do nothing. Return this.


uninstall ​

This uninstall()

Uninstall this service from the VM's service registry. If the service is running, this method automatically calls stop. If not installed, do nothing. Return this.