## Reading from a `trn` variable

This is like `iso`, but with a weaker guarantee (_write uniqueness_ as opposed to _read and write uniqueness_). That makes a big difference since now we can return something readable when we enforce our guarantees.

An `iso` field makes stronger guarantees than `trn`, and can't alias anything readable inside the `trn` origin, so it's perfectly safe to read.

On the other hand, `trn` and `ref` fields have to be returned as `box`. It might seem a bit odd that `trn` has to be returned as `box`, since after all it guarantees write uniqueness itself and we might expect it to behave like `iso`. The issue is that `trn`, unlike `iso`, *can* alias with some `box` variables in the origin. And that `trn` origin still has to make the guarantee that nothing else can write to fields that it can read. On the other hand, `trn` still can't be returned as `val`, because then we might leave the original field in place and create a `val` alias, while that field can still be used to write! So we have to view it as `box`.

Immutable and opaque capabilities, though, can never violate write uniqueness, so `val`, `box`, and `tag` are viewed as themselves.


fun box sock_client()
: U64 val

Returns¶

U64 val

sock_server¶
[Source]
fun box sock_server()
: U64 val

Returns¶

U64 val

mac_get¶
[Source]


fun box sctp_pcb_flags_in_tcppool()
: I32 val

Returns¶

I32 val

sctp_pcb_flags_multiple_asconfs¶
[Source]
fun box sctp_pcb_flags_multiple_asconfs()
: I32 val

Returns¶

I32 val

sctp_pcb_flags_needs_mapped_v4¶
[Source]


List[A: A]¶
[Source]
A doubly linked list.
The following is paraphrased from Wikipedia.
A doubly linked list is a linked data structure that consists of a set of sequentially
linked records called nodes (implemented in Pony via the collections.ListNode class). Each
node contains four fields: two link fields (references to the previous and to the next node in
the sequence of nodes), one data field, and the reference to the List in which it resides. A doubly
linked list can be conceptualized as two singly linked lists formed from the same data items, but
in opposite sequential orders.
As you would expect. functions are provided to perform all the common list operations such as
creation, traversal, node addition and removal, iteration, mapping, filtering, etc.
Example program¶


_edit = strings.CommonPrefix(r)
end_key()
end

fun ref _dispatch(term: ANSITerm) =>
"""
Send a finished line to the notifier.
"""
if _edit.size() > 0 then
let line: String = _edit = recover String end

if _blocked then
_queue.push(line)
else
_add_history(line)
_out.write("\n")
_handle_line(term, line)
end
end


Returns¶

String val

magenta_bg¶
[Source]
Magenta background.
fun box magenta_bg()
: String val

Returns¶

String val

cyan_bg¶
[Source]
Cyan background.
fun box cyan_bg()


Returns¶

None val

delete¶
[Source]
fun ref delete(
ctrl: Bool val,
alt: Bool val,
shift: Bool val)
: None val

Parameters¶

ctrl: Bool val
alt: Bool val
shift: Bool val


132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151


F64 val

compare¶
[Source]
fun box compare(
that: ISize val)
: (Less val | Equal val | Greater val)

Parameters¶

that: ISize val

Returns¶

(Less val | Equal val | Greater val)


U128 val ?

mod_unsafe¶
[Source]
fun box mod_unsafe(
y: U128 val)
: U128 val

Parameters¶

y: U128 val

Returns¶

U128 val

shl_unsafe¶
[Source]


primitive Foo
fun object_wrong(f: Factory, o1: Option, o2: Option): Object =>
f.>add_option(o1).>add_option(o2).>make_object() // Error! The expression returns a Factory

fun object_right(f: Factory, o1: Option, o2: Option): Object =>
f.>add_option(o1).>add_option(o2).make_object() // Works. The expression returns an Object
```


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51


from: String box,
to: String box,
n: USize val = 0)
: USize val

Parameters¶

from: String box
to: String box
n: USize val = 0

Returns¶

USize val

split_by¶
[Source]
Split the string into an array of strings that are delimited by delim in
the original string. If n > 0, then the split count is limited to n.


# Type Aliases

A __type alias__ is just a way to give a different name to a type. This may sound a bit silly: after all, types already have names! However, Pony can express some complicated types, and it can be convenient to have a short way to talk about them.

We'll give a couple examples of using type aliases, just to get the feel of them.


This might error, which does not necessarily mean that the Iterator is exhausted.
"""


fun box exit_code()
: I32 val

Returns¶

I32 val

string¶
[Source]
fun box string()
: String iso^

Returns¶

String iso^

eq¶
[Source]


_out.write("\n")
term.dispose()
else
delete()
end
| 0x05 => end_key() // ctrl-e
| 0x06 => right() // ctrl-f
| 0x08 => _backspace() // ctrl-h
| 0x09 => _tab()
| 0x0A => _dispatch(term) // LF
| 0x0B =>
// ctrl-k, delete to the end of the line.
_edit.truncate(_cur_pos.usize())
| 0x0C => _clear() // ctrl-l
| 0x0D => _dispatch(term) // CR
| 0x0E => down() // ctrl-n
| 0x10 => up() // ctrl-p
| 0x14 => _swap() // ctrl-t
| 0x15 =>
// ctrl-u, delete the whole line.


[Source]
Called when data is sent on the connection. This gives the notifier an
opportunity to modify sent data before it is written. To swallow data,
return an empty string.
fun ref sent(
conn: TCPConnection ref,
data: (String val | Array[U8 val] val))
: (String val | Array[U8 val] val)

Parameters¶

conn: TCPConnection ref
data: (String val | Array[U8 val] val)

Returns¶

(String val | Array[U8 val] val)

sentv¶


end

for g in _groups.values() do
if g._1 == name then
return g._2
end
end

// Group doesn't exist yet, make it.
// We only need one simultaneous group, which we've already made. All new
// groups are exclusive.
let g = _ExclusiveGroup
_groups.push((name, g))
g

be _test_started(id: USize) =>
"""
A test has started running, update status info.
The id parameter is the test identifier handed out when we created the test
helper.


Add K, V pairs from the iterator to the map.
fun ref concat(
iter: Iterator[(K^ , V^)] ref)
: None val

Parameters¶

iter: Iterator[(K^ , V^)] ref

Returns¶

None val

add[optional H2: HashFunction[this->K!] val]¶
[Source]
This with the new (key, value) mapping.
fun box add[optional H2: HashFunction[this->K!] val](
key: this->K!,
value: this->V!)


pony_bench.pony

1
2
3
4
5
6
7
8
9
10
11


new ref create(name': String, level: U64) =>
name = name'
_hunger_level = level

fun ref set_hunger_level(hunger_level: U64) =>
_hunger_level = hunger_level // Ok, _hunger_level is of var type

fun ref set_name(name' : String) =>
name = name' // Error, can't assign to a let definition more than once
```

__Can field declarations appear after methods?__ No. If `var` or `let` keywords appear after a `fun` or `be` declaration, they will be treated as variables within the method body rather than fields within the type declaration. As a result, fields must appear prior to methods in the type declaration


if den <= num then
num = num - den
quot = quot + qbit
end

den = den >> 1
qbit = qbit >> 1
end
(quot, num)
end

fun div(y: U128): U128 =>
ifdef native128 then
this / y
else
(let q, let r) = divrem(y)
q
end

fun rem(y: U128): U128 =>


Return an iterator that only returns items that match the predicate `f`.


Iter[T1^](shrinks1).zip2[T2^, T3^](shrinks2, shrinks3))

fun shrink(t: (T1, T2, T3)): ValueAndShrink[(T1, T2, T3)] =>
(let t1, let t2, let t3) = consume t
(let t11, let t1_shrunken: Iterator[T1^]) = gen1.shrink(consume t1)
(let t21, let t2_shrunken: Iterator[T2^]) = gen2.shrink(consume t2)
(let t31, let t3_shrunken: Iterator[T3^]) = gen3.shrink(consume t3)

let shrunken = Iter[T1^](t1_shrunken).zip2[T2^, T3^](t2_shrunken, t3_shrunken)
((consume t11, consume t21, consume t31), shrunken)
end)

fun zip4[T1, T2, T3, T4](
gen1: Generator[T1],
gen2: Generator[T2],
gen3: Generator[T3],
gen4: Generator[T4])
: Generator[(T1, T2, T3, T4)]
=>
"""


fun box tcpopt_eol()
: I32 val

Returns¶

I32 val

tcpopt_fastopen¶
[Source]
fun box tcpopt_fastopen()
: I32 val

Returns¶

I32 val

tcpopt_fast_open¶
[Source]


## Variadic C functions

Some C functions are variadic, that is, they can take a variable number of parameters. To interact with these functions, you should also specify that fact in the FFI signature:

```pony
use @printf[I32](fmt: Pointer[U8] tag, ...)
// ...
let run_ns: I64 = _current_t - _last_t
let rate: I64 = (_partial_count.i64() * 1_000_000_000) / run_ns
@printf("Elapsed: %lld,%lld\n".cstring(), run_ns, rate)
```

In the example above, the compiler will type-check the first argument to `printf`, but will not be able to check any other argument, since it lacks the necessary type information. It is __very__ important that you use `...` in the FFI signature if the corresponding C function is variadic: if you don't, the compiler might generate a program that is incorrect or crash on some platforms while appearing to work correctly on others.


"""
if _available >= n then
_available = _available - n
var rem = n

while rem > 0 do
let node = _chunks.head()?
(var data, var offset) = node()?
let avail = data.size() - offset

if avail > rem then
node()? = (data, offset + rem)
break
end

rem = rem - avail
_chunks.shift()?
end

else


contains¶
[Source]
Check whether the node contains the provided key.
fun val contains(
k: K)
: Bool val

Parameters¶

k: K

Returns¶

Bool val

concat¶
[Source]


132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147"""


fun box u128_unsafe()
: U128 val

Returns¶

U128 val

ulong_unsafe¶
[Source]
fun box ulong_unsafe()
: ULong val

Returns¶

ULong val

usize_unsafe¶
[Source]


USize val

f32_unsafe¶
[Source]
fun box f32_unsafe()
: F32 val

Returns¶

F32 val

f64_unsafe¶
[Source]
fun box f64_unsafe()
: F64 val

Returns¶


212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231


s(i)? = '/'
end

i = i + 1
end
end

s
else
path
end

fun canonical(path: String): String ? =>
"""
Return the equivalent canonical absolute path. Raise an error if there
isn't one.
"""
let cstring = @pony_os_realpath(path.cstring())

if cstring.is_null() then


: Bool val

Parameters¶

that: PonyCheck val

Returns¶

Bool val

ne¶
[Source]
fun box ne(
that: PonyCheck val)
: Bool val

Parameters¶

that: PonyCheck val


412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431


args': Array[ArgSpec] box = Array[ArgSpec]()) ?
=>
"""
Creates a command spec that can accept options and arguments, but not child
commands.
"""
_type = _CommandSpecLeaf
_name = _assertName(name')?
_descr = descr'
for o in options'.values() do
_options.update(o.name(), o)
end
for a in args'.values() do
_args.push(a)
end

fun tag _assertName(nm: String): String ? =>
for b in nm.values() do
if (b != '-') and (b != '_') and
not ((b >= '0') and (b <= '9')) and


USize val

divrem_unsafe¶
[Source]
fun box divrem_unsafe(
y: USize val)
: (USize val , USize val)

Parameters¶

y: USize val

Returns¶

(USize val , USize val)

rem_unsafe¶
[Source]


state: Bool val

set_multicast_interface¶
[Source]
By default, the OS will choose which address is used to send packets bound
for multicast addresses. This can be used to force a specific interface. To
revert to allowing the OS to choose, call with an empty string.
be set_multicast_interface(
from: String val = "")

Parameters¶

from: String val = ""

set_multicast_loopback¶
[Source]
By default, packets sent to a multicast address will be received by the
sending system if it has subscribed to that address. Disabling loopback


fun box netlink_selinux()
: I32 val

Returns¶

I32 val

netlink_sock_diag¶
[Source]
fun box netlink_sock_diag()
: I32 val

Returns¶

I32 val

netlink_tx_ring¶
[Source]


new val string_seq(
name': String,
descr': String = "")
=>
"""
Creates an Arg with a ReadSeq[String] typed value that can be used like
`<cmd> file1 file2 file3`
to yield a sequence of three strings equivalent to
`cmd.arg("file").string_seq() (equiv) ["file1"; "file2"; "file3"]`.
"""
_name = name'
_descr = descr'
(_typ, _default, _required) = _init(_StringSeqType, _StringSeq.empty())

fun name(): String =>
"""
Returns the name of this arg.
"""
_name


Implements¶

Property1[IntPropertySample ref] ref

Public Functions¶
gen¶
[Source]
fun box gen()
: Generator[IntPropertySample ref] box

Returns¶

Generator[IntPropertySample ref] box

property¶
[Source]
fun ref property(


# As Operator

The `as` operator in Pony has two related uses. First, it provides a safe way to increase the specificity of an object's type. Second, it gives the programmer a way to specify the type of the items in an array literal.


n = n + 1
end
end

fun ref clear() =>
"""
Truncate the string to zero length.
"""
_set(0, 0)
_size = 0

fun insert(offset: ISize, that: String): String iso^ =>
"""
Returns a version of the string with the given string inserted at the given
offset.
"""
let s = clone()
s.insert_in_place(offset, that)
s


end

list.benchmarks(this)

be apply(bench: Benchmark) =>
match consume bench
| let b: MicroBenchmark =>
_bench_q.push((b.overhead(), true))
_bench_q.push((consume b, false))
| let b: AsyncMicroBenchmark =>
_bench_q.push((b.overhead(), true))
_bench_q.push((consume b, false))
end

if not _running then
_running = true
_next_benchmark()
end

be _next_benchmark() =>


232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251


Returns¶

None val

reserve_current¶
[Source]
Reserve space for size bytes in _current.
fun ref reserve_current(
size': USize val)
: None val

Parameters¶

size': USize val

Returns¶

None val


_SignedUnsafeArithmetic.mod_unsafe[I16, U16](this, y)

fun addc(y: I16): (I16, Bool) =>
@"llvm.sadd.with.overflow.i16"(this, y)

fun subc(y: I16): (I16, Bool) =>
@"llvm.ssub.with.overflow.i16"(this, y)

fun mulc(y: I16): (I16, Bool) =>
@"llvm.smul.with.overflow.i16"(this, y)

fun divc(y: I16): (I16, Bool) =>
_SignedCheckedArithmetic.div_checked[I16, U16](this, y)

fun remc(y: I16): (I16, Bool) =>
_SignedCheckedArithmetic.rem_checked[I16, U16](this, y)

fun fldc(y: I16): (I16, Bool) =>
_SignedCheckedArithmetic.fld_checked[I16, U16](this, y)


The `Connect` actor uses this derived authority when it creates a TCP connection:

```pony
TCPConnection(auth, MyTCPConnectionNotify(out), "example.com", "80")
```

The `TCPConnection` requires an authority as first parameter, and since the compiler checks that the correct type was passed, this guarantees that a `TCPConnection` can only be created by an actor holding the required authorization.

The implementation of the `TCPConnection` constructor does not even use the authorization parameter at run time, all it does is require it to be of the right type. The type checking done by the compiler is sufficient for this guarantee.


bright_green_bg¶
[Source]
Bright green background.
fun box bright_green_bg()
: String val

Returns¶

String val

bright_yellow_bg¶
[Source]
Bright yellow background.
fun box bright_yellow_bg()
: String val

Returns¶

String val


y: U16 val

Returns¶

Bool val

hash¶
[Source]
fun box hash()
: USize val

Returns¶

USize val

hash64¶
[Source]


process: ProcessMonitor ref
data: Array[U8 val] iso

Returns¶

None val

stderr¶
[Source]
ProcessMonitor calls this when new data is received on STDERR of the
forked process
fun ref stderr(
process: ProcessMonitor ref,
data: Array[U8 val] iso)
: None val

Parameters¶

process: ProcessMonitor ref


match child_exit_status
| let exited: Exited =>
_env.out.print("Child exit code: " + exited.exit_code().string())
| let signaled: Signaled =>
_env.out.print("Child terminated by signal: " + signaled.signal().string())
end

Process portability¶
The ProcessMonitor supports spawning processes on Linux, FreeBSD, OSX and
Windows.
Shutting down ProcessMonitor and external process¶
When a process is spawned using ProcessMonitor, and it is not necessary to
communicate to it any further using stdin and stdout or stderr, calling
done_writing() will close stdin to
the child process. Processes expecting input will be notified of an EOF on
their stdin and can terminate.
If a running program needs to be canceled and the
ProcessMonitor should be shut down, calling
dispose will terminate the child process
and clean up all resources.


new create(value: U32) => value
new from[A: (Number & Real[A] val)](a: A) => a.u32()

new min_value() => 0
new max_value() => 0xFFFF_FFFF

fun next_pow2(): U32 =>
let x = (this - 1).clz()
1 << (if x == 0 then 0 else bitwidth() - x end)

fun abs(): U32 => this
fun bit_reverse(): U32 => @"llvm.bitreverse.i32"(this)
fun bswap(): U32 => @"llvm.bswap.i32"(this)
fun popcount(): U32 => @"llvm.ctpop.i32"(this)
fun clz(): U32 => @"llvm.ctlz.i32"(this, false)
fun ctz(): U32 => @"llvm.cttz.i32"(this, false)

fun clz_unsafe(): U32 =>
"""
Unsafe operation.


fun box rem_unsafe(
y: I32 val)
: I32 val

Parameters¶

y: I32 val

Returns¶

I32 val

neg_unsafe¶
[Source]
fun box neg_unsafe()
: I32 val

Returns¶


Generator[box->T](
object is GenObj[box->T]
fun generate(rnd: Randomness): GenerateResult[box->T] ? =>
let idx = rnd.usize(0, xs.size() - 1)
let res = xs(idx)?
if do_shrink then
(res, Iter[box->T].repeat_value(res))
else
res
end
end)

fun one_of_safe[T](xs: ReadSeq[T], do_shrink: Bool = false): Generator[box->T] ? =>
"""
Version of `one_of` that will error if `xs` is empty.
"""
Fact(xs.size() > 0, "cannot use one_of_safe on empty ReadSeq")?
Generators.one_of[T](xs, do_shrink)


Returns¶

UDPSocket tag^

ip4¶
[Source]
Listens for IPv4 datagrams.
new tag ip4(
auth: UDPAuth val,
notify: UDPNotify iso,
host: String val = "",
service: String val = "0",
size: USize val = 1024)
: UDPSocket tag^

Parameters¶

auth: UDPAuth val


u128¶
[Source]
A random integer in [0, 2^128)
fun ref u128()
: U128 val

Returns¶

U128 val

ulong¶
[Source]
A random integer in [0, ULong.max_value()]
fun ref ulong()
: ULong val

Returns¶


USize val

bytewidth¶
[Source]
fun box bytewidth()
: USize val

Returns¶

USize val

min¶
[Source]
fun box min(
y: ISize val)
: ISize val


832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851


fun ref _read_line(): String iso^ ? =>
let line = _reader.line(where keep_line_breaks = true)?
let len = line.size()
_last_line_length = len

// advance the cursor to the end of the returned line
_inc_public_file_cursor(len)

// strip trailing line break
line.truncate(
len - if (len >= 2) and (line.at_offset(-2)? == '\r') then 2 else 1 end)
consume line

fun ref _fill_buffer(): Bool =>
"""
read from file and fill the reader-buffer.

Returns `true` if data could be read from the file.


fun head(): val->A =>
"""
Returns the head of the list.
"""
_head

fun tail(): List[A] =>
"""
Returns the tail of the list.
"""
_tail

fun val reverse(): List[A] =>
"""
Builds a new list by reversing the elements in the list.
"""
_reverse(this, Nil[A])

fun val _reverse(l: List[A], acc: List[A]): List[A] =>
"""


Parameters¶

y: ISize val

Returns¶

(ISize val , ISize val)

rem¶
[Source]
fun box rem(
y: ISize val)
: ISize val

Parameters¶

y: ISize val

Returns¶


# Semicolons

In Pony, you don't end an expression with a `;`, unlike C, C++, Java, C#, etc. In fact, you don't need to end it at all! The compiler knows when an expression has finished, like Python or Ruby.

However, sometimes it's convenient to put more than one expression on the same line. When you want to do that, you __must__ separate them with a `;`.

__Why? Can't the compiler tell an expression has finished?__ Yes, it can. The compiler doesn't really need the `;`. However, it turns out the programmer does! By requiring a `;` between expressions on the same line, the compiler can catch some pretty common syntax errors for you.


Find the `nth` appearance of `value` from the beginning of the vector,
starting at `offset` and examining higher indices, and using the
supplied `predicate` for comparisons. Returns the index of the value, or
raise an error if the value isn't present.

By default, the search starts at the first element of the vector,
returns the first instance of `value` found, and uses object identity
for comparison.
"""
var n: USize = 0
for i in mut.Range(offset, _size) do
if predicate(this(i)?, value) then
if n == nth then return i end
n = n + 1
end
end
error

fun val contains(
value: val->A,


I16 val

i32¶
[Source]
fun box i32()
: I32 val

Returns¶

I32 val

i64¶
[Source]
fun box i64()
: I64 val

Returns¶


y: A

Returns¶

(A , A)

rem¶
[Source]
fun box rem(
y: A)
: A

Parameters¶

y: A

Returns¶


fun box netlink_iscsi()
: I32 val

Returns¶

I32 val

netlink_kobject_uevent¶
[Source]
fun box netlink_kobject_uevent()
: I32 val

Returns¶

I32 val

netlink_listen_all_nsid¶
[Source]


372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391


Hashable64¶
[Source]
A version of Hashable that returns 64-bit hashes on every platform.
interface ref Hashable64

Public Functions¶
hash64¶
[Source]
fun box hash64()
: U64 val

Returns¶


92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111


primitive ASCIIAll
"""
Represents all ASCII characters,
excluding the NUL (\x00) character for its special treatment in C strings.
"""
fun apply(): String =>
ASCIIPrintable() + ASCIINonPrintable()

primitive ASCIIAllWithNUL
"""
Represents all ASCII characters,
including the NUL (\x00) character for its special treatment in C strings.
"""
fun apply(): String =>
ASCIIAll() + ASCIINUL()

type ASCIIRange is
( ASCIINUL
| ASCIIDigits
| ASCIIWhiteSpace


asio_event.pony

1
2
3
4
5
6
7
8
9
10
11


+ my_list_node.apply()?) // My Node item
end

// Update the item contained in the ListNode
try
my_list_node.update("My updated Node item")?
env.out.print("My node has the updated item value: "
+ my_list_node.apply()?) // My updated Node item
end
// Pop the item from the ListNode
try
my_list_node.pop()?
env.out.print("Popped the item from the ListNode")
my_list_node.apply()? // This will error as the item is now None
else
env.out.print("The ListNode has no (None) item.")
end
```
"""
var _item: (A | None)


232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251


572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591


## Unsafe Integer Arithmetic

Unsafe integer arithmetic comes close to what you can expect from integer arithmetic in C. No checks, _raw speed_, possibilities of overflow, underflow or division by zero. Like in C, overflow, underflow and division by zero scenarios are undefined. Don't rely on the results in these cases. It could be anything and is highly platform specific. Division by zero might even crash your program with a `SIGFPE`. Our suggestion is to use these operators only if you can make sure you can exclude these cases.

Here is a list with all unsafe operations defined on Integers:

---

| Operator | Method       | Undefined in case of                                          |
| -------- | ------------ | ------------------------------------------------------------- |
| `+~`     | `add_unsafe()` | Overflow  E.g. `I32.max_value() +~ I32(1)`                    |
| `-~`     | `sub_unsafe()` | Overflow                                                      |
| `*~`     | `mul_unsafe()` | Overflow.                                                     |
| `/~`     | `div_unsafe()` | Division by zero and overflow. E.g. `I32.min_value() / I32(-1)` |
| `%~`     | `rem_unsafe()` | Division by zero and overflow.                                |
| `%%~`    | `mod_unsafe()` | Division by zero and overflow.                                |
| `-~`     | `neg_unsafe()` | Overflow. E.g. `-~I32.max_value()`                            |
| `>>~`    | `shr_unsafe()` | If non-zero bits are shifted out. E.g. `I32(1) >>~ U32(2)`    |
| `<<~`    | `shl_unsafe()` | If bits differing from the final sign bit are shifted out.    |


```

This produces the same code as:

```pony
object iso
fun apply(s: String): String => "lambda: " + s
end
```

Lambdas can be used to capture from the lexical scope in the same way as object literals can assign from the lexical scope to a field. This is done by adding a second argument list after the parameters:

```pony
class Foo
new create(env:Env) =>
foo({(s: String)(env) => env.out.print(s) })

fun foo(f: {(String)}) =>
f("Hello World")
```


```

Thinking of the `as` keyword as "an attempt to match that will error if not matched" is a good mental model to have. If you don't care about handling the "not matched" case that causes an error when using `as`, you can rewrite an `as` to use match without an error like:

```pony
actor Main
new create(env: Env) =>
let anys = Array[Any ref].>push(Wombat).>push(Capybara)
for any in anys.values() do
match any
| let critter: Critter =>
env.out.print(critter.wash())
end
end
```

You can learn more about matching on type in the [captures section of the match documentation](/pattern-matching/match.md#captures).


size¶
[Source]
The number of elements in the array.
fun box size()
: USize val

Returns¶

USize val

space¶
[Source]
The available space in the array.
fun box space()
: USize val

Returns¶


// do a trim in place instead of a clear to free up memory
_pending_writev_windows.trim_in_place(_pending_writev_windows.size())
_pending_sent = 0
else
// do a trim in place instead of a clear to free up memory
_pending_writev_posix.trim_in_place(_pending_writev_posix.size())
end
return true
else
ifdef windows then
// do a trim in place instead of many shifts for efficiency
_pending_writev_windows.trim_in_place(num_to_send)
_pending_sent = _pending_sent - num_to_send
else
// do a trim in place instead of many shifts for efficiency
_pending_writev_posix.trim_in_place(num_to_send)
end
end
end


252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271


# Floating Point

Pony default arithmetic on floating point numbers (`F32`, `F64`) behave as defined in the floating point standard IEEE 754.

That means e.g. that division by `+0` returns `Inf` and by `-0` returns `-Inf`.


is not accounted for. As a result iterating with this class will always return the full
file content without gaps or repeated lines.

`min_read_size` determines the minimum amount of bytes to read from the file
in one go. This class keeps track of the line lengths in the current file
and uses the length of the last line as amount of bytes to read next, but it
will never read less than `min_read_size`.
"""
_file = file
_buffer_cursor = _file.position()
_cursor = _file.position()
_min_read_size = min_read_size
_last_line_length = min_read_size
_has_next = _file.valid()

fun ref has_next(): Bool =>
_has_next

fun ref next(): String iso^ ? =>
"""


72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91


Set index i and return the previous value.
"""
compile_intrinsic

fun _offset(n: USize): this->Pointer[A] =>
"""
Return a pointer to the n-th element.
"""
compile_intrinsic

fun tag offset(n: USize): Pointer[A] tag =>
"""
Return a tag pointer to the n-th element.
"""
_unsafe()._offset(n)

fun tag _element_size(): USize =>
"""
Return the size of a single element in an array of type A.
"""


Parses all of the command line tokens and env vars and returns a Command,
or the first SyntaxError.
"""
let tokens = argv.clone()
try tokens.shift()? end  // argv[0] is the program name, so skip it
let options: Map[String,Option] ref = options.create()
let args: Map[String,Arg] ref = args.create()
_parse_command(
tokens, options, args,
EnvVars(envs, _spec.name().upper() + "_", true),
false)

fun _fullname(): String =>
match _parent
| let p: CommandParser box => p._fullname() + "/" + _spec.name()
else
_spec.name()
end

fun _root_spec(): CommandSpec box =>


IntUnitTest¶
[Source]
type IntUnitTest is
Property1UnitTest[IntPropertySample ref] iso

Type Alias For¶

Property1UnitTest[IntPropertySample ref] iso


fun box f64_unsafe()
: F64 val

Returns¶

F64 val

compare¶
[Source]
fun box compare(
that: I8 val)
: (Less val | Equal val | Greater val)

Parameters¶

that: I8 val

Returns¶


F64 val) & Real[B] val)](
a: B)
: Real[A] val^

Parameters¶

a: B

Returns¶

Real[A] val^

min_value¶
[Source]
new val min_value()
: Real[A] val^

Returns¶


fun box rds_cmsg_rdma_dest()
: I32 val

Returns¶

I32 val

rds_cmsg_rdma_map¶
[Source]
fun box rds_cmsg_rdma_map()
: I32 val

Returns¶

I32 val

rds_cmsg_rdma_status¶
[Source]


: NetAddress val

Returns¶

NetAddress val

expect¶
[Source]
A received call on the notifier must contain exactly qty bytes. If
qty is zero, the call can contain any amount of data. This has no effect
if called in the sent notifier callback.
Errors if qty exceeds the max buffer size as indicated by the
read_buffer_size supplied when the connection was created.
fun ref expect(
qty: USize val = 0)
: None val ?

Parameters¶


### Fixed Versus Variable Object Sizes

The programmer must write their custom serialisation and deserialisation code in such a way that it is aware of how many bytes are available in the byte arrays that are passed to the methods. If the objects are always of a fixed size then the functions can read and write that many bytes to the buffer. However, if the objects are of varying sizes (for example, if the object was a string), then the serialized representation must include information that the deserialisation code can use to ensure that it does not read beyond the end of the memory occupied by the object. The custom serialisation system does not provide a mechanism for doing this, so it is up to the program to choose a mechanism and implement it. In the case of a string, the serialisation format could consist of a 4-byte header that encodes the length of the string, followed by a string of the specified length. These additional four bytes must be included in the value returned by `_serialise_space()`. The deserialisation function would then start by reading the first four bytes of the array to obtain the size of the string and then read only that many bytes from the array.


I16 val

abs¶
[Source]
fun box abs()
: F32 val

Returns¶

F32 val

ceil¶
[Source]
fun box ceil()
: F32 val

Returns¶


DebugErr¶
[Source]
primitive val DebugErr

Constructors¶
create¶
[Source]
new val create()
: DebugErr val^

Returns¶

DebugErr val^


sock: UDPSocket ref)
: None val

Parameters¶

sock: UDPSocket ref

Returns¶

None val

received¶
[Source]
Called when new data is received on the socket.
fun ref received(
sock: UDPSocket ref,
data: Array[U8 val] iso,
from: NetAddress val)
: None val


var z = x._2
```

Note that there's no way to assign to an element of a tuple. Instead, you can just reassign the entire tuple, like this:

```pony
x = ("wombat", x._2)
```

__Why use a tuple instead of a class?__ Tuples are a way to express a collection of values that doesn't have any associated code or expected behaviour. Basically, if you just need a quick collection of things, maybe to return more than one value from a function, for example, you can use a tuple.


312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331


292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311


usize¶
fun box usize()
: USize val

Returns¶

USize val

f32¶
fun box f32()
: F32 val

Returns¶

F32 val

f64¶


fun box size()
: USize val

Returns¶

USize val

space¶
[Source]
The available space in the set.
fun box space()
: USize val

Returns¶

USize val

apply¶


fun box tcpolen_cc()
: I32 val

Returns¶

I32 val

tcpolen_cc_appa¶
[Source]
fun box tcpolen_cc_appa()
: I32 val

Returns¶

I32 val

tcpolen_eol¶
[Source]


FormatUTF32¶
[Source]
primitive val FormatUTF32 is
FormatSpec val

Implements¶

FormatSpec val

Constructors¶
create¶
[Source]


352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371


2. An undefined value that must be ignored.
Usage example:
// listening() is a callback function for class UDPNotify
fun ref listening(sock: UDPSocket ref) =>
match sock.getsockopt(OSSockOpt.sol_socket(), OSSockOpt.so_rcvbuf(), 4)
| (0, let gbytes: Array[U8] iso) =>
try
let br = Reader.create().>append(consume gbytes)
ifdef littleendian then
let buffer_size = br.u32_le()?
else
let buffer_size = br.u32_be()?
end
end
| (let errno: U32, _) =>
// System call failed
end

fun ref getsockopt(
level: I32 val,


I16 val

popcount¶
[Source]
fun box popcount()
: U16 val

Returns¶

U16 val

clz¶
[Source]
fun box clz()
: U16 val

Returns¶


F32 val

fld¶
[Source]
fun box fld(
y: F32 val)
: F32 val

Parameters¶

y: F32 val

Returns¶

F32 val

fld_unsafe¶
[Source]


gt¶
[Source]
fun tag gt(
that: Pointer[A] tag)
: Bool val

Parameters¶

that: Pointer[A] tag

Returns¶

Bool val

hash¶
[Source]
Returns a hash of the address.


Bool val

ne¶
[Source]
fun box ne(
that: FormatExpLarge val)
: Bool val

Parameters¶

that: FormatExpLarge val

Returns¶

Bool val


MapIs[K: Any #share, V: Any #share]¶
[Source]
A map that uses identity comparison on the key.
type MapIs[K: Any #share, V: Any #share] is
HashMap[K, V, HashIs[K] val] val

Type Alias For¶

HashMap[K, V, HashIs[K] val] val


.find({(x) => (x % 2) == 0 })

2
Iter[I64]([1; 2; 3; 4].values())
.find({(x) => (x % 2) == 0 }, 2)

4
fun ref find(
f: {(A!): Bool ?}[A] box,
n: USize val = 1)
: A! ?

Parameters¶

f: {(A!): Bool ?}[A] box
n: USize val = 1

Returns¶

A! ?


out.push(pad)
end

out.push(pad)
end

if lineblocks > 0 then
out.append(linesep)
end
else
out.clear()
end

out

fun decode_url[A: Seq[U8] iso = Array[U8] iso](data: ReadSeq[U8]): A^ ? =>
"""
Decode for URLs (RFC 4648).
"""
decode[A](data, '-', '_')?


None val

connected¶
[Source]
Called when we have successfully connected to the server.
fun ref connected(
conn: TCPConnection ref)
: None val

Parameters¶

conn: TCPConnection ref

Returns¶

None val

connect_failed¶


try
_stdin = _Pipe.outgoing()?
else
_stdin.close()
_notifier.failed(this, ProcessError(PipeError,
"Failed to open pipe for stdin."))
return
end

try
_stdout = _Pipe.incoming()?
else
_stdin.close()
_stdout.close()
_notifier.failed(this, ProcessError(PipeError,
"Failed to open pipe for stdout."))
return
end

try


try
let i = path.rfind(separator)?.usize()
(clean(path.trim(0, i)), path.trim(i+separator.size()))
else
("", path)
end

fun base(path: String, with_ext: Bool = true): String =>
"""
Return the path after the last separator, or the whole path if there is no
separator.
If `with_ext` is `false`, the extension as defined by the `ext()` method
will be omitted from the result.
"""
let b = try
path.trim(path.rfind(sep())?.usize() + 1)
else
path
end


Parameters¶

y: ILong val

Returns¶

ILong val

max¶
[Source]
fun box max(
y: ILong val)
: ILong val

Parameters¶

y: ILong val

Returns¶


Implements¶

Property1[IntPairPropertySample ref] ref

Public Functions¶
gen¶
[Source]
fun box gen()
: Generator[IntPairPropertySample ref] box

Returns¶

Generator[IntPairPropertySample ref] box

property¶
[Source]
fun ref property(


Returns¶

Bool val

ne_unsafe¶
fun box ne_unsafe(
y: F32 val)
: Bool val

Parameters¶

y: F32 val

Returns¶

Bool val


fun box sctp_cause_protocol_violation()
: I32 val

Returns¶

I32 val

sctp_cause_request_refused¶
[Source]
fun box sctp_cause_request_refused()
: I32 val

Returns¶

I32 val

sctp_cause_resource_shortage¶
[Source]


fun box rds_info_tcp_sockets()
: I32 val

Returns¶

I32 val

rds_rdma_canceled¶
[Source]
fun box rds_rdma_canceled()
: I32 val

Returns¶

I32 val

rds_rdma_dontwait¶
[Source]


fun box sctp_connect_x()
: I32 val

Returns¶

I32 val

sctp_connect_x_complete¶
[Source]
fun box sctp_connect_x_complete()
: I32 val

Returns¶

I32 val

sctp_connect_x_delayed¶
[Source]


112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131


372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391


object is Iterator[GenerateResult[T]]
fun ref has_next(): Bool => true
fun ref next(): GenerateResult[T] ? => that.generate(rnd)?
end

fun value_iter(rnd: Randomness): Iterator[T^] =>
let that: GenObj[T] = this

object is Iterator[T^]
fun ref has_next(): Bool => true
fun ref next(): T^ ? =>
match that.generate(rnd)?
| let value_only: T => consume value_only
| (let v: T, _) => consume v
end
end

fun value_and_shrink_iter(rnd: Randomness): Iterator[ValueAndShrink[T]] =>
let that: GenObj[T] = this


ILong val

hash¶
[Source]
fun box hash()
: USize val

Returns¶

USize val

addc¶
[Source]
fun box addc(
y: ILong val)
: (ILong val , Bool val)


_stdin.close_near()
return
end
elseif (len.usize() + offset) < data.size() then
// Send remaining data later.
node()? = (data, offset + len.usize())
return
else
// This pending chunk has been fully sent.
_pending.shift()?
if (_pending.size() == 0) then
Backpressure.release(_backpressure_auth)
// check if the client has signaled it is done
if _done_writing then
_stdin.close_near()
end
end
end
else
// handle error


end
```


If this is 0, the result is undefined.
"""
@"llvm.ctlz.i32"(this, true)

fun ctz_unsafe(): U32 =>
"""
Unsafe operation.
If this is 0, the result is undefined.
"""
@"llvm.cttz.i32"(this, true)

fun bitwidth(): U32 => 32

fun bytewidth(): USize => bitwidth().usize() / 8

fun min(y: U32): U32 => if this < y then this else y end
fun max(y: U32): U32 => if this > y then this else y end

fun addc(y: U32): (U32, Bool) =>
@"llvm.uadd.with.overflow.i32"(this, y)


y: F64 val

Returns¶

Bool val

ge_unsafe¶
fun box ge_unsafe(
y: F64 val)
: Bool val

Parameters¶

y: F64 val

Returns¶

Bool val


min: USize = 0,
max: USize = 100)
: Generator[String]
=>
"""
Create a generator for strings
generated from the bytes returned by the generator `gen`,
with a minimum length of `min` (default: 0)
and a maximum length of `max` (default: 100).
"""
Generator[String](
object is GenObj[String]
fun generate(rnd: Randomness): GenerateResult[String] =>
let size = rnd.usize(min, max)
let gen_iter = Iter[U8^](gen.value_iter(rnd))
.take(size)
let arr: Array[U8] iso = recover Array[U8](size) end
for b in gen_iter do
arr.push(b)
end


[Source]
fun box add_partial(
y: ILong val)
: ILong val ?

Parameters¶

y: ILong val

Returns¶

ILong val ?

sub_partial¶
[Source]
fun box sub_partial(
y: ILong val)
: ILong val ?


None val

insert¶
[Source]
Returns a version of the string with the given string inserted at the given
offset.
fun box insert(
offset: ISize val,
that: String val)
: String iso^

Parameters¶

offset: ISize val
that: String val

Returns¶


Parameters¶

that: (Less val | Equal val | Greater val)

Returns¶

Bool val


create¶
[Source]
new val create()
: Sort[A, B] val^

Returns¶

Sort[A, B] val^

Public Functions¶
apply¶
[Source]
Sort the given seq.
fun box apply(
a: A)
: A^

Parameters¶


new create(slop: USize = 20) =>
"""
Create a timer handler with the specified number of slop bits. No slop bits
means trying for nanosecond resolution. 10 slop bits is approximately
microsecond resolution, 20 slop bits is approximately millisecond
resolution.
"""
_slop = slop
_set_time()

for i in Range(0, _wheels()) do
_wheel.push(_TimingWheel(i))
end

be apply(timer: Timer iso) =>
"""
Sets a timer. Fire it if need be, schedule it on the right timing wheel,
then rearm the timer.
"""
let timer': Timer ref = consume timer


# Garbage Collection with Pony-ORCA

Pony-ORCA is a fully concurrent protocol for garbage collection in the actor paradigm. It allows cheap and small actors to perform garbage collection concurrently with any number of other actors, and this number can go into the millions since one actor needs only 256 bytes on 64bit systems. It does not require any form of synchronization across actors except those introduced through the actor paradigm, i.e. **message send** and **message receive**.

Pony-ORCA, yes _the killer whale_, is based on ideas from ownership and deferred, distributed, weighted **reference counting**. It adapts messaging systems of actors to keep the reference count consistent. The main challenges in concurrent garbage collection are the detection of cycles of sleeping actors in the actor's graph, in the presence of the concurrent mutation of this graph. With message passing, you get deferred direct reference counting, a dedicated actor for the detection of (cyclic) garbage, and a confirmation protocol (to deal with the mutation of the actor graph).

1. _Soundness_: the technique collects only dead actors.

2. _Completeness_: the technique collects all dead actors eventually.

3. _Concurrency_: the technique does not require a stop-the-world step, clocks, time stamps, versioning, thread coordination, actor introspection, shared memory, read/write barriers or cache coherency.

The type system ensures at compile time that your program can **never have data races**. It's **deadlock free**... Because Pony has **no locks**!

When an actor has completed local execution and has no pending messages on its queue, it is _blocked_. An actor is _dead_, if it is blocked and all actors that have a reference to it are blocked, transitively. A collection of dead actors depends on being able to collect closed cycles of blocked actors.

The Pony type system guarantees race and deadlock free concurrency and soundness by adhering to the following principles:


72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91


# The Pony Type System at a Glance

Pony is a _statically typed_ language, like Java, C#, C++, and many others. This means the compiler knows the type of everything in your program. This is different from _dynamically typed_ languages, such as Python, Lua, JavaScript, and Ruby.


let p2 = Promise[String val]
let p3 = Promise[String val]

p3.join([p1; p2].values())
.next[None]({(a: Array[String val] val) =>
for s in a.values() do
env.out.print(s)
end
})

p2("second")
p3("third")
p1("first")
```
"""
Promises[A].join(
[this]
.> concat(ps)
.values())


let help_option = OptionSpec.bool(_help_name, _help_info, 'h', false)
_options.update(_help_name, help_option)
if is_parent() then
let help_cmd = CommandSpec.leaf(_help_name, "", Array[OptionSpec](), [
ArgSpec.string("command" where default' = "")
])?
_commands.update(_help_name, help_cmd)
end

fun name(): String =>
"""
Returns the name of this command.
"""
_name

fun descr(): String =>
"""
Returns the description for this command.
"""
_descr


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31


172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191


fun box tipc_max_link_name()
: I32 val

Returns¶

I32 val

tipc_max_media_name¶
[Source]
fun box tipc_max_media_name()
: I32 val

Returns¶

I32 val

tipc_max_user_msg_size¶
[Source]


y: U32 val

Returns¶

U32 val

modc¶
[Source]
fun box modc(
y: U32 val)
: (U32 val , Bool val)

Parameters¶

y: U32 val

Returns¶


# Additional resources

You can learn more about PonyCheck specifics by checking out the [API documentation](https://stdlib.ponylang.io/pony_check--index/). You can also find some [example tests](https://github.com/ponylang/ponyc/tree/main/examples/pony_check) in [ponyc GitHub repository](https://github.com/ponylang/ponyc).

To learn more about testing in Pony in general, there's a [testing section](http://patterns.ponylang.io/testing.html) in the [Pony Patterns](http://patterns.ponylang.io/) book which isn't specific to `PonyCheck`.


end

s .> recalc()
end

fun int[A: (Int & Integer[A])](
x: A,
fmt: FormatInt = FormatDefault,
prefix: PrefixNumber = PrefixDefault,
prec: USize = -1,
width: USize = 0,
align: Align = AlignRight,
fill: U32 = ' ')
: String iso^
=>
let zero = x.from[USize](0)
(let abs, let neg) = if x < zero then (-x, true) else (x, false) end

iftype A <: U128 then
_FormatInt.u128(x.u128(), false, fmt, prefix, prec, width, align, fill)


@pony_asio_event_set_readable(_event, false)
_readable = false
_reading = false
@pony_asio_event_resubscribe_read(_event)
return
end

_read_buf_offset = _read_buf_offset + len
sum = sum + len
end
else
// The socket has been closed from the other side.
_shutdown_peer = true
hard_close()
end
end

_reading = false

fun ref _notify_connecting() =>


Returns¶

I8 val ?

i16¶
[Source]
fun box i16(
base: U8 val = 0)
: I16 val ?

Parameters¶

base: U8 val = 0

Returns¶

I16 val ?


Signaled¶
[Source]
Process exit status: Process was terminated by a signal.
class val Signaled is
Stringable box,
Equatable[(Exited val | Signaled val)] ref

Implements¶

Stringable box
Equatable[(Exited val | Signaled val)] ref


472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491


Returns false if the file wasn't opened with write permission.
Raises an error if not all the bytes were written.
Returns true if it sent all pending data.
Returns num_processed and new pending_total also.
"""
var num_to_send: I32 = 0
var num_sent: USize = 0
var bytes_to_send: USize = 0
var pending_total = _pending_writev_total

if (not writeable) or (_fd == -1) then
return (false, num_sent, pending_total)
end

// TODO: Make writev_batch_size user configurable
let writev_batch_size = @pony_os_writev_max()
while pending_total > 0 do
// Determine the number of bytes and buffers to send.
num_to_send = _pending_writev.size().i32() - num_sent.i32()
if num_to_send <= writev_batch_size then


: String val

Returns¶

String val


fun box netlink_ecryptfs()
: I32 val

Returns¶

I32 val

netlink_fib_lookup¶
[Source]
fun box netlink_fib_lookup()
: I32 val

Returns¶

I32 val

netlink_firewall¶
[Source]


Bool val

ne¶
[Source]
fun box ne(
that: StartProcessAuth val)
: Bool val

Parameters¶

that: StartProcessAuth val

Returns¶

Bool val


fun box i16()
: I16 val

Returns¶

I16 val

i32¶
[Source]
fun box i32()
: I32 val

Returns¶

I32 val

i64¶
[Source]


F64 val

finite¶
[Source]
Check whether this number is finite, ie not +/-infinity and not NaN.
fun box finite()
: Bool val

Returns¶

Bool val

infinite¶
[Source]
Check whether this number is +/-infinity
fun box infinite()
: Bool val


Returns¶

Bool val

ne¶
[Source]
fun box ne(
that: SerialiseAuth val)
: Bool val

Parameters¶

that: SerialiseAuth val

Returns¶

Bool val


52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71


fun box tcp_cookie_out_never()
: I32 val

Returns¶

I32 val

tcp_cookie_pair_size¶
[Source]
fun box tcp_cookie_pair_size()
: I32 val

Returns¶

I32 val

tcp_cookie_transactions¶
[Source]


The result has the sign of the dividend.

If y is `0` or the operation overflows, this function errors.
"""

fun divrem_partial(y: A): (A, A) ?
"""
Divides this number by y and calculates the remainder of the operation.

If y is `0` or the operation overflows, this function errors.
"""

fun fld_partial(y: A): A ?
"""
Floored integer division, rounded towards negative infinity.

If y is `0` or the operation overflows, this function errors
"""

fun mod_partial(y: A): A ?


Internal constructor from a file descriptor and a path.
"""
if not from.caps(FileRead) or (fd == -1) then
error
end

path = from
writeable = from.caps(FileWrite)
_fd = fd

_FileDes.set_rights(_fd, path, writeable)?

fun errno(): FileErrNo =>
"""
Returns the last error code set for this File
"""
_errno

fun ref clear_errno() =>
"""


fun box rds_info_iwarp_connections()
: I32 val

Returns¶

I32 val

rds_info_last¶
[Source]
fun box rds_info_last()
: I32 val

Returns¶

I32 val

rds_info_message_flag_ack¶
[Source]


command_help.pony

1
2
3
4
5
6
7
8
9
10
11


new create(from: FilePath) =>
"""
Attempt to open for read/write, creating if it doesn't exist, preserving
the contents if it does exist.
Set errno according to result.
"""
path = from
writeable = true
_fd = -1

if not from.caps(FileRead) or not from.caps(FileWrite) then
_errno = FileError
else
var flags: I32 = @ponyint_o_rdwr()
let mode = FileMode.u32() // default file permissions
if not path.exists() then
if not path.caps(FileCreate) then
_errno = FileError
else


String iso^

compare¶
[Source]
Lexically compare two strings.
fun box compare(
that: String box)
: (Less val | Equal val | Greater val)

Parameters¶

that: String box

Returns¶

(Less val | Equal val | Greater val)


892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911


```pony
let my_list = List[String].from(["a"; "b"; "c"])
let other_list = List[String].from(["d"; "e"; "f"])
my_list.concat(other_list.values())  // my_list is ["a"; "b"; "c"; "d"; "e"; "f"], other_list is unchanged
```
"""
try
for i in Range(0, offset) do
if iter.has_next() then
iter.next()?
else
return
end
end

for i in Range(0, len) do
if iter.has_next() then
push(iter.next()?)
else
return


Bool val


Benchmark¶
[Source]
type Benchmark is
(MicroBenchmark iso | AsyncMicroBenchmark iso)

Type Alias For¶

(MicroBenchmark iso | AsyncMicroBenchmark iso)


"""
for v in values() do
if not that.contains(v) then return false end
end
true

fun gt(that: HashSet[A, H] box): Bool =>
"""
Return true if every element in that is also in this, and this has more
elements than that.
"""
(size() > that.size()) and (that <= this)

fun ge(that: HashSet[A, H] box): Bool =>
"""
Return true if every element in that is also in this.
"""
that <= this

fun values(): Iterator[A]^ =>


cap_rights.pony

1
2
3
4
5
6
7
8
9
10
11


Bool val

lines¶
[Source]
Returns an iterator for reading lines from the file.
fun ref lines()
: FileLines ref

Returns¶

FileLines ref

dispose¶
[Source]
Close the file. Future operations will do nothing.
fun ref dispose()
: None val


let access_time: (I64, I64) = (0, 0)
"""
Time of last access as a tuple of seconds and nanoseconds since the epoch:

```pony
(let a_secs: I64, let a_nanos: I64) = file_info.access_time
```
"""

let modified_time: (I64, I64) = (0, 0)
"""
Time of last modification as tuple of seconds and nanoseconds since the epoch:

```pony
(let m_secs: I64, let m_nanos: I64) = file_info.modified_time
```
"""

let change_time: (I64, I64) = (0, 0)
"""


ctrl: Bool val = false
alt: Bool val = false
shift: Bool val = false

Returns¶

None val

insert¶
[Source]
fun ref insert(
ctrl: Bool val,
alt: Bool val,
shift: Bool val)
: None val

Parameters¶


72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91


backpressure.pony

1
2
3
4
5
6
7
8
9
10
11


zip3[B: B, C: C, D: D]¶
[Source]
Zip four iterators together so that each call to next() results in
a tuple with the next value of each of the iterators. The number of
items returned is the minimum of the number of items returned by the
iterators.
fun ref zip3[B: B, C: C, D: D](
i2: Iterator[B] ref,
i3: Iterator[C] ref,
i4: Iterator[D] ref)
: Iter[(A , B , C , D)] ref^

Parameters¶

i2: Iterator[B] ref
i3: Iterator[C] ref
i4: Iterator[D] ref

Returns¶


# Example program
There are a _lot_ of functions in List. The following code picks out a few common examples.

It outputs:

A new empty list has 0 nodes.
Adding one node to our empty list means it now has a size of 1.
The first (index 0) node has the value: A single String
A list created by appending our second single-node list onto our first has size: 2
The List nodes of our first list are now:
A single String
Another String
Append *moves* the nodes from the second list so that now has 0 nodes.
A list created from an array of three strings has size: 3
First
Second
Third
Mapping over our three-node list produces a new list of size: 3
Each node-value in the resulting list is now far more exciting:
First BOOM!


new create(s: String, u: U32) =>
_s = s
_u = u

fun eq(foo: Foo box): Bool =>
(_s == foo._s) and (_u == foo._u)

actor Main
new create(env: Env) =>
try
// get serialization authorities
let serialise = SerialiseAuth(env.root)
let output = OutputSerialisedAuth(env.root)
let deserialise = DeserialiseAuth(env.root)
let input = InputSerialisedAuth(env.root)

let foo1 = Foo("abc", 123)

// serialisation


if the result would over- or underflow,
the offset exceeds the size of this string or
there are leftover characters in the string after conversion.

Examples:

```pony
"1.5".f32()? == F32(1.5)
"1.19208e-07".f32()? == F32(1.19208e-07)
"NaN".f32()?.nan() == true
```
"""
let index = offset_to_index(offset)
if index < _size then
let ptr = this.cstring()
var endp: Pointer[U8] box = Pointer[U8]
@pony_os_clear_errno()
let res = @strtof(ptr.offset(index), addressof endp)
let errno: I32 = @pony_os_errno()
if (errno != 0) or (endp != ptr.offset(_size)) then


Bool val

ne¶
[Source]
fun box ne(
that: DNSAuth val)
: Bool val

Parameters¶

that: DNSAuth val

Returns¶

Bool val


if _size.next_pow2() != _alloc.next_pow2() then
_alloc = _size.next_pow2()
let old_ptr = _ptr = Pointer[A]._alloc(_alloc)
old_ptr._copy_to(_ptr._convert[A!](), _size)
end
elseif _size < _alloc then
_alloc = _size
let old_ptr = _ptr = Pointer[A]._alloc(_alloc)
old_ptr._copy_to(_ptr._convert[A!](), _size)
end

fun ref undefined[B: (A & Real[B] val & Number) = A](len: USize) =>
"""
Resize to len elements, populating previously empty elements with random
memory. This is only allowed for an array of numbers.
"""
reserve(len)
_size = len

fun read_u8[B: (A & Real[B] val & U8) = A](offset: USize): U8 ? =>


Returns¶

USize val ?

index¶
[Source]
Returns the key and value at a given index.
Raise an error if the index is not populated.
fun box index(
i: USize val)
: (this->K , this->V) ?

Parameters¶

i: USize val

Returns¶

(this->K , this->V) ?


fun box has_next()
: Bool val

Returns¶

Bool val

next¶
[Source]
Returns the next value, or raises an error if there isn't one. If values
are added during iteration, this may not return all values.
fun ref next()
: S->A ?

Returns¶

S->A ?


fun box rose_max_digis()
: I32 val

Returns¶

I32 val

rose_mtu¶
[Source]
fun box rose_mtu()
: I32 val

Returns¶

I32 val

rose_network_congestion¶
[Source]


failed.
Exclusion groups¶
By default all tests are run concurrently. This may be a problem for some
tests, eg if they manipulate an external file or use a system resource. To fix
this issue any number of tests may be put into an exclusion group.
No tests that are in the same exclusion group will be run concurrently.
Exclusion groups are identified by name, arbitrary strings may be used.
Multiple exclusion groups may be used and tests in different groups may run
concurrently. Tests that do not specify an exclusion group may be run
concurrently with any other tests.
The command line option "--sequential" prevents any tests from running
concurrently, regardless of exclusion groups. This is intended for debugging
rather than standard use.
Labels¶
Test can have label. Labels are used to filter which tests are run, by setting
command line argument --label=[some custom label]. It can be used to separate
unit tests from integration tests.
By default label is empty. You can set it up by overriding label(): String
method in unit test.
use "pony_test"


252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271


y: USize val

Returns¶

USize val

modc¶
[Source]
fun box modc(
y: USize val)
: (USize val , Bool val)

Parameters¶

y: USize val

Returns¶


to either of these constructors to perform additional tasks.
Test names¶
Tests are identified by names, which are used when printing test results and on
the command line to select which tests to run. These names are independent of
the names of the test classes in the Pony source code.
Arbitrary strings can be used for these names, but for large projects it is
strongly recommended to use a hierarchical naming scheme to make it easier to
select groups of tests.
You can skip any tests whose names start with a given string by using the
--exclude=[prefix] command line option.
You can run only tests whose names start with a given string by using the
--only=[prefix] command line option.
Aggregation¶
Often it is desirable to run a collection of unit tests from multiple different
source files. For example, if several packages within a bundle each have their
own unit tests it may be useful to run all tests for the bundle together.
This can be achieved by writing an aggregate test list class, which calls the
list function for each package. The following is an example that aggregates the
tests from packages foo and bar.
use "pony_test"


ASCIIPrintable¶
[Source]
primitive val ASCIIPrintable

Constructors¶
create¶
[Source]
new val create()
: ASCIIPrintable val^

Returns¶

ASCIIPrintable val^


132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151


let change_time: (I64 val , I64 val)¶
[Source]
Time of the last change either the attributes (number of links, owner,
group, file mode, ...) or the content of filepath
as a tuple of seconds and nanoseconds since the epoch:
(let c_secs: I64, let c_nanos: I64) = file_info.change_time

On Windows this will be the file creation time.

let file: Bool val¶
[Source]
true if filepath points to an a regular file.

let directory: Bool val¶
[Source]
true if filepath points to a directory.

let pipe: Bool val¶
[Source]
true if filepath points to a named pipe.


Returns¶

Bool val

ge¶
[Source]
Returns true if every element in that is also in this.
fun box ge(
that: HashSet[A, H] box)
: Bool val

Parameters¶

that: HashSet[A, H] box

Returns¶

Bool val


Public Functions¶
name¶
[Source]
fun box name()
: String val

Returns¶

String val

apply¶
[Source]
fun ref apply(
h: TestHelper val)
: None val ?

Parameters¶


### Example

```pony
Iter[I64]([1; 2; 3].values())
.count()
```
`3`
"""
var sum: USize = 0
for _ in _iter do
sum = sum + 1
end
sum

fun ref cycle(): Iter[A!]^ =>
"""
Repeatedly cycle through the values from the iterator.

WARNING: The values returned by the original iterator are cached, so
the input iterator should be finite.


directory.pony

1
2
3
4
5
6
7
8
9
10
11


# What goes in a struct?

The same as a class! A struct is composed of some combination of:

1. Fields
2. Constructors
3. Functions


max_sample_time = max_sample_time'

class iso OverheadBenchmark is MicroBenchmark
"""
Default benchmark for measuring synchronous overhead.
"""
fun name(): String =>
"Benchmark Overhead"

fun ref apply() =>
DoNotOptimise[None](None)
DoNotOptimise.observe()

class iso AsyncOverheadBenchmark is AsyncMicroBenchmark
"""
Default benchmark for measuring asynchronous overhead.
"""
fun name(): String =>
"Benchmark Overhead"


Bool val

i8¶
[Source]
fun box i8()
: I8 val

Returns¶

I8 val

i16¶
[Source]
fun box i16()
: I16 val

Returns¶


: U128 val

Returns¶

U128 val

ulong¶
[Source]
fun ref ulong()
: ULong val

Returns¶

ULong val

usize¶
[Source]
fun ref usize()


U128 val

ulong¶
[Source]
fun box ulong()
: ULong val

Returns¶

ULong val

usize¶
[Source]
fun box usize()
: USize val

Returns¶


y: I64 val

Returns¶

(I64 val , Bool val)

modc¶
[Source]
fun box modc(
y: I64 val)
: (I64 val , Bool val)

Parameters¶

y: I64 val

Returns¶


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51


Returns¶

Bool val

ne¶
[Source]
fun box ne(
that: Sig val)
: Bool val

Parameters¶

that: Sig val

Returns¶

Bool val


fun box f64_unsafe()
: F64 val

Returns¶

F64 val

compare¶
[Source]
fun box compare(
that: U32 val)
: (Less val | Equal val | Greater val)

Parameters¶

that: U32 val

Returns¶


while tokens.size() > 0 do
let token = try tokens.shift()? else "" end
if (token == "--") and (opt_stop == false) then
opt_stop = true

elseif not opt_stop and (token.compare_sub("--", 2, 0) == Equal) then
match _parse_long_option(token.substring(2), tokens)
| let o: Option =>
if o.spec()._typ_p().is_seq() then
options.upsert(o.spec().name(), o, {(x, n) => x._append(n) })
else
options.update(o.spec().name(), o)
end
| let se: SyntaxError => return se
end

elseif not opt_stop and
((token.compare_sub("-", 1, 0) == Equal) and (token.size() > 1)) then
match _parse_short_options(token.substring(1), tokens)


fun ref u64(
min: U64 val = call,
max: U64 val = call)
: U64 val

Parameters¶

min: U64 val = call
max: U64 val = call

Returns¶

U64 val

u128¶
[Source]
Generate a U128 in closed interval [min, max]
(default: [min_value, max_value]).
Behavior is undefined if min > max.


832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851


1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411


fun box lt(
y: U64 val)
: Bool val

Parameters¶

y: U64 val

Returns¶

Bool val

le¶
[Source]
fun box le(
y: U64 val)
: Bool val

Parameters¶


fun box ipproto_ipcv()
: I32 val

Returns¶

I32 val

ipproto_ipeip¶
[Source]
fun box ipproto_ipeip()
: I32 val

Returns¶

I32 val

ipproto_ipip¶
[Source]


actor Main
new create(env:Env) =>
let a = Foo(recover ref String end)
env.out.print(a.get().string())
a.set(recover ref String end)
env.out.print(a.get().string())
```

That compiles and runs, so `ref` is valid now. The real test though is `iso`. Let's convert the class to `iso` and walk through what is needed to get it to compile. We'll then revisit our generic class to get it working:


# Immutable reference capabilities

The __immutable__ reference capabilities are `val` and `box`. These reference capabilities are __immutable__ because they can be used to read from an object, but not to write to it.

* If an actor has a `val` variable, no other variable can be used by _any_ actor to write to that object. This means that the object can't _ever_ change. It is _globally immutable_.
* If an actor has a `box` variable, no other variable can be used by _other_ actors to write to that object. This means that other actors may be able to read the object and other variables in the same actor may be able to write to it (although not both). In either case, it is safe for us to read. The object is _locally immutable_.

__Why can they be used to read but not write?__ Because these reference capabilities only stop _other_ actors from writing to the object. That means there is no guarantee that _other_ actors aren't reading from the object, which means it's not safe for us to write to it. It's safe for more than one actor to read from an object at the same time though, so we're allowed to do that.


532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551


min + _random.int((max - min).u64() + 1).u32()
end

fun ref u64(min: U64 = U64.min_value(), max: U64 = U64.max_value()): U64 =>
"""
Generate a U64 in closed interval [min, max]
(default: [min_value, max_value]).

Behavior is undefined if `min` > `max`.
"""
if (min == U64.min_value()) and (max == U64.max_value()) then
_random.u64()
elseif min > U32.max_value().u64() then
(u32((min >> 32).u32(), (max >> 32).u32()).u64() << 32) or _random.u32().u64()
elseif max > U32.max_value().u64() then
let high = (u32((min >> 32).u32(), (max >> 32).u32()).u64() << 32).u64()
let low =
if high > 0 then
_random.u32().u64()
else


152
153
154
155
156
157
158
159
160
161use "time"

use @pony_ctx[Pointer[None]]()
use @pony_triggergc[None](ctx: Pointer[None])

trait tag _Runner
be apply()

actor _RunSync is _Runner
let _ponybench: PonyBench
embed _aggregator: _Aggregator


fun box sctp_auth_supported()
: I32 val

Returns¶

I32 val

sctp_autoclose¶
[Source]
fun box sctp_autoclose()
: I32 val

Returns¶

I32 val

sctp_auto_asconf¶
[Source]


92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111


_pending_writes()
end
end

fun ref _complete_writes(len: U32) =>
"""
The OS has informed us that `len` bytes of pending writes have completed.
This occurs only with IOCP on Windows.
"""
ifdef windows then
if len == 0 then
// IOCP reported a failed write on this chunk. Non-graceful shutdown.
hard_close()
return
end

try
_manage_pending_buffer(len.usize(),
_pending_writev_total, _pending_writev_windows.size())?
end


does not allow the holder to serialise objects or examine serialised data.
"""
new create(auth: AmbientAuth) =>
None

primitive OutputSerialisedAuth
"""
This is a capability token that allows the holder to examine serialised data.
This should only be provided to types that need to write serialised data to
some output stream, such as a file or socket. A type with the [SerialiseAuth](serialise-SerialiseAuth.md)
capability should usually not also have OutputSerialisedAuth, as the
combination gives the holder the ability to examine the bitwise contents of
any object it has a reference to.
"""
new create(auth: AmbientAuth) =>
None

primitive InputSerialisedAuth
"""
This is a capability token that allows the holder to treat arbitrary


272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291


descr': String val = "")
: ArgSpec val^

Parameters¶

name': String val
descr': String val = ""

Returns¶

ArgSpec val^

Public Functions¶
name¶
[Source]
Returns the name of this arg.
fun box name()
: String val


132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151


[Source]
fun box ne(
that: CreateFile val)
: Bool val

Parameters¶

that: CreateFile val

Returns¶

Bool val


332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351


72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91


52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71


# Partial Application

Partial application lets us supply _some_ of the arguments to a constructor, function, or behaviour, and get back something that lets us supply the rest of the arguments later.


172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191


652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671


ILong val

isize¶
[Source]
fun box isize()
: ISize val

Returns¶

ISize val

u8¶
[Source]
fun box u8()
: U8 val

Returns¶


```pony
a
-b
```

That means "first do a, then, in a new expression, do a unary negation of b".


that._int_shrink[U8](consume u, min)
end)

fun u16(
min: U16 = U16.min_value(),
max: U16 = U16.max_value())
: Generator[U16]
=>
"""
create a generator for U16 values
"""
let that = this
Generator[U16](
object is GenObj[U16]
fun generate(rnd: Randomness): U16^ =>
rnd.u16(min, max)

fun shrink(u: U16): ValueAndShrink[U16] =>
that._int_shrink[U16](consume u, min)
end)


432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451


Property3[T1: T1, T2: T2, T3: T3]¶
[Source]
trait ref Property3[T1: T1, T2: T2, T3: T3] is
Property1[(T1 , T2 , T3)] ref

Implements¶

Property1[(T1 , T2 , T3)] ref

Public Functions¶
gen1¶
[Source]


bool.pony

1
2
3
4
5
6
7
8
9
10
11


end
end

s
else
path
end

fun to_slash(path: String): String =>
"""
Changes each OS specific separator in the path to /.
"""
ifdef windows then
let s = path.clone()
let len = s.size()
var i = USize(0)

try
while i < len do
if s(i)? == '\\' then


Parameters¶

y: box->A

Returns¶

Bool val

ne¶
[Source]
fun box ne(
y: box->A)
: Bool val

Parameters¶

y: box->A

Returns¶


fun rose_qbitincl():I32 => @pony_os_sockopt_option(I32(502))
fun rose_remote_procedure():I32 => @pony_os_sockopt_option(I32(503))
fun rose_ship_absent():I32 => @pony_os_sockopt_option(I32(504))
fun rose_t1():I32 => @pony_os_sockopt_option(I32(505))
fun rose_t2():I32 => @pony_os_sockopt_option(I32(506))
fun rose_t3():I32 => @pony_os_sockopt_option(I32(507))
fun scm_hci_raw_direction():I32 => @pony_os_sockopt_option(I32(508))
fun scm_timestamp():I32 => @pony_os_sockopt_option(I32(509))
fun scm_timestamping():I32 => @pony_os_sockopt_option(I32(510))
fun scm_timestampns():I32 => @pony_os_sockopt_option(I32(511))
fun scm_wifi_status():I32 => @pony_os_sockopt_option(I32(512))
fun sctp_abort_association():I32 => @pony_os_sockopt_option(I32(513))
fun sctp_adaptation_layer():I32 => @pony_os_sockopt_option(I32(514))
fun sctp_adaption_layer():I32 => @pony_os_sockopt_option(I32(515))
fun sctp_add_streams():I32 => @pony_os_sockopt_option(I32(516))
fun sctp_add_vrf_id():I32 => @pony_os_sockopt_option(I32(517))
fun sctp_asconf():I32 => @pony_os_sockopt_option(I32(518))
fun sctp_asconf_ack():I32 => @pony_os_sockopt_option(I32(519))
fun sctp_asconf_supported():I32 => @pony_os_sockopt_option(I32(520))
fun sctp_associnfo():I32 => @pony_os_sockopt_option(I32(521))


Builds a list by dropping the first n elements.
fun val drop(
n: USize val)
: (Cons[A] val | Nil[A] val)

Parameters¶

n: USize val

Returns¶

(Cons[A] val | Nil[A] val)

drop_while¶
[Source]
Builds a list by dropping elements from the front of the list until one
fails to satisfy the provided predicate.
fun val drop_while(
f: {(val->A): Bool}[A] box)


sock: UDPSocket ref

Returns¶

None val


RejectAlways[A] iso^

Public Functions¶
apply¶
[Source]
fun ref apply()
: A ?

Returns¶

A ?


fun box mmap_wx()
: U64 val

Returns¶

U64 val

mmap_rwx¶
[Source]
fun box mmap_rwx()
: U64 val

Returns¶

U64 val

creat¶
[Source]


# Local and global aliases

Before anything else, we want to clarify what we mean by "local" and "global" aliases.

A local alias is a reference to the same variable that exists in the same actor. Whenever you pass a value around, and it's not the argument of an actor's behavior, this is the kind of alias we are working with.

On the other hand, a global alias is a reference to the same variable that can exist in a _different_ actor. That is, it describes the properties of how two or more actors could interact with the same reference.

Each reference capability in Pony is actually a pair of local guarantees and global guarantees. For instance, `ref` doesn't deny any read/write capabilities inside the actor, but denies other actors from reading or writing to that reference.

You may recall from the [Reference Capability Guarantees](guarantees.md) section that mutable references cannot be safely shared between actors, while immutable references can be read by multiple actors. In general, global properties are always as restrictive or more restrictive than the local properties to that reference - what is denied globally must also be denied locally. For example, it's not possible to write to an immutable reference in either a global or local alias. It's also not possible to read from or write to an opaque reference, `tag`. Therefore, some combinations of local and global aliases are impossible, and have no designated capabilities.


452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471


192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211


```pony
let my_list = List[String].from(["a"; "b"; "c"])
let rvalues = my_list.rvalues()  // value "c" is before value "a"
```
"""
ListValues[A, this->ListNode[A]](_head, true)

fun ref _increment() =>
"""
Private method to control mutating `_size` field.
"""
_size = _size + 1

fun ref _decrement() =>
"""
Private method to control mutating `_size` field.
"""
_size = _size - 1


292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311


that: Time val

Returns¶

Bool val


fun box sctp_get_stat_log()
: I32 val

Returns¶

I32 val

sctp_get_vrf_ids¶
[Source]
fun box sctp_get_vrf_ids()
: I32 val

Returns¶

I32 val

sctp_had_no_tcb¶
[Source]


y: U64 val

Returns¶

U64 val ?

fld_unsafe¶
[Source]
fun box fld_unsafe(
y: U64 val)
: U64 val

Parameters¶

y: U64 val

Returns¶


fun map4[T1, T2, T3, T4, T5](
gen1: Generator[T1],
gen2: Generator[T2],
gen3: Generator[T3],
gen4: Generator[T4],
fn: {(T1, T2, T3, T4): T5^})
: Generator[T5]
=>
"""
Convenience combinator for mapping 4 generators into 1.
"""
Generators.zip4[T1, T2, T3, T4](gen1, gen2, gen3, gen4)
.map[T5]({(arg) =>
(let arg1, let arg2, let arg3, let arg4) = consume arg
fn(consume arg1, consume arg2, consume arg3, consume arg4)
})

fun bool(): Generator[Bool] =>
"""
Create a generator of bool values.


// is given a ApplyReleaseBackpressureAuth token. This allows the notifier
// to inform the Pony runtime when to apply and release backpressure
// as the connection experiences it.
// Note the calls to
//
// Backpressure.apply(_auth)
// Backpressure.release(_auth)
//
// that apply and release backpressure as needed

use "backpressure"
use "collections"
use "net"

class SlowDown is TCPConnectionNotify
let _auth: ApplyReleaseBackpressureAuth
let _out: OutStream

new iso create(auth: ApplyReleaseBackpressureAuth, out: OutStream) =>
_auth = auth


"""The program's environment variables."""

let exitcode: {(I32)} val
"""
Sets the environment's exit code. The exit code of the root environment will
be the exit code of the application, which defaults to 0.
"""

new _create(
argc: U32,
argv: Pointer[Pointer[U8]] val,
envp: Pointer[Pointer[U8]] val)
=>
"""
Builds an environment from the command line. This is done before the Main
actor is created.
"""
root = AmbientAuth._create()
@pony_os_stdout_setup()


// Have more buffers than a single writev can handle.
// Iterate over buffers being sent to add up total.
num_to_send = writev_batch_size
bytes_to_send = 0
for d in Range[USize](0, num_to_send, 1) do
bytes_to_send = bytes_to_send + _pending_writev_posix(d)?._2
end
end

// Write as much data as possible.
var len = @pony_os_writev(_event,
_pending_writev_posix.cpointer(), num_to_send.i32()) ?

if _manage_pending_buffer(len, bytes_to_send, num_to_send)? then
return true
end

bytes_sent = bytes_sent + len
else
// Non-graceful shutdown on error.


612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631


"""
Returns true if the file is currently open.
"""
not (_fd == -1)

fun ref read(len: USize): Array[U8] iso^ =>
"""
Returns up to len bytes.
"""
if _fd != -1 then
let result = recover Array[U8] .> undefined(len) end

let r =
(ifdef windows then
@_read(_fd, result.cpointer(), len.i32())
else
@read(_fd, result.cpointer(), len)
end)
.isize()


Each test run is provided with a helper object. This provides logging and
assertion functions. By default log messages are only shown for tests that
fail.
When any assertion function fails the test is counted as a fail. However, tests
can also indicate failure by raising an error in the test function.
Example program¶
To use PonyTest simply write a class for each test and a TestList type that
tells the PonyTest object about the tests. Typically the TestList will be Main
for the package.
The following is a complete program with 2 trivial tests.
use "pony_test"

actor Main is TestList
new create(env: Env) =>
PonyTest(env, this)

new make() =>
None

fun tag tests(test: PonyTest) =>


312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331


[Source]
Create a new timer. The expiration time should be a nanosecond count
until the first expiration. The interval should also be in nanoseconds.
new iso create(
notify: TimerNotify iso,
expiration: U64 val,
interval: U64 val = 0)
: Timer iso^

Parameters¶

notify: TimerNotify iso
expiration: U64 val
interval: U64 val = 0

Returns¶

Timer iso^


is_non_empty¶
[Source]
Returns a Bool indicating if the list is non-empty.
fun box is_non_empty()
: Bool val

Returns¶

Bool val

head¶
[Source]
Returns an error, since Nil has no head.
fun box head()
: val->A ?

Returns¶

val->A ?


# Reference capability matrix

Without further ado, here's the reference capability matrix:

---

|                              | Deny global read/write aliases | Deny global write aliases | Don't deny any global aliases |
| --------------------------------- | ------------------------------ | ------------------------- | ----------------------------- |
| __Deny local read/write aliases__ | __`iso`__                      |                           |
| __Deny local write aliases__      | `trn`                          | __`val`__                 |
| __Don't deny any local aliases__  | `ref`                          | `box`                     | __`tag`__                     |
|                              | _(Mutable)_                    | _(Immutable)_             | _(Opaque)_                    |

---

In the context of the matrix, "denying a capability" means that any other alias to that reference is not allowed to do that action. For example, since `trn` denies other local write aliases (but allows reads), this is the only reference that allows writing to the object; and since it denies both read and write aliases to other actors, it's safe to write inside this actor, thus being mutable. And since `box` does not break any guarantees that `trn` makes (local reads are allowed, but global writes are forbidden), we can create `box` aliases to a `trn` reference.

You'll notice that the top-right side is empty. That's because, as previously discussed, we cannot make any local guarantees that are more restrictive than the global guarantees, or we'd end up with invalid capabilities that could be written to in this actor but read somewhere else at the same time.

The matrix also helps visualizing other concepts previously discussed in this chapter:


If the generator generates key-value pairs with
duplicate keys (based on identity),
the pair that is generated later will overwrite earlier entries in the map.
fun box map_is_of[K: K, V: V](
gen: Generator[(K , V)] box,
max: USize val = 100)
: Generator[HashMap[K, V, HashIs[K] val] ref] box

Parameters¶

gen: Generator[(K , V)] box
max: USize val = 100

Returns¶

Generator[HashMap[K, V, HashIs[K] val] ref] box

one_of[T: T]¶
[Source]


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51


### Example

```pony
Iter[USize](Range(0, 4))
.interleave_shortest(Range(4, 6))
```
`0 4 1 5 2`
"""
Iter[A!](
object is Iterator[A!]
var _use_original: Bool = true

fun ref has_next(): Bool =>
if _use_original then
_iter.has_next()
else
other.has_next()
end

fun ref next(): A! ? =>


if _closed and not _readable and not _event.is_null() then
@pony_asio_event_unsubscribe(_event)
end
else
// Unsubscribe immediately.
if not _event.is_null() then
@pony_asio_event_unsubscribe(_event)
_readable = false
end
end

_closed = true

if _fd != -1 then
_notify.closed(this)
// On windows, this will also cancel all outstanding IOCP operations.
@pony_os_socket_close(_fd)
_fd = -1
end


fun frequency_safe[T](
weighted_generators: ReadSeq[WeightedGenerator[T]])
: Generator[T] ?
=>
"""
Version of `frequency` that errors if the given `weighted_generators` is
empty.
"""
Fact(weighted_generators.size() > 0,
"cannot use frequency_safe on empty ReadSeq[WeightedGenerator]")?
Generators.frequency[T](weighted_generators)

fun zip2[T1, T2](
gen1: Generator[T1],
gen2: Generator[T2])
: Generator[(T1, T2)]
=>
"""
Zip two generators into a generator of a 2-tuple


Thus every call to `next()` should be preceeded with a call to `has_next()` to
check for exhaustiveness.


new val create()
: FormatDefault val^

Returns¶

FormatDefault val^

Public Functions¶
eq¶
[Source]
fun box eq(
that: FormatDefault val)
: Bool val

Parameters¶

that: FormatDefault val

Returns¶


532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551


: USize val

Parameters¶

s: String box
offset: ISize val = 0

Returns¶

USize val

at¶
[Source]
Returns true if the substring s is present at the given offset.
fun box at(
s: String box,
offset: ISize val = 0)
: Bool val


process_monitor.pony

1
2
3
4
5
6
7
8
9
10
11


And finally, here the value of __x__ is "no names!"


a._2 = _addr2  // Bits 33-64 of the IPv6 address in host byte order.a._3 = _addr3  // Bits 65-96 of the IPv6 address in host byte order.
`a._4 = _addr4  // Bits 97-128 of the IPv6 address in host byte order.
The contents of the 4-tuple returned are valid only if ip6() is True.
fun box ipv6_addr()
: (U32 val , U32 val , U32 val ,
U32 val)

Returns¶

(U32 val , U32 val , U32 val ,
U32 val)

ne¶
[Source]
fun box ne(
that: NetAddress val)
: Bool val

Parameters¶


U16 val

max¶
[Source]
fun box max(
y: U16 val)
: U16 val

Parameters¶

y: U16 val

Returns¶

U16 val

addc¶
[Source]


U64 val

radix¶
[Source]
Exponent radix.
fun tag radix()
: U8 val

Returns¶

U8 val

precision2¶
[Source]
Mantissa precision in bits.
fun tag precision2()
: U8 val


252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271


(Less val | Equal val | Greater val)


U8 val

rotl¶
[Source]
fun box rotl(
y: U8 val)
: U8 val

Parameters¶

y: U8 val

Returns¶

U8 val

rotr¶
[Source]


y: U128 val

Returns¶

(U128 val , U128 val) ?

shl¶
[Source]
fun box shl(
y: U128 val)
: U128 val

Parameters¶

y: U128 val

Returns¶


U8 val

op_and¶
[Source]
fun box op_and(
y: U8 val)
: U8 val

Parameters¶

y: U8 val

Returns¶

U8 val

op_or¶
[Source]


that: Serialise val)
: Bool val

Parameters¶

that: Serialise val

Returns¶

Bool val

ne¶
[Source]
fun box ne(
that: Serialise val)
: Bool val

Parameters¶


fun box sctp_heartbeat_request()
: I32 val

Returns¶

I32 val

sctp_hmac_ident¶
[Source]
fun box sctp_hmac_ident()
: I32 val

Returns¶

I32 val

sctp_idata¶
[Source]


# Type signature compatibility

Since type signature declarations are scoped to a single Pony package, separate packages might define different FFI signatures for the same C function. In this case, as well as the case where you specify a different return type for an FFI call, the compiler will make sure that all calls and declarations are compatible with each other. Two functions are compatible if their arguments and return types are compatible. Two types are compatible with each other if they have the same ABI size and they can be safely cast to each other. The compiler allows the following type casts:

* Any `struct` type can be cast to any other `struct` (as they are both pointer types)
* Pointers and integers can be cast to each other.

Consider the following example:

```pony
// In library lib_a
use @memcmp[I32](dst: Pointer[None] tag, src: Pointer[None] tag, len: USize)

// In library lib_b
use @memcmp[I32](dst: Pointer[None] tag, src: USize, len: U64)
```

These two declarations have different types for the `src` and `len` parameters. In the case of `src`, the types are compatible since an integer can be cast as a pointer, and vice versa. For `len`, the types will not be compatible on 32 bit platforms, where `USize` is equivalent to `U32`. It is important to take the rules around casting into account when writing type declarations in libraries that will be used by others, as it will avoid any compatibility problems with other libraries.


ANSINotify¶
[Source]
Receive input from an ANSITerm.
interface ref ANSINotify

Public Functions¶
apply¶
[Source]
fun ref apply(
term: ANSITerm ref,
input: U8 val)
: None val


p.next[None](
{(b) => c.fulfill_b(b) },
{() => p'.reject() })

p'

fun tag join(ps: Iterator[Promise[A]]): Promise[Array[A] val] =>
"""
Create a promise that is fulfilled when the receiver and all promises in
the given iterator are fulfilled. If the receiver or any promise in the
sequence is rejected then the new promise is also rejected.

Join `p1` and `p2` with an existing promise, `p3`.
```pony
use "promises"

actor Main
new create(env: Env) =>

let p1 = Promise[String val]


FormatHexSmallBare¶
[Source]
primitive val FormatHexSmallBare is
FormatSpec val

Implements¶

FormatSpec val

Constructors¶
create¶
[Source]


y: ULong val

Returns¶

ULong val ?

mod_unsafe¶
[Source]
fun box mod_unsafe(
y: ULong val)
: ULong val

Parameters¶

y: ULong val

Returns¶


172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191


from: FilePath val

Returns¶

File ref^

Public fields¶
let path: FilePath val¶
[Source]
This is the filesystem path locating this file on the file system
and an object capability granting access to operate on this file.

let writeable: Bool val¶
[Source]
true if the underlying file descriptor has been opened as writeable.

Public Functions¶
errno¶


fun box ip_hdrincl()
: I32 val

Returns¶

I32 val

ip_ipsec_policy¶
[Source]
fun box ip_ipsec_policy()
: I32 val

Returns¶

I32 val

ip_max_group_src_filter¶
[Source]


fun box ne(
that: OpenFile val)
: Bool val

Parameters¶

that: OpenFile val

Returns¶

Bool val


this

class ArrayPairs[A, B: Array[A] #read] is Iterator[(USize, B->A)]
let _array: B
var _i: USize

new create(array: B) =>
_array = array
_i = 0

fun has_next(): Bool =>
_i < _array.size()

fun ref next(): (USize, B->A) ? =>
(_i, _array(_i = _i + 1)?)


352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371


recover SlowDown(
ApplyReleaseBackpressureAuth(env.root), env.out) end, "", "7669")
```


[Source]
fun box eq(
that: (Less val | Equal val | Greater val))
: Bool val

Parameters¶

that: (Less val | Equal val | Greater val)

Returns¶

Bool val

ne¶
[Source]
fun box ne(
that: (Less val | Equal val | Greater val))
: Bool val


fun box add_partial(
y: U128 val)
: U128 val ?

Parameters¶

y: U128 val

Returns¶

U128 val ?

sub_partial¶
[Source]
fun box sub_partial(
y: U128 val)
: U128 val ?

Parameters¶


file_path.pony

1
2
3
4
5
6
7
8
9
10
11


Returns¶

F32 val

tan¶
[Source]
fun box tan()
: F32 val

Returns¶

F32 val

cosh¶
[Source]
fun box cosh()
: F32 val


lt_unsafe¶
fun box lt_unsafe(
y: F32 val)
: Bool val

Parameters¶

y: F32 val

Returns¶

Bool val

le_unsafe¶
fun box le_unsafe(
y: F32 val)
: Bool val

Parameters¶


fun box scm_timestamping()
: I32 val

Returns¶

I32 val

scm_timestampns¶
[Source]
fun box scm_timestampns()
: I32 val

Returns¶

I32 val

scm_wifi_status¶
[Source]


x: box->A!

Returns¶

USize val

hash64¶
[Source]
Hash the identity rather than the contents.
fun box hash64(
x: box->A!)
: U64 val

Parameters¶

x: box->A!

Returns¶


Returns¶

(Cons[A] val | Nil[A] val)

eq[optional T: Equatable[T] val]¶
[Source]
Checks whether two lists are equal.
fun box eq[optional T: Equatable[T] val](
l1: (Cons[T] val | Nil[T] val),
l2: (Cons[T] val | Nil[T] val))
: Bool val ?

Parameters¶

l1: (Cons[T] val | Nil[T] val)
l2: (Cons[T] val | Nil[T] val)

Returns¶


1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251


Returns¶

Bool val

ne¶
[Source]
fun box ne(
that: Nanos val)
: Bool val

Parameters¶

that: Nanos val

Returns¶

Bool val


fun box icmp_host_unreach()
: I32 val

Returns¶

I32 val

icmp_host_unr_tos¶
[Source]
fun box icmp_host_unr_tos()
: I32 val

Returns¶

I32 val

icmp_info_reply¶
[Source]


fun ref reverse_in_place() =>
"""
Reverses the byte order in the string. This needs to be changed to handle
UTF-8 correctly.
"""
if _size > 1 then
var i: USize = 0
var j = _size - 1

while i < j do
let x = _ptr._apply(i)
_set(i, _ptr._apply(j))
_set(j, x)
i = i + 1
j = j - 1
end
end

fun ref push(value: U8) =>
"""


```

FFI functions have the @ symbol before its name, and FFI signatures are declared using the `use` command. The types specified here are considered authoritative, and any FFI calls that use different parameter types will result in a compile error.

The use @ command can take a condition just like other `use` commands. This is useful in this case, since the `_mkdir` function only exists in Windows.

If the name of the C function that you want to call is also a [reserved keyword in Pony](/appendices/keywords.md) (such as `box`), you will need to wrap the name in double quotes (`@"box"`). If you forget to do so, your program will not compile.

An FFI signature is public to all Pony files inside the same package, so you only need to write them once.


that: FileExec val

Returns¶

Bool val

ne¶
[Source]
fun box ne(
that: FileExec val)
: Bool val

Parameters¶

that: FileExec val

Returns¶


fun box ilong()
: ILong val

Returns¶

ILong val

isize¶
[Source]
fun box isize()
: ISize val

Returns¶

ISize val

u8¶
[Source]


132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151


Returns¶

OptionSpec val^

Public Functions¶
name¶
[Source]
Returns the name of this option.
fun box name()
: String val

Returns¶

String val

descr¶
[Source]
Returns the description for this option.


fun netlink_ecryptfs():I32 => @pony_os_sockopt_option(I32(402))
fun netlink_fib_lookup():I32 => @pony_os_sockopt_option(I32(403))
fun netlink_firewall():I32 => @pony_os_sockopt_option(I32(404))
fun netlink_generic():I32 => @pony_os_sockopt_option(I32(405))
fun netlink_inet_diag():I32 => @pony_os_sockopt_option(I32(406))
fun netlink_ip6_fw():I32 => @pony_os_sockopt_option(I32(407))
fun netlink_iscsi():I32 => @pony_os_sockopt_option(I32(408))
fun netlink_kobject_uevent():I32 => @pony_os_sockopt_option(I32(409))
fun netlink_listen_all_nsid():I32 => @pony_os_sockopt_option(I32(410))
fun netlink_list_memberships():I32 => @pony_os_sockopt_option(I32(411))
fun netlink_netfilter():I32 => @pony_os_sockopt_option(I32(412))
fun netlink_nflog():I32 => @pony_os_sockopt_option(I32(413))
fun netlink_no_enobufs():I32 => @pony_os_sockopt_option(I32(414))
fun netlink_pktinfo():I32 => @pony_os_sockopt_option(I32(415))
fun netlink_rdma():I32 => @pony_os_sockopt_option(I32(416))
fun netlink_route():I32 => @pony_os_sockopt_option(I32(417))
fun netlink_rx_ring():I32 => @pony_os_sockopt_option(I32(418))
fun netlink_scsitransport():I32 => @pony_os_sockopt_option(I32(419))
fun netlink_selinux():I32 => @pony_os_sockopt_option(I32(420))
fun netlink_sock_diag():I32 => @pony_os_sockopt_option(I32(421))


fun box ipproto_shim6()
: I32 val

Returns¶

I32 val

ipproto_skip¶
[Source]
fun box ipproto_skip()
: I32 val

Returns¶

I32 val

ipproto_spacer¶
[Source]


352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371


712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731


52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71


: HashSet[this->A!, K]^
=>
"""
Add a value to the set.
"""
clone[K]() .> set(value)

fun sub[K: HashFunction[this->A!] val = H](
value: box->this->A!)
: HashSet[this->A!, K]^
=>
"""
Remove a value from the set.
"""
clone[K]() .> unset(value)

fun op_or[K: HashFunction[this->A!] val = H](
that: this->HashSet[A, H])
: HashSet[this->A!, K]^
=>


192
193
194interface val Flag[A: (Unsigned & Integer[A] val)]
"""
A flag should be a primitive with a value method that returns the bits that
represent the flag. This allows a flag to encode a single bit, or any
combination of bits.
"""
fun value(): A

class Flags[A: Flag[B] val, B: (Unsigned & Integer[B] val) = U64] is
Comparable[Flags[A, B] box]
"""
Flags is a set of flags. The flags that are recognised should be passed as
a union type for type parameter A. For example:

primitive SSE
fun value(): U64 => 1

primitive AVX


152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171


test(_TestClass2)
test(_TestClass3)

fun tag tests(
test: PonyTest tag)
: None val

Parameters¶

test: PonyTest tag

Returns¶

None val


Public Functions¶
string¶
[Source]
fun box string()
: String iso^

Returns¶

String iso^

eq¶
[Source]
fun box eq(
that: KillError val)
: Bool val

Parameters¶


U64¶
[Source]
primitive val U64 is
UnsignedInteger[U64 val] val

Implements¶

UnsignedInteger[U64 val] val

Constructors¶
create¶
[Source]


fun ref _handle_line(term: ANSITerm, line: String) =>
"""
Dispatch a single line.
"""
let promise = Promise[String]

promise.next[Any tag](
recover term~prompt() end,
recover term~dispose() end)

_notify(line, promise)
_cur_pos = 0
_blocked = true

fun ref _refresh_line() =>
"""
Refresh the line on screen.
"""
if not _blocked then


Generator[Bool val] box

u8¶
[Source]
Create a generator for U8 values.
fun box u8(
min: U8 val = call,
max: U8 val = call)
: Generator[U8 val] box

Parameters¶

min: U8 val = call
max: U8 val = call

Returns¶

Generator[U8 val] box


_runner.complete_action(name, true)

fun fail_action(name: String) =>
"""
Call to fail an action, which will also cause the entire test to fail
immediately, without waiting the rest of the outstanding actions.

The name of the failed action will be included in the failure output.

Usually the action name should be an expected action set up by a call to
expect_action, but failing unexpected actions will also fail the test.
"""
_runner.complete_action(name, false)

fun dispose_when_done(disposable: DisposableActor) =>
"""
Pass a disposable actor to be disposed of when the test is complete.
The actor will be disposed no matter whether the test succeeds or fails.

If the test is already tearing down, the actor will be disposed immediately.


Bool val


y: box->A

Returns¶

Bool val

le_unsafe¶
[Source]
Unsafe operation.
If any input of the operation is +/- infinity or NaN, the result is
undefined.
The operation isn't required to fully comply to IEEE 754 semantics.
fun box le_unsafe(
y: box->A)
: Bool val

Parameters¶

y: box->A


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51


412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431


92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111


532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551


fun ip_fw_get():I32 => @pony_os_sockopt_option(I32(262))
fun ip_fw_nat_cfg():I32 => @pony_os_sockopt_option(I32(263))
fun ip_fw_nat_del():I32 => @pony_os_sockopt_option(I32(264))
fun ip_fw_nat_get_config():I32 => @pony_os_sockopt_option(I32(265))
fun ip_fw_nat_get_log():I32 => @pony_os_sockopt_option(I32(266))
fun ip_fw_resetlog():I32 => @pony_os_sockopt_option(I32(267))
fun ip_fw_table_add():I32 => @pony_os_sockopt_option(I32(268))
fun ip_fw_table_del():I32 => @pony_os_sockopt_option(I32(269))
fun ip_fw_table_flush():I32 => @pony_os_sockopt_option(I32(270))
fun ip_fw_table_getsize():I32 => @pony_os_sockopt_option(I32(271))
fun ip_fw_table_list():I32 => @pony_os_sockopt_option(I32(272))
fun ip_fw_zero():I32 => @pony_os_sockopt_option(I32(273))
fun ip_hdrincl():I32 => @pony_os_sockopt_option(I32(274))
fun ip_ipsec_policy():I32 => @pony_os_sockopt_option(I32(275))
fun ip_max_group_src_filter():I32 => @pony_os_sockopt_option(I32(276))
fun ip_max_memberships():I32 => @pony_os_sockopt_option(I32(277))
fun ip_max_sock_mute_filter():I32 => @pony_os_sockopt_option(I32(278))
fun ip_max_sock_src_filter():I32 => @pony_os_sockopt_option(I32(279))
fun ip_max_source_filter():I32 => @pony_os_sockopt_option(I32(280))
fun ip_minttl():I32 => @pony_os_sockopt_option(I32(281))


172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191


le¶
fun box le(
y: F32 val)
: Bool val

Parameters¶

y: F32 val

Returns¶

Bool val

ge¶
fun box ge(
y: F32 val)
: Bool val

Parameters¶


fun box ndrv_deldmxspec()
: I32 val

Returns¶

I32 val

ndrv_delmulticast¶
[Source]
fun box ndrv_delmulticast()
: I32 val

Returns¶

I32 val

ndrv_demuxtype_ethertype¶
[Source]


data: I128 val)
: None val

Parameters¶

data: I128 val

Returns¶

None val

i128_be¶
[Source]
Write an I128 to the buffer in big-endian byte order.
fun ref i128_be(
data: I128 val)
: None val

Parameters¶


fun box ipproto_micp()
: I32 val

Returns¶

I32 val

ipproto_mobile¶
[Source]
fun box ipproto_mobile()
: I32 val

Returns¶

I32 val

ipproto_mpls¶
[Source]


Equal¶
[Source]
primitive val Equal is
Equatable[(Less val | Equal val | Greater val)] ref

Implements¶

Equatable[(Less val | Equal val | Greater val)] ref

Constructors¶
create¶
[Source]


Returns¶

HashSet[A, H] val

op_or¶
[Source]
Return a set with the elements of both this and that.
fun val op_or(
that: (HashSet[A, H] val | Iterator[A] ref))
: HashSet[A, H] val

Parameters¶

that: (HashSet[A, H] val | Iterator[A] ref)

Returns¶

HashSet[A, H] val


352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371


Public Functions¶
string¶
[Source]
fun box string()
: String iso^

Returns¶

String iso^

eq¶
[Source]
fun box eq(
that: ExecveError val)
: Bool val

Parameters¶


fun ref update_offset(offset: ISize, value: U8): U8 ? =>
"""
Changes a byte in the string, returning the previous byte at that offset.
Raise an error if the offset is out of bounds.
"""
this(offset_to_index(offset))? = value

fun clone(): String iso^ =>
"""
Returns a copy of the string. The resulting string is
null-terminated even if the original is not.
"""
let len = _size
let str = recover String(len) end
_ptr._copy_to(str._ptr._unsafe(), len)
str._size = len
str._set(len, 0)
str


| _EscapeMod =>
match c
| 'A' => _up()
| 'B' => _down()
| 'C' => _right()
| 'D' => _left()
| 'H' => _home()
| 'F' => _end()
| '~' => _keypad()
| if (c >= '0') and (c <= '9') =>
// Escape modifier.
_esc_mod = (_esc_mod * 10) + (c - '0')
_esc_buf.push(c)
else
_esc_flush()
end
end
end

// If we are in the middle of an escape sequence, set a timer for 25 ms.


Returns¶

ArgSpec val^

u64¶
[Source]
Creates an Arg with an U64 typed value that can be used like
<cmd> 47
to yield an arg value like
cmd.arg("count").u64() == U64(47).
new val u64(
name': String val,
descr': String val = "",
default': (U64 val | None val) = reference)
: ArgSpec val^

Parameters¶


HashIs[A: A]¶
[Source]
primitive val HashIs[A: A] is
HashFunction[A] val,
HashFunction64[A] val

Implements¶

HashFunction[A] val
HashFunction64[A] val

Constructors¶


972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991


out

fun ref read_until(separator: U8): Array[U8] iso^ ? =>
"""
Find the first occurrence of the separator and return the block of bytes
before its position. The separator is not included in the returned array,
but it is removed from the buffer. To read a line of text, prefer line()
that handles \n and \r\n.
"""
let b = block(_distance_of(separator)? - 1)?
u8()?
b

fun ref line(keep_line_breaks: Bool = false): String iso^ ? =>
"""
Return a \n or \r\n terminated line as a string. By default the newline is not
included in the returned string, but it is removed from the buffer.
Set `keep_line_breaks` to `true` to keep the line breaks in the returned line.
"""


72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91


success: Bool val

Returns¶

None val


[Source]
Unsafe operation.
If this is 0, the result is undefined.
fun box clz_unsafe()
: B

Returns¶

B

ctz_unsafe¶
[Source]
Unsafe operation.
If this is 0, the result is undefined.
fun box ctz_unsafe()
: B

Returns¶


IniParse val^

Public Functions¶
apply¶
[Source]
This accepts a string iterator and returns a nested map of strings. If
parsing fails, an error is raised.
fun box apply(
lines: Iterator[String val] ref)
: HashMap[String val, HashMap[String val, String val, HashEq[String val] val] ref, HashEq[String val] val] ref^ ?

Parameters¶

lines: Iterator[String val] ref

Returns¶

HashMap[String val, HashMap[String val, String val, HashEq[String val] val] ref, HashEq[String val] val] ref^ ?


var min: I32 val¶
[Source]

var hour: I32 val¶
[Source]

var day_of_month: I32 val¶
[Source]

var month: I32 val¶
[Source]

var year: I32 val¶
[Source]

var day_of_week: I32 val¶
[Source]

var day_of_year: I32 val¶
[Source]


fun signature(): Array[U8] val =>
"""
Returns a byte array that is unique to this compiled Pony binary, for the
purposes of comparing before deserialising any data from that source.
It is statistically impossible for two serialisation-incompatible Pony
binaries to have the same serialise signature.
"""
@"internal.signature"()

primitive SerialiseAuth
"""
This is a capability that allows the holder to serialise objects. It does not
allow the holder to examine serialised data or to deserialise objects.
"""
new create(auth: AmbientAuth) =>
None

primitive DeserialiseAuth
"""
This is a capability token that allows the holder to deserialise objects. It


172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191


yield_after_writing: USize val = 16384

Returns¶

TCPConnection tag^

ip4¶
[Source]
Connect via IPv4.
new tag ip4(
auth: TCPConnectAuth val,
notify: TCPConnectionNotify iso,
host: String val,
service: String val,
from: String val = "",
read_buffer_size: USize val = 16384,
yield_after_reading: USize val = 16384,
yield_after_writing: USize val = 16384)
: TCPConnection tag^


212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231


fun ref sentv(conn: TCPConnection ref, data: ByteSeqIter): ByteSeqIter =>
if not _throttled then
data
else
recover Array[String] end
end

fun ref throttled(connection: TCPConnection ref) =>
_throttled = true

fun ref unthrottled(connection: TCPConnection ref) =>
_throttled = false

fun ref connect_failed(conn: TCPConnection ref) =>
None

actor Main
new create(env: Env) =>
TCPConnection(TCPConnectAuth(env.root),