fun mod_unsafe(y: A): A => this.rem_unsafe(y)

fun shl_unsafe(y: A): A =>
"""
Unsafe operation.
If non-zero bits are shifted-out, the result is undefined.
"""
this <<~ y

fun shr_unsafe(y: A): A =>
"""
Unsafe operation.
If non-zero bits are shifted-out, the result is undefined.
"""
this >>~ y

fun rotl(y: A): A =>
let y' = y % bitwidth()
if y' == y'.min_value() then
this._value()


_readable = true
_queue_read()
_pending_reads()

be write(data: ByteSeq) =>
"""
Write a single sequence of bytes. Data will be silently discarded if the
connection has not yet been established though.
"""
if _connected and not _closed then
_in_sent = true
write_final(_notify.sent(this, data))
_in_sent = false
end

be writev(data: ByteSeqIter) =>
"""
Write a sequence of sequences of bytes. Data will be silently discarded if
the connection has not yet been established though.


Returns¶

U32 val

tstp¶
[Source]
fun box tstp()
: U32 val

Returns¶

U32 val

cont¶
[Source]
fun box cont()
: U32 val


Returns¶

None val


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


cyan¶
[Source]
Cyan text.
fun box cyan()
: String val

Returns¶

String val

grey¶
[Source]
Grey text.
fun box grey()
: String val

Returns¶

String val


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


fun box usize()
: USize val

Returns¶

USize val

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

Returns¶

F32 val

f64¶
[Source]


# Tear down

Each unit test object may define a `tear_down()` function. This is called after the test has finished allowing the tearing down of any complex environment that had to be set up for the test.

The `tear_down()` function is called for each test regardless of whether it passed or failed. If a test times out tear_down() will be called after `timed_out()` returns.

When a test is in an exclusion group, the `tear_down()` call is considered part of the tests run. The next test in the exclusion group will not start until after `tear_down()` returns on the current test.

The test's `TestHelper` is handed to `tear_down()` and it is permitted to log messages and call assert functions during tear down.


HashByteSeq¶
[Source]
Hash and equality functions for arbitrary ByteSeq.
primitive val HashByteSeq is
HashFunction[(String box | Array[U8 val] box)] val,
HashFunction64[(String box | Array[U8 val] box)] val

Implements¶

HashFunction[(String box | Array[U8 val] box)] val
HashFunction64[(String box | Array[U8 val] box)] val


fun box usize_unsafe()
: USize val

Returns¶

USize val

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

Returns¶

F32 val

f64_unsafe¶
[Source]


# Compiler Arguments

`ponyc`, the compiler, is usually called in the project directory, where it finds the `.pony` files and its dependencies automatically. There it will create the binary based on the directory name. You can override this and tune the compilation with several options as described via `ponyc --help` and you can pass a separate source directory as an argument.

```bash
ponyc [OPTIONS] <package directory>
```

The most useful options are `--debug`, `--path` or just `-p`, `--output` or just `-o` and `--docs` or `-g`.

`--debug` will skip the LLVM optimizations passes. This should not be mixed up with `make config=debug`, the default make configuration target. `config=debug` will create DWARF symbols, and add slower assertions to ponyc, but not to the generated binaries. For those, you can omit DWARF symbols with the `--strip` or `-s` option.

`--path` or `-p` take a `:` separated path list as the argument and adds those to the compile-time library paths for the linker to find source packages and the native libraries, static or dynamic, being linked at compile-time or via the FFI at run-time. The system adds several paths already, e.g. on windows it queries the registry to find the compiler run-time paths, you can also use `use "lib:path"` statements in the source code and as a final possibility, you can add `-p` paths. But if you want the generated binary to accept such a path to find a dynamic library on your client system, you need to handle that in your source code by yourself. See the `options` package for this.

`--output` or `-o` takes a directory name where the final binary is created.

`--docs` or -`g` creates a directory of the package with documentation in [Read the Docs](http://readthedocs.org) format, i.e. markdown with nice navigation.

Let's study the documentation of the builtin standard library:


new val create()
: FormatHexBare val^

Returns¶

FormatHexBare val^

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

Parameters¶

that: FormatHexBare val

Returns¶


192
193use "buffered"

primitive Help
fun general(cs: CommandSpec box): CommandHelp =>
"""
Creates a command help that can print a general program help message.
"""
CommandHelp._create(None, cs)

fun for_command(cs: CommandSpec box, argv: Array[String] box)
: (CommandHelp | SyntaxError)
=>
"""
Creates a command help for a specific command that can print a detailed
help message.
"""
_parse(cs, CommandHelp._create(None, cs), argv)

fun _parse(cs: CommandSpec box, ch: CommandHelp, argv: Array[String] box)


fun box shr_unsafe(
y: ULong val)
: ULong val

Parameters¶

y: ULong val

Returns¶

ULong val

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

Parameters¶


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


new val min_normalised()
new val epsilon()
fun tag radix(): U8
fun tag precision2(): U8
fun tag precision10(): U8
fun tag min_exp2(): I16
fun tag min_exp10(): I16
fun tag max_exp2(): I16
fun tag max_exp10(): I16

fun add_unsafe(y: A): A =>
"""
Unsafe operation.
If any input or output of the operation is +/- infinity or NaN, the result
is undefined.
The operation isn't required to fully comply to IEEE 754 semantics.
"""
this +~ y

fun sub_unsafe(y: A): A =>


[Source]
Unsafe operation.
If the value doesn't fit in the destination type, the result is undefined.
fun box f32_unsafe()
: F32 val

Returns¶

F32 val

f64_unsafe¶
[Source]
Unsafe operation.
If the value doesn't fit in the destination type, the result is undefined.
fun box f64_unsafe()
: F64 val

Returns¶


fun tcp_vendor():I32 => @pony_os_sockopt_option(I32(1042))
fun tcp_window_clamp():I32 => @pony_os_sockopt_option(I32(1043))
fun tipc_addr_id():I32 => @pony_os_sockopt_option(I32(1044))
fun tipc_addr_mcast():I32 => @pony_os_sockopt_option(I32(1045))
fun tipc_addr_name():I32 => @pony_os_sockopt_option(I32(1046))
fun tipc_addr_nameseq():I32 => @pony_os_sockopt_option(I32(1047))
fun tipc_cfg_srv():I32 => @pony_os_sockopt_option(I32(1048))
fun tipc_cluster_scope():I32 => @pony_os_sockopt_option(I32(1049))
fun tipc_conn_shutdown():I32 => @pony_os_sockopt_option(I32(1050))
fun tipc_conn_timeout():I32 => @pony_os_sockopt_option(I32(1051))
fun tipc_critical_importance():I32 => @pony_os_sockopt_option(I32(1052))
fun tipc_destname():I32 => @pony_os_sockopt_option(I32(1053))
fun tipc_dest_droppable():I32 => @pony_os_sockopt_option(I32(1054))
fun tipc_errinfo():I32 => @pony_os_sockopt_option(I32(1055))
fun tipc_err_no_name():I32 => @pony_os_sockopt_option(I32(1056))
fun tipc_err_no_node():I32 => @pony_os_sockopt_option(I32(1057))
fun tipc_err_no_port():I32 => @pony_os_sockopt_option(I32(1058))
fun tipc_err_overload():I32 => @pony_os_sockopt_option(I32(1059))
fun tipc_high_importance():I32 => @pony_os_sockopt_option(I32(1060))
fun tipc_importance():I32 => @pony_os_sockopt_option(I32(1061))


ansi.pony

1
2
3
4
5
6
7
8
9
10
11


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


List[B] ref^

flat_map[B: B]¶
[Source]
Builds a new List by applying a function to every element of the List,
producing a new List for each element, then flattened into a single List.
let my_list = List[String].from(["a"; "b"; "c"])
let other_list = my_list.flat_map[String]( {(s: String): List[String] => List[String].from( ["m"; s] )} )  // other_list is ["m"; "a"; "m"; "b"; "m"; c"]

fun box flat_map[B: B](
f: {(this->A!): List[B]}[A, B] box)
: List[B] ref^

Parameters¶

f: {(this->A!): List[B]}[A, B] box

Returns¶


ASCIIAll val | ASCIIAllWithNUL val) = reference

Returns¶

Generator[String val] box

ascii_printable¶
[Source]
Create a generator for strings of printable ASCII characters,
with a minimum length of min (default: 0)
and a maximum length of max (default: 100).
fun box ascii_printable(
min: USize val = 0,
max: USize val = 100)
: Generator[String val] box

Parameters¶

min: USize val = 0


setsockopt¶
[Source]
General wrapper for TCP sockets to the setsockopt(2) system call.
The caller is responsible for the correct size and byte contents of
the option array for the requested level and option_name,
including using the appropriate machine endian byte order.
This function returns 0 on success, else the value of errno on
failure.
Usage example:
// connected() is a callback function for class TCPConnectionNotify
fun ref connected(conn: TCPConnection ref) =>
let sb = Writer

sb.u32_le(7744)             // Our desired socket buffer size
let sbytes = Array[U8]
for bs in sb.done().values() do
sbytes.append(bs)
end
match conn.setsockopt(OSSockOpt.sol_socket(), OSSockOpt.so_rcvbuf(), sbytes)


exponent: I32 val)
: F64 val

Parameters¶

x: F64 val
exponent: I32 val

Returns¶

F64 val

frexp¶
[Source]
fun box frexp()
: (F64 val , U32 val)

Returns¶


### Example

```pony
Iter[I64]([1; 2].values())
.zip[I64]([3; 4].values())
```
`(1, 3) (2, 4)`
"""
Iter[(A, B)](
object is Iterator[(A, B)]
let _i1: Iterator[A] = _iter
let _i2: Iterator[B] = i2

fun ref has_next(): Bool =>
_i1.has_next() and _i2.has_next()

fun ref next(): (A, B) ? =>
(_i1.next()?, _i2.next()?)
end)


fun box ipctl_gif_ttl()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipctl_intrdqmaxlen¶
[Source]


Bool val

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

Parameters¶

that: ApplyReleaseBackpressureAuth val

Returns¶

Bool val


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


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


"""
// if `data` is 1 cacheline or less in size
// copy it into the existing `_current` array
// to coalesce multiple tiny arrays
// into a single bigger array
if data.size() <= 64 then
match data
| let d: String =>
let a = d.array()
_current.copy_from(a, 0, _current.size(), a.size())
| let d: Array[U8] val =>
_current.copy_from(d, 0, _current.size(), d.size())
end
_size = _size + data.size()
else
_append_current()
_chunks.push(data)
_size = _size + data.size()
end


precision (ie a normalised number).
fun tag min_exp2()
: I16 val

Returns¶

I16 val

min_exp10¶
[Source]
Minimum exponent value such that (10^exponent) - 1 is representable at full
precision (ie a normalised number).
fun tag min_exp10()
: I16 val

Returns¶

I16 val


U64 val | U128 val | ULong val |
USize val) & Real[N] val)](
n: N)
: N

Parameters¶

n: N

Returns¶

N

int[optional N: ((U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val) & Real[N] val)]¶
[Source]
fun ref int[optional N: ((U8 val | U16 val | U32 val |
U64 val | U128 val | ULong val |
USize val) & Real[N] val)](
n: N)


8

9
16

16
16

17
32

Call the compact() method to ask the GC to reclaim unused space. There are
no guarantees that the GC will actually reclaim any space.
class ref Array[A: A] is
Seq[A] ref


fun fsck(): U64 => _id(0, 1 << 18)
fun fstat(): U64 => _id(0, 1 << 19)
fun fstatat(): U64 => fstat() or lookup()
fun fstatfs(): U64 => _id(0, 1 << 20)
fun futimes(): U64 => _id(0, 1 << 21)
fun futimesat(): U64 => futimes() or lookup()

fun linkat(): U64 => _id(0, 1 << 22) or lookup()
fun mkdirat(): U64 => _id(0, 1 << 23) or lookup()
fun mkfifoat(): U64 => _id(0, 1 << 24) or lookup()
fun mknodat(): U64 => _id(0, 1 << 25) or lookup()
fun renameat(): U64 => _id(0, 1 << 26) or lookup()
fun symlinkat(): U64 => _id(0, 1 << 27) or lookup()
fun unlinkat(): U64 => _id(0, 1 << 28) or lookup()

fun accept(): U64 => _id(0, 1 << 29)
fun bind(): U64 => _id(0, 1 << 30)
fun connect(): U64 => _id(0, 1 << 31)
fun getpeername(): U64 => _id(0, 1 << 32)
fun getsockname(): U64 => _id(0, 1 << 33)


: None val

Parameters¶

conn: TCPConnection ref

Returns¶

None val

proxy_via¶
[Source]
Called before before attempting to connect to the destination server
In order to connect via proxy, return the host & service for the proxy
server.
An implementation of this function might look like:
let _proxy_host = "some-proxy.example.com"
let _proxy_service = "80"
var _destination_host: ( None | String )


y: box->A

Returns¶

Bool val

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

Parameters¶

y: box->A

Returns¶

Bool val


```pony
let my_list = List[String].from(["a"; "b"; "c"])
let other_list = List[String].from(["d"; "e"; "f"])
my_list.prepend_list(other_list)  // my_list is ["d"; "e"; "f"; "a"; "b"; "c"], other_list is empty
```
"""
if this isnt that then
while that._size > 0 do
try prepend_node(that.tail()?) end
end
end

fun ref push(a: A) =>
"""
Adds a new tail value.

```pony
let my_list = List[String].from(["a"; "b"; "c"])
my_list.push("d")  // my_list is ["a"; "b"; "c"; "d"]
```


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


y: F32 val

Returns¶

F32 val

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

Parameters¶

y: F32 val

Returns¶


ILong val

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

Returns¶

ISize val

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

Returns¶


y: I128 val

Returns¶

I128 val

op_xor¶
[Source]
fun box op_xor(
y: I128 val)
: I128 val

Parameters¶

y: I128 val

Returns¶


y: I16 val

Returns¶

I16 val

mul¶
[Source]
fun box mul(
y: I16 val)
: I16 val

Parameters¶

y: I16 val

Returns¶


AsioEvent¶
[Source]
Functions for asynchronous event notification.
primitive val AsioEvent

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

Returns¶


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


Returns¶

U16 val ?

u32¶
[Source]
fun box u32(
base: U8 val = 0)
: U32 val ?

Parameters¶

base: U8 val = 0

Returns¶

U32 val ?


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


Add the K, V pairs from the given iterator to the map.
fun val concat(
iter: Iterator[(val->K , val->V)] ref)
: HashMap[K, V, H] val

Parameters¶

iter: Iterator[(val->K , val->V)] ref

Returns¶

HashMap[K, V, H] val

add¶
[Source]
Return this Map with the given (key, value) mapping.
fun val add(
key: K,
value: val->V)


Parameters¶

f: {ref(A!): Bool ?}[A] ref

Returns¶

Iter[A!] ref^

filter_map_stateful[B: B]¶
[Source]
Allows stateful modification to the stream of elements from an iterator,
similar to filter_map.
fun ref filter_map_stateful[B: B](
f: {ref(A!): (B^ | None) ?}[A, B] ref)
: Iter[B] ref^

Parameters¶

f: {ref(A!): (B^ | None) ?}[A, B] ref


i32¶
[Source]
fun box i32(
base: U8 val = 0)
: I32 val ?

Parameters¶

base: U8 val = 0

Returns¶

I32 val ?

i64¶
[Source]
fun box i64(
base: U8 val = 0)
: I64 val ?


IntProperty¶
[Source]
A property implementation for conveniently evaluating properties
for all Pony Integer types at once.
The property needs to be formulated inside the method int_property:
class DivisionByZeroProperty is IntProperty
fun name(): String => "div/0"

fun int_property[T: (Int & Integer[T] val)](x: T, h: PropertyHelper)? =>
h.assert_eq[T](T.from[U8](0), x / T.from[U8](0))

trait ref IntProperty is
Property1[IntPropertySample ref] ref


Bool val


# How PonyCheck implements Property Based Testing

A property based test in PonyCheck consists of the following:

* A name (mostly for integration into PonyTest)
* One or more generators, depending on how your property is laid out.
There are tons of them defined in the primitive
[Generators](pony_check-Generators.md).
* A `property` method that asserts a certain property for each sample
generated by the [Generator(s)](pony_check-Generator.md) with the help of
[PropertyHelper](pony_check-PropertyHelper.md), which tries to expose a
similar API   as [TestHelper](pony_test-TestHelper.md).
* Optionally, the method `params()` can be used to configure how PonyCheck
executes the property by specifying a custom
[PropertyParams](pony_check-PropertyParams.md) object.

The classical list-reverse example:

```pony
use "collections"


elseif A <: I128 then
_FormatInt.u128(abs.u128(), neg, fmt, prefix, prec, width, align, fill)
elseif A <: (U64 | I64) then
_FormatInt.u64(abs.u64(), neg, fmt, prefix, prec, width, align, fill)
elseif A <: (U32 | I32) then
_FormatInt.u32(abs.u32(), neg, fmt, prefix, prec, width, align, fill)
elseif A <: (U16 | I16) then
_FormatInt.u16(abs.u16(), neg, fmt, prefix, prec, width, align, fill)
elseif A <: (U8 | I8) then
_FormatInt.u8(abs.u8(), neg, fmt, prefix, prec, width, align, fill)
elseif A <: (USize | ISize) then
ifdef ilp32 then
_FormatInt.u32(abs.u32(), neg, fmt, prefix, prec, width, align, fill)
else
_FormatInt.u64(abs.u64(), neg, fmt, prefix, prec, width, align, fill)
end
elseif A <: (ULong | ILong) then
ifdef ilp32 or llp64 then
_FormatInt.u32(abs.u32(), neg, fmt, prefix, prec, width, align, fill)
else


_UnsignedPartialArithmetic.mul_partial[U32](this, y)?

fun div_partial(y: U32): U32 ? =>
_UnsignedPartialArithmetic.div_partial[U32](this, y)?

fun rem_partial(y: U32): U32 ? =>
_UnsignedPartialArithmetic.rem_partial[U32](this, y)?

fun divrem_partial(y: U32): (U32, U32) ? =>
_UnsignedPartialArithmetic.divrem_partial[U32](this, y)?

primitive U64 is UnsignedInteger[U64]
new create(value: U64) => value
new from[A: (Number & Real[A] val)](a: A) => a.u64()

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

fun next_pow2(): U64 =>
let x = (this - 1).clz()


U32 val

u64¶
fun box u64()
: U64 val

Returns¶

U64 val

ulong¶
fun box ulong()
: ULong val

Returns¶

ULong val


"""
Unsafe operation.
If y is 0, the result is undefined.
If the operation overflows, the result is undefined.
"""
ifdef native128 then
this %~ y
else
this % y
end

fun f32(): F32 =>
f64().f32()

fun f64(): F64 =>
if this < 0 then
-(-u128()).f64()
else
u128().f64()
end


fun box dso_conaccept()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

dso_condata¶
[Source]


fun box i64_unsafe()
: I64 val

Returns¶

I64 val

i128_unsafe¶
[Source]
fun box i128_unsafe()
: I128 val

Returns¶

I128 val

ilong_unsafe¶
[Source]


692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711


Parameters¶

that: HashSet[A, H] box

Returns¶

Bool val

gt¶
[Source]
Returns true if every element in that is also in this, and this has more
elements than that.
fun box gt(
that: HashSet[A, H] box)
: Bool val

Parameters¶

that: HashSet[A, H] box


# Exclusion groups

By default, all tests are run concurrently. This may be a problem for some tests, e.g. 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.


1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151


fun ipproto_carp():I32 => @pony_os_sockopt_level(I32(4011))
fun ipproto_cftp():I32 => @pony_os_sockopt_level(I32(4012))
fun ipproto_chaos():I32 => @pony_os_sockopt_level(I32(4013))
fun ipproto_cmtp():I32 => @pony_os_sockopt_level(I32(4014))
fun ipproto_comp():I32 => @pony_os_sockopt_level(I32(4015))
fun ipproto_cphb():I32 => @pony_os_sockopt_level(I32(4016))
fun ipproto_cpnx():I32 => @pony_os_sockopt_level(I32(4017))
fun ipproto_dccp():I32 => @pony_os_sockopt_level(I32(4018))
fun ipproto_ddp():I32 => @pony_os_sockopt_level(I32(4019))
fun ipproto_dgp():I32 => @pony_os_sockopt_level(I32(4020))
fun ipproto_divert():I32 => @pony_os_sockopt_level(I32(4021))
fun ipproto_done():I32 => @pony_os_sockopt_level(I32(4022))
fun ipproto_dstopts():I32 => @pony_os_sockopt_level(I32(4023))
fun ipproto_egp():I32 => @pony_os_sockopt_level(I32(4024))
fun ipproto_emcon():I32 => @pony_os_sockopt_level(I32(4025))
fun ipproto_encap():I32 => @pony_os_sockopt_level(I32(4026))
fun ipproto_eon():I32 => @pony_os_sockopt_level(I32(4027))
fun ipproto_esp():I32 => @pony_os_sockopt_level(I32(4028))
fun ipproto_etherip():I32 => @pony_os_sockopt_level(I32(4029))
fun ipproto_fragment():I32 => @pony_os_sockopt_level(I32(4030))


fun box add_unsafe(
y: I128 val)
: I128 val

Parameters¶

y: I128 val

Returns¶

I128 val

sub_unsafe¶
[Source]
fun box sub_unsafe(
y: I128 val)
: I128 val

Parameters¶


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


None val

u64_be¶
[Source]
Write a U64 to the buffer in big-endian byte order.
fun ref u64_be(
data: U64 val)
: None val

Parameters¶

data: U64 val

Returns¶

None val


v: Vec[A] val

Returns¶

VecValues[A] ref^

Public Functions¶
has_next¶
[Source]
fun box has_next()
: Bool val

Returns¶

Bool val

next¶
[Source]


fun box bytewidth()
: USize val

Returns¶

USize val

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

Parameters¶

y: U64 val

Returns¶


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


fun ref any(f: {(A!): Bool ?} box): Bool =>
"""
Return true if at least one value of the iterator matches the predicate
`f`. This method short-circuits at the first value where the predicate
returns true, otherwise false is returned.


```

"""

fun ref has_next(): Bool
"""
Returns `true` if this Iterator is not yet exhausted.
That means that a value returned from a subsequent call to `next()`
is a valid part of this iterator.

Returns `false` if this Iterator is exhausted.

The behavior of `next()` after this function returned `false` is undefined,
it might throw an error or return values which are not part of this Iterator.
"""

fun ref next(): A ?
"""
Generate the next value.


fun ref _set_head(head': (ListNode[A] | None)) =>
"""
Private method to control mutating `_head` field.
"""
_head = head'

fun ref _set_tail(tail': (ListNode[A] | None)) =>
"""
Private method to control mutating `_tail` field.
"""
_tail = tail'

fun ref _set_both(node: ListNode[A]) =>
"""
Private method to set both `_head` and `_tail` to the same node,
creating a `List` with a `_size` of 1.
"""
node._set_list(this)
_head = node
_tail = node


ifdef windows then
try
// Add an IOCP write.
_pending_writev_windows .> push((data.size(), data.cpointer()))
_pending_writev_total = _pending_writev_total + data.size()

// Write as much data as possible
// Returns how many we sent or 0 if we are experiencing backpressure
let len = @pony_os_writev(_event,
_pending_writev_windows.cpointer(_pending_sent), I32(1))?

if len == 0 then
_apply_backpressure()
else
_pending_sent = _pending_sent + len
end
end
else
_pending_writev_posix .> push((data.cpointer(), data.size()))
_pending_writev_total = _pending_writev_total + data.size()


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


I32¶
[Source]
primitive val I32 is
SignedInteger[I32 val, U32 val] val

Implements¶

SignedInteger[I32 val, U32 val] val

Constructors¶
create¶
[Source]


fun ref u32(
min: U32 val = call,
max: U32 val = call)
: U32 val

Parameters¶

min: U32 val = call
max: U32 val = call

Returns¶

U32 val

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


fun box shr(
y: U32 val)
: U32 val

Parameters¶

y: U32 val

Returns¶

U32 val

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

Parameters¶


fun ref push(value: A): Bool =>
"""
Add an element to the ring. If the ring is full, this will drop the oldest
element in the ring. Returns true if an element was dropped.
"""
var full = false

if _write < space() then
_array.push(consume value)
else
try _array(_write and _mod)? = consume value end
full = true
end

_write = _write + 1
full

fun ref clear() =>
"""


: ULong val

Returns¶

ULong val

usize_unsafe¶
fun box usize_unsafe()
: USize val

Returns¶

USize val

f32_unsafe¶
fun box f32_unsafe()
: F32 val


"""
ifdef native128 then
(this *~ y, this /~ y)
else
divrem(y)
end

fun div_unsafe(y: I128): I128 =>
"""
Unsafe operation.
If y is 0, the result is undefined.
If the operation overflows, the result is undefined.
"""
ifdef native128 then
this /~ y
else
this / y
end

fun rem_unsafe(y: I128): I128 =>


Returns¶

Bool val

offset_to_index¶
[Source]
fun box offset_to_index(
i: ISize val)
: USize val

Parameters¶

i: ISize val

Returns¶

USize val


close¶
[Source]
Attempt to perform a graceful shutdown. Don't accept new writes. If the
connection isn't muted then we won't finish closing until we get a zero
length read. If the connection is muted, perform a hard close and shut
down immediately.
fun ref close()
: None val

Returns¶

None val

hard_close¶
[Source]
When an error happens, do a non-graceful close.
fun ref hard_close()


Returns¶

ArrayValues[A, this->Array[A] ref] ref^

pairs¶
[Source]
Return an iterator over the (index, value) pairs in the array.
fun box pairs()
: ArrayPairs[A, this->Array[A] ref] ref^

Returns¶

ArrayPairs[A, this->Array[A] ref] ref^


U8 val

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

Returns¶

U16 val

u32_unsafe¶
[Source]
fun box u32_unsafe()
: U32 val

Returns¶


Parameters¶

s: String box = "
"

Returns¶

None val

add¶
[Source]
Return a string that is a concatenation of this and that.
fun box add(
that: String box)
: String iso^

Parameters¶


## Reading from an `iso` variable

Anything read through an `iso` origin has to maintain the isolation guarantee that the origin has. The key thing to remember is that the `iso` can be sent to another actor and it can also become any other reference capability. So when we read a field, we need to get a result that won't ever break the isolation guarantees that the origin makes, that is, _read and write uniqueness_.

An `iso` field makes the same guarantees as an `iso` origin, so that's fine to read. A `val` field is _globally immutable_, which means it's always ok to read it, no matter what the origin is (well, other than `tag`).

Everything else, though, can break our isolation guarantees. That's why other reference capabilities are seen as `tag`: it's the only type that is neither readable nor writable.


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


fun ref next(): U8 ? =>
_string(_i = _i + 1)?

class StringRunes is Iterator[U32]
let _string: String box
var _i: USize

new create(string: String box) =>
_string = string
_i = 0

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

fun ref next(): U32 ? =>
(let rune, let len) = _string.utf32(_i.isize())?
_i = _i + len.usize()
rune

primitive _UTF32Encoder


1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071


## Annotations in the Pony compiler

The following annotations are recognised by the Pony compiler. Note that the Pony compiler will ignore annotations that it doesn't recognise, as well as the annotations described here if they're encountered in an unexpected place.


fun box icmp_prec_violation()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

icmp_redirect¶
[Source]


new val create(
value: ILong val)
: ILong val^

Parameters¶

value: ILong val

Returns¶

ILong val^

from[A: ((I8 val | I16 val | I32 val | I64 val | I128 val | ILong val | ISize val | U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val | F32 val | F64 val) & Real[A] val)]¶
[Source]
new val from[A: ((I8 val | I16 val | I32 val |
I64 val | I128 val | ILong val |
ISize val | U8 val | U16 val |
U32 val | U64 val | U128 val |
ULong val | USize val | F32 val |


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

Parameters¶

that: HashIs[A] val

Returns¶

Bool val


let samples: USize
"""
Total number of samples to be measured. (Default: 20)
"""
let max_iterations: U64
"""
Maximum number of iterations to execute per sample. (Default: 1_000_000_000)
"""
let max_sample_time: U64
"""
Maximum time to execute a sample in Nanoseconds. (Default: 100_000_000)
"""

new val create(
samples': USize = 20,
max_iterations': U64 = 1_000_000_000,
max_sample_time': U64 = 100_000_000)
=>
samples = samples'
max_iterations = max_iterations'


generator.pony

1
2
3
4
5
6
7
8
9
10
11


y: U16 val

Returns¶

U16 val

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

Parameters¶

y: U16 val

Returns¶


iter: Iterator[A^] ref
offset: USize val = 0
len: USize val = call

Returns¶

None val

find¶
[Source]
Find the nth appearance of value from the beginning of the array,
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 array, returns
the first instance of value found, and uses object identity for
comparison.
fun box find(


fun box mmap_w()
: U64 val

Returns¶

U64 val

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

Returns¶

U64 val

mmap_rw¶
[Source]


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


property_unit_test.pony

1
2
3
4
5
6
7
8
9
10
11


to yield an arg value like
`cmd.arg("count").u64() == U64(47)`.
"""
_name = name'
_descr = descr'
(_typ, _default, _required) = _init(_U64Type, default')

new val f64(name': String,
descr': String = "",
default': (F64 | None) = None)
=>
"""
Creates an Arg with a F64 typed value that can be used like
`<cmd> 1.039`
to yield an arg value like
`cmd.arg("ratio").f64() == F64(1.039)`.
"""
_name = name'
_descr = descr'
(_typ, _default, _required) = _init(_F64Type, default')


if windows
use @QueryPerformanceFrequency[I32](frequency: Pointer[(U32, U32)]) if windows
use @QueryPerformanceCounter[I32](count: Pointer[(U32, U32)]) if windows

type _Clock is (_ClockRealtime | _ClockMonotonic)

primitive _ClockRealtime
fun apply(): U32 =>
ifdef linux or bsd then
0
else
compile_error "no clock_gettime realtime clock"
end

primitive _ClockMonotonic
fun apply(): U32 =>
ifdef linux then
1
elseif bsd then
4


```

Here is a full list of all available conversions for numeric types:

---

| Safe conversion | Unsafe conversion |
| --------------- | ----------------- |
| `u8()`            | `u8_unsafe()`       |
| `u16()`           | `u16_unsafe()`      |
| `u32()`           | `u32_unsafe()`      |
| `u64()`           | `u64_unsafe()`      |
| `u128()`          | `u128_unsafe()`     |
| `ulong()`         | `ulong_unsafe()`    |
| `usize()`         | `usize_unsafe()`    |
| `i8()`            | `i8_unsafe()`       |
| `i16()`           | `i16_unsafe()`      |
| `i32()`           | `i32_unsafe()`      |
| `i64()`           | `i64_unsafe()`      |
| `i128()`          | `i128_unsafe()`     |


predicate: {(A, A): Bool} val = {(l: A, r: A): Bool => l is r })
: Bool
=>
"""
Returns true if the vector contains `value`, false otherwise.
"""
for v in values() do
if predicate(v, value) then return true end
end
false

fun val slice(from: USize = 0, to: USize = -1, step: USize = 1): Vec[A] =>
"""
Return a vector that is a clone of a portion of this vector. The range is
exclusive and saturated.
"""
var vec = Vec[A]
for i in mut.Range(0, if _size < to then _size else to end, step) do
try vec.push(this(i)?) end
end


compile_intrinsic

fun tag lt(that: Pointer[A] tag): Bool =>
"""
Return true if this address is less than that address.
"""
compile_intrinsic

fun tag ne(that: Pointer[A] tag): Bool => not eq(that)
fun tag le(that: Pointer[A] tag): Bool => lt(that) or eq(that)
fun tag ge(that: Pointer[A] tag): Bool => not lt(that)
fun tag gt(that: Pointer[A] tag): Bool => not le(that)

fun tag hash(): USize =>
"""
Returns a hash of the address.
"""
usize().hash()

fun tag hash64(): U64 =>


fun box ipproto_irtp()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipproto_larp¶
[Source]


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


Bool val

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

Parameters¶

that: FormatDefault val

Returns¶

Bool val


fun box repeat_str(
num: USize val = 1,
sep: String val = "")
: String iso^

Parameters¶

num: USize val = 1
sep: String val = ""

Returns¶

String iso^

mul¶
[Source]
Returns a copy of the string repeated num times.
fun box mul(
num: USize val)


52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69use "collections"

primitive FileCreate


h: TestHelper val

Returns¶

None val ?

exclusion_group¶
fun box exclusion_group()
: String val

Returns¶

String val

timed_out¶
fun ref timed_out(
h: TestHelper val)
: None val


I8 val

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

Parameters¶

y: I8 val

Returns¶

(I8 val , I8 val)

rem_unsafe¶
[Source]


Create a PonyTest object and use it to run the tests from the given
TestList
"""
_env = env
_process_opts()
_groups.push(("", _SimultaneousGroup))
@ponyint_assert_disable_popups()
list.tests(this)
_all_tests_applied()

be apply(test: UnitTest iso) =>
"""
Run the given test, subject to our filters and options.
"""
if _do_nothing then
return
end

var name = test.name()


fun so_label():I32 => @pony_os_sockopt_option(I32(842))
fun so_linger():I32 => @pony_os_sockopt_option(I32(843))
fun so_linger_sec():I32 => @pony_os_sockopt_option(I32(844))
fun so_linkinfo():I32 => @pony_os_sockopt_option(I32(845))
fun so_listenincqlen():I32 => @pony_os_sockopt_option(I32(846))
fun so_listenqlen():I32 => @pony_os_sockopt_option(I32(847))
fun so_listenqlimit():I32 => @pony_os_sockopt_option(I32(848))
fun so_lock_filter():I32 => @pony_os_sockopt_option(I32(849))
fun so_mark():I32 => @pony_os_sockopt_option(I32(850))
fun so_max_msg_size():I32 => @pony_os_sockopt_option(I32(851))
fun so_max_pacing_rate():I32 => @pony_os_sockopt_option(I32(852))
fun so_multipoint():I32 => @pony_os_sockopt_option(I32(853))
fun so_netsvc_marking_level():I32 => @pony_os_sockopt_option(I32(854))
fun so_net_service_type():I32 => @pony_os_sockopt_option(I32(855))
fun so_nke():I32 => @pony_os_sockopt_option(I32(856))
fun so_noaddrerr():I32 => @pony_os_sockopt_option(I32(857))
fun so_nofcs():I32 => @pony_os_sockopt_option(I32(858))
fun so_nosigpipe():I32 => @pony_os_sockopt_option(I32(859))
fun so_notifyconflict():I32 => @pony_os_sockopt_option(I32(860))
fun so_no_check():I32 => @pony_os_sockopt_option(I32(861))


I64 val

i128_unsafe¶
[Source]
fun box i128_unsafe()
: I128 val

Returns¶

I128 val

ilong_unsafe¶
[Source]
fun box ilong_unsafe()
: ILong val

Returns¶


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


392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411


I64 val

i128¶
[Source]
fun box i128()
: I128 val

Returns¶

I128 val

ilong¶
[Source]
fun box ilong()
: ILong val

Returns¶


h: TestHelper val)
: None val

Parameters¶

h: TestHelper val

Returns¶

None val

label¶
fun box label()
: String val

Returns¶

String val


Reserve space for len elements.
"""

fun size(): USize
"""
Returns the number of elements in the sequence.
"""

fun apply(i: USize): this->A ?
"""
Returns the i-th element of the sequence. Raises an error if the index
is out of bounds.
"""

fun ref update(i: USize, value: A): A^ ?
"""
Replaces the i-th element of the sequence. Returns the previous value.
Raises an error if the index is out of bounds.
"""


y: I64 val

Returns¶

I64 val ?

mod_partial¶
[Source]
fun box mod_partial(
y: I64 val)
: I64 val ?

Parameters¶

y: I64 val

Returns¶


Returns¶

Bool val

rename¶
[Source]
Rename source (which is relative to this directory) to target (which is
relative to the to directory).
fun box rename(
source: String val,
to: Directory box,
target: String val)
: Bool val

Parameters¶

source: String val
to: Directory box
target: String val


fun box ipv6_tlv_pad1()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipv6_tlv_routeralert¶
[Source]


92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108use @pony_os_stdout[Pointer[U8]]()
use @pony_os_stderr[Pointer[U8]]()
use @pony_os_std_flush[None](file: Pointer[None] tag)
use @pony_os_std_print[None](file: Pointer[None] tag, buffer: Pointer[U8] tag,


ULong val

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

Parameters¶

y: ULong val

Returns¶

ULong val

fldc¶
[Source]


primitive TCPAuth
primitive TCPConnectAuth
actor TCPConnection
interface TCPConnectionNotify
primitive TCPListenAuth
interface TCPListenNotify
actor TCPListener
primitive UDPAuth
interface UDPNotify
actor UDPSocket


if to_vol != target_vol then
error
end

to_i = to_vol.size().isize()
end

var to_0 = to_i
var target_i = to_i
var target_0 = target_i

while true do
to_i = try
to_clean.find(sep(), to_i)?
else
to_clean.size().isize()
end

target_i = try


Parameters¶

len: USize val

Returns¶

BinaryHeap[A, P] ref^

Public Functions¶
clear¶
[Source]
Remove all elements from the heap.
fun ref clear()
: None val

Returns¶

None val


fun box sol_tipc()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

af_coip¶
[Source]


# Rights are part of a capability

If you open a file in UNIX and get a file descriptor back, that file descriptor is a token that designates an object - but it isn't a capability. To be a capability, we need to open that file with some permission - some access right. For example:

```C
int fd = open("/etc/passwd", O_RDWR);
```

Now we have a token and a set of rights.

In Pony, every reference has both a type and a reference capability. In fact, the reference capability is _part_ of its type. These allow you to specify which of your objects can be shared with other actors and allow the compiler to check that what you're doing is concurrency safe.


"""
match l
| let cons: Cons[A] =>
_map[B](cons.tail(), f, acc.prepend(f(cons.head())))
else
acc.reverse()
end

fun val flat_map[B](f: {(val->A): List[B]} box): List[B] =>
"""
Builds a new list by applying a function to every member of the list and
using the elements of the resulting lists.
"""
_flat_map[B](this, f, Nil[B])

fun _flat_map[B](l: List[A], f: {(val->A): List[B]} box, acc: List[B]):
List[B] =>
"""
Private helper for flat_map, recursively working on elements.
"""


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


Flush any data out to the os (ignoring failures).
be flush()


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


U128 val

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

Returns¶

U128 val

bit_reverse¶
[Source]
fun box bit_reverse()
: U128 val

Returns¶


Returns¶

U32 val

quit¶
[Source]
fun box quit()
: U32 val

Returns¶

U32 val

ill¶
[Source]
fun box ill()
: U32 val


812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831


trim¶
[Source]
Return a shared portion of this array, covering from until to.
Both the original and the new array are immutable, as they share memory.
The operation does not allocate a new array pointer nor copy elements.
fun val trim(
from: USize val = 0,
to: USize val = call)
: Array[A] val

Parameters¶

from: USize val = 0
to: USize val = call

Returns¶

Array[A] val


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


Returns¶

None val ?

add_help¶
[Source]
Adds a standard help option and, optionally command, to a root command.
fun ref add_help(
hname: String val = "help",
descr': String val = "")
: None val ?

Parameters¶

hname: String val = "help"
descr': String val = ""

Returns¶


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


# Partial functions

Pony does not require that all errors are handled immediately as in our previous examples. Instead, functions can raise errors that are handled by whatever code calls them. These are called partial functions (this is a mathematical term meaning a function that does not have a defined result for all possible inputs, i.e. arguments). Partial functions __must__ be marked as such in Pony with a `?`, both in the function signature (after the return type) and at the call site (after the closing parentheses).

For example, a somewhat contrived version of the factorial function that accepts a signed integer will error if given a negative input. It's only partially defined over its valid input type.

```pony
fun factorial(x: I32): I32 ? =>
if x < 0 then error end
if x == 0 then
1
else
x * factorial(x - 1)?
end
```

Everywhere that an error can be generated in Pony (an error command, a call to a partial function, or certain built-in language constructs) must appear within a `try` block or a function that is marked as partial. This is checked at compile time, ensuring that an error cannot escape handling and crash the program.

Prior to Pony 0.16.0, call sites of partial functions were not required to be marked with a `?`. This often led to confusion about the possibilities for control flow when reading code. Having every partial function call site clearly marked makes it very easy for the reader to immediately understand everywhere that a block of code may jump away to the nearest error handler, making the possible control flow paths more obvious and explicit.


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

"""
var _listen: (TCPListener | None) = None
var _notify: TCPConnectionNotify
var _connect_count: U32
var _fd: U32 = -1
var _event: AsioEventID = AsioEvent.none()
var _connected: Bool = false
var _readable: Bool = false
var _reading: Bool = false
var _writeable: Bool = false
var _throttled: Bool = false
var _closed: Bool = false
var _shutdown: Bool = false
var _shutdown_peer: Bool = false
var _in_sent: Bool = false
embed _pending_writev_posix: Array[(Pointer[U8] tag, USize)] = _pending_writev_posix.create()
embed _pending_writev_windows: Array[(USize, Pointer[U8] tag)] = _pending_writev_windows.create()


include <stdlib.h>


fun ref home(ctrl: Bool = false, alt: Bool = false, shift: Bool = false) =>
"""
Beginning of the line.
"""
_cur_pos = 0
_refresh_line()

fun ref end_key(
ctrl: Bool = false,
alt: Bool = false,
shift: Bool = false)
=>
"""
End of the line.
"""
_cur_pos = _edit.size().isize()
_refresh_line()

fun ref _backspace() =>
"""


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


try
while srclen >= 3 do
let in1 = data(i)?
let in2 = data(i + 1)?
let in3 = data(i + 2)?

let out1 = in1 >> 2
let out2 = ((in1 and 0x03) << 4) + (in2 >> 4)
let out3 = ((in2 and 0x0f) << 2) + (in3 >> 6)
let out4 = in3 and 0x3f

out.push(_enc_byte(out1, at62, at63)?)
out.push(_enc_byte(out2, at62, at63)?)
out.push(_enc_byte(out3, at62, at63)?)
out.push(_enc_byte(out4, at62, at63)?)

i = i + 3
blocks = blocks + 1
srclen = srclen - 3


fun box sem_wait()
: U64 val

Returns¶

U64 val

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

Returns¶

U64 val

kqueue_event¶
[Source]


_store.push(_iter.next()?)
return _store(_store.size() - 1)?
end

_first_time_through = false
end

if not _store_iter.has_next() then
_store_iter.rewind()
end

_store_iter.next()?
end)

fun ref dedup[H: HashFunction[A] val = HashIs[A]](): Iter[A!]^ =>
"""
Return an iterator that removes duplicates from consecutive identical
elements. Equality is determined by the HashFunction `H`.


fun ref u32()
: U32 val

Returns¶

U32 val

u64¶
fun ref u64()
: U64 val

Returns¶

U64 val

u128¶
fun ref u128()
: U128 val


fun box usize_unsafe()
: USize val

Returns¶

USize val

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

Returns¶

F32 val

f64_unsafe¶
[Source]


Parameters¶

y: ILong val

Returns¶

Bool val

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

Parameters¶

y: ILong val

Returns¶


fun ref usize(
min: USize val = call,
max: USize val = call)
: USize val

Parameters¶

min: USize val = call
max: USize val = call

Returns¶

USize val

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


else
false
end
```

__But what if my if doesn't have an else?__ Any `else` branch that doesn't exist gives an implicit `None`.

```pony
var x: (String | None) =
if friendly then
"Hello"
end
```

The same rules that apply to the value of an `if` expression applies to loops as well. Let's take a look at what a loop value would look like:

```pony
actor Main
new create(env: Env) =>
var x: (String | None) =


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


ISize val

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

Returns¶

U8 val

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

Returns¶


String val

bright_green¶
[Source]
Bright green text.
fun box bright_green()
: String val

Returns¶

String val

bright_yellow¶
[Source]
Bright yellow text.
fun box bright_yellow()
: String val


fun box netlink_add_membership()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

netlink_broadcast_error¶
[Source]


Returns¶

U32 val

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

Returns¶

U32 val

bitwidth¶
[Source]


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


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

Implements¶

UnsignedInteger[U16 val] val

Constructors¶
create¶
[Source]


512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531


Term package¶
The Term package provides support for building text-based user interfaces in ANSI terminals.
Public Types¶

primitive ANSI
interface ANSINotify
actor ANSITerm
primitive EraseLeft
primitive EraseLine
primitive EraseRight
class Readline
interface ReadlineNotify


fun sctp_pr_assoc_status():I32 => @pony_os_sockopt_option(I32(742))
fun sctp_pr_stream_status():I32 => @pony_os_sockopt_option(I32(743))
fun sctp_pr_supported():I32 => @pony_os_sockopt_option(I32(744))
fun sctp_reconfig_supported():I32 => @pony_os_sockopt_option(I32(745))
fun sctp_recvnxtinfo():I32 => @pony_os_sockopt_option(I32(746))
fun sctp_recvrcvinfo():I32 => @pony_os_sockopt_option(I32(747))
fun sctp_recv_rwnd_logging_enable():I32 => @pony_os_sockopt_option(I32(748))
fun sctp_remote_udp_encaps_port():I32 => @pony_os_sockopt_option(I32(749))
fun sctp_reset_assoc():I32 => @pony_os_sockopt_option(I32(750))
fun sctp_reset_streams():I32 => @pony_os_sockopt_option(I32(751))
fun sctp_reuse_port():I32 => @pony_os_sockopt_option(I32(752))
fun sctp_rtoinfo():I32 => @pony_os_sockopt_option(I32(753))
fun sctp_rttvar_logging_enable():I32 => @pony_os_sockopt_option(I32(754))
fun sctp_sack_cmt_dac():I32 => @pony_os_sockopt_option(I32(755))
fun sctp_sack_logging_enable():I32 => @pony_os_sockopt_option(I32(756))
fun sctp_sack_nonce_sum():I32 => @pony_os_sockopt_option(I32(757))
fun sctp_sack_rwnd_logging_enable():I32 => @pony_os_sockopt_option(I32(758))
fun sctp_sat_network_burst_incr():I32 => @pony_os_sockopt_option(I32(759))
fun sctp_sat_network_min():I32 => @pony_os_sockopt_option(I32(760))
fun sctp_sb_logging_enable():I32 => @pony_os_sockopt_option(I32(761))


(U8 val , Bool val)

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

Parameters¶

y: U8 val

Returns¶

U8 val ?

mod_unsafe¶
[Source]


fun u128_unsafe(): U128 =>
"""
Unsafe operation.
If the value doesn't fit in the destination type, the result is undefined.
"""
compile_intrinsic

fun ulong_unsafe(): ULong =>
"""
Unsafe operation.
If the value doesn't fit in the destination type, the result is undefined.
"""
compile_intrinsic

fun usize_unsafe(): USize =>
"""
Unsafe operation.
If the value doesn't fit in the destination type, the result is undefined.
"""


end
(let host', let service') = _notify.proxy_via(host, service)
_connect_count =
@pony_os_connect_tcp(this, host'.cstring(), service'.cstring(),
from.cstring(), asio_flags)
_notify_connecting()

new ip4(
auth: TCPConnectAuth,
notify: TCPConnectionNotify iso,
host: String,
service: String,
from: String = "",
read_buffer_size: USize = 16384,
yield_after_reading: USize = 16384,
yield_after_writing: USize = 16384)
=>
"""
Connect via IPv4.
"""


# Enumeration with values

```pony
primitive Black fun apply(): U32 => 0xFF000000
primitive Red   fun apply(): U32 => 0xFFFF0000
```


Bool val

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

Parameters¶

y: U32 val

Returns¶

Bool val

ge¶
[Source]


primitive ExecveError
fun string(): String iso^ => "ExecveError".clone()
```


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


EraseLine¶
[Source]
primitive val EraseLine

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

Returns¶

EraseLine val^


"""
Check that the 2 given expressions are equal.
"""
if expect != actual then
fail(_format_loc(loc) + "Assert " + check + " failed. " + msg
+ " Expected (" + expect.string() + ") == (" + actual.string() + ")")
return false
end

log(_format_loc(loc) + "Assert " + check + " passed. " + msg
+ " Got (" + expect.string() + ") == (" + actual.string() + ")", true)
true

fun assert_isnt[A](
not_expect: A,
actual: A,
msg: String = "",
loc: SourceLoc = __loc)
: Bool
=>


932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951


952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971


U32 val

setsockopt_u32¶
[Source]
General wrapper for TCP sockets to the setsockopt(2) system call where
the kernel expects an option value of a C uint32_t type / Pony
type U32.
This function returns 0 on success, else the value of errno on
failure.
fun ref setsockopt_u32(
level: I32 val,
option_name: I32 val,
option: U32 val)
: U32 val

Parameters¶

level: I32 val
option_name: I32 val


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

Parameters¶

a: B

Returns¶

U8 val^

min_value¶
[Source]
new val min_value()
: U8 val^

Returns¶


12
13
14
15
16
17
18
19
20
21
22
23primitive NetAuth
new create(from: AmbientAuth) =>
None

primitive DNSAuth
new create(from: (AmbientAuth | NetAuth)) =>
None

primitive UDPAuth


fun box ipv6_xfrm_policy()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipx_address_notify¶
[Source]


# Embedded Fields

Unlike local variables, some types of fields can be declared using `embed`. Specifically, only classes or structs can be embedded - interfaces, traits, primitives and numeric types cannot. A field declared using `embed` is similar to one declared using `let`, but at the implementation level, the memory for the embedded class is laid out directly within the outer class. Contrast this with `let` or `var`, where the implementation uses pointers to reference the field class. Embedded fields can be passed to other functions in exactly the same way as `let` or `var` fields. Embedded fields must be initialised from a constructor expression.

__Why would I use `embed`?__ `embed` avoids a pointer indirection when accessing a field and a separate memory allocation when creating that field. By default, it is advised to use `embed` if possible. However, since an embedded field is allocated alongside its parent object, exterior references to the field forbids garbage collection of the parent, which can result in higher memory usage if a field outlives its parent. Use `let` if this is a concern for you.


fun box usize_unsafe()
: USize val

Returns¶

USize val

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

Returns¶

F32 val

f64_unsafe¶
[Source]


| 24 => _fn_key(12)
| 25 => _fn_key(13)
| 26 => _fn_key(14)
| 28 => _fn_key(15)
| 29 => _fn_key(16)
| 31 => _fn_key(17)
| 32 => _fn_key(18)
| 33 => _fn_key(19)
| 34 => _fn_key(20)
end

fun ref _up() =>
"""
Up arrow.
"""
(let ctrl, let alt, let shift) = _mod()
_notify.up(ctrl, alt, shift)
_esc_clear()

fun ref _down() =>


# Recursion

Recursive functions in Pony can cause many problems. Every function call in a program adds a frame on the system call stack, which is bounded. If the stack grows too big it will overflow, usually crashing the program. This is an out-of-memory type of error and it cannot be prevented by the guarantees offered by Pony.

If you have a heavy recursive algorithm, you must take some precautions in your code to avoid stack overflows. Most recursive functions can be easily transformed into tail-recursive function which are less problematic. A tail-recursive function is a function in which the recursive call is the last instruction of the function. Here is an example with a factorial function:

```pony
fun recursive_factorial(x: U32): U32 =>
if x == 0 then
1
else
x * recursive_factorial(x - 1)
end

fun tail_recursive_factorial(x: U32, y: U32): U32 =>
if x == 0 then
y
else
tail_recursive_factorial(x - 1, x * y)
end


Parameters¶

failed_repr: String val

expect_action¶
[Source]
be expect_action(
name: String val,
round: (_Shrink val | _Run val))

Parameters¶

name: String val
round: (_Shrink val | _Run val)

complete_action¶
[Source]


fun box mulc(
y: ULong val)
: (ULong val , Bool val)

Parameters¶

y: ULong val

Returns¶

(ULong val , Bool val)

divc¶
[Source]
fun box divc(
y: ULong val)
: (ULong val , Bool val)

Parameters¶


least_common_multiple.pony

1
2
3
4
5
6
7
8
9
10
11


let timers = Timers
let timer = Timer(Notify(env), 5_000_000_000, 2_000_000_000)
timers(consume timer)

class Notify is TimerNotify
let _env: Env
var _counter: U32 = 0

new iso create(env: Env) =>
_env = env

fun ref apply(timer: Timer, count: U64): Bool =>
_env.out.print(_counter.string())
_counter = _counter + 1
true

class ref Timer

Constructors¶
create¶


# Local variables

Local variables in Pony work very much as they do in other languages, allowing you to store temporary values while you perform calculations. Local variables live within a chunk of code (they are _local_ to that chunk) and are created every time that code chunk executes and disposed of when it completes.

To define a local variable the `var` keyword is used (`let` can also be used, but we'll get to that later). Right after the `var` comes the variable's name, and then you can (optionally) put a `:` followed by the variable's type. For example:

```pony
var x: String = "Hello"
```

Here, we're assigning the __string literal__ `"Hello"` to `x`.

You don't have to give a value to the variable when you define it: you can assign one later if you prefer. If you try to read the value from a variable before you've assigned one, the compiler will complain instead of allowing the dreaded _uninitialised variable_ bug.

Every variable has a type, but you don't have to specify it in the declaration if you provide an initial value. The compiler will automatically use the type of the initial value of the variable.

The following definitions of `x`, `y` and `z` are all effectively identical.

```pony
var x: String = "Hello"


let filtered_list = new_list.filter({ (n) => n.string().contains("d BOOM!") })
env.out.print("Filtering our three-node list produces a new list of size: "
+ filtered_list.size().string()) // 2
for n in filtered_list.values() do
env.out.print("\t" + n.string()) // Second BOOM!\nThird BOOM!
end

// Partition the filtered list
let partitioned_lists = filtered_list.partition({ (n) => n.string().contains("Second") })
env.out.print("The size of our first partitioned list (matches predicate): " + partitioned_lists._1.size().string())        // 1
env.out.print("The size of our second partitioned list (doesn't match predicate): " + partitioned_lists._2.size().string())  // 1
env.out.print("Our matching partition elements are:")
for n in partitioned_lists._1.values() do
env.out.print("\t" + n.string()) // Second BOOM!
end

class ref List[A: A] is
Seq[A] ref

Implements¶


fun box ipproto_spacer()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipproto_st¶
[Source]


fun box sctp_cc_option()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_cc_opt_steady_step¶
[Source]


Returns¶

String iso^

add¶
fun box add(
y: F64 val)
: F64 val

Parameters¶

y: F64 val

Returns¶

F64 val

sub¶


fun hash64(): U64 =>
var x = u64()

x = (not x) + (x << 21)
x = x xor (x >> 24)
x = (x + (x << 3)) + (x << 8)
x = x xor (x >> 14)
x = (x + (x << 2)) + (x << 4)
x = x xor (x >> 28)
x = x + (x << 31)

x

fun _value(): A => compile_intrinsic

trait val Integer[A: Integer[A] val] is Real[A]
fun add_unsafe(y: A): A =>
"""
Unsafe operation.


if _closed then
return
end

_closed = true

if not _event.is_null() then
@pony_asio_event_unsubscribe(_event)

@pony_os_socket_close(_fd)
_fd = -1

_notify.closed(this)
end


"""
Called when new data is received on the socket.
"""
None

fun ref closed(sock: UDPSocket ref) =>
"""
Called when the socket is closed.
"""
None


Returns¶

A^ ?

pop¶
[Source]
Remove the item from the node, if we have one, otherwise raise an error.
fun ref pop()
: A^ ?

Returns¶

A^ ?

prepend¶
[Source]
Prepend a node to this one. If that is already in a list, it is removed
before it is prepended. Returns true if that was removed from another


y: F64 val

Returns¶

Bool val

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

Parameters¶

y: F64 val

Returns¶

Bool val


if (i + s.size()) <= _size then
@memcmp(_ptr._offset(i), s._ptr, s._size) == 0
else
false
end

fun ref delete(offset: ISize, len: USize = 1) =>
"""
Delete len bytes at the supplied offset, compacting the string in place.
"""
let i = offset_to_index(offset)

if i < _size then
let n = len.min(_size - i)
_size = _size - n
_ptr._offset(i)._delete(n, _size - i)
_set(_size, 0)
end


v: Vec[A] val

Returns¶

VecPairs[A] ref^

Public Functions¶
has_next¶
[Source]
fun box has_next()
: Bool val

Returns¶

Bool val

next¶
[Source]


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


i32¶
fun box i32()
: I32 val

Returns¶

I32 val

i64¶
fun box i64()
: I64 val

Returns¶

I64 val

ilong¶
fun box ilong()


DeserialiseAuth¶
[Source]
This is a capability token that allows the holder to deserialise objects. It
does not allow the holder to serialise objects or examine serialised data.
primitive val DeserialiseAuth

Constructors¶
create¶
[Source]
new val create(
auth: AmbientAuth val)
: DeserialiseAuth val^


fun ref _pending_writes(): Bool =>
"""
Write pending data.
Returns false if the file wasn't opened with write permission.
Returns false and closes the file and discards all pending data
if not all the bytes were written.
Returns true if it sent all pending data.
"""
try
(let result, let num_written, let new_pending_total) =
_write_to_disk()?
_pending_writev_total = new_pending_total
if _pending_writev_total == 0 then
_pending_writev.clear()
_unsynced_data = true
_unsynced_metadata = true
else
if num_written > 0 then
_unsynced_data = true


Parameters¶

y: ISize val

Returns¶

(ISize val , Bool val)

divc¶
[Source]
fun box divc(
y: ISize val)
: (ISize val , Bool val)

Parameters¶

y: ISize val

Returns¶


# Comparison to exceptions in other languages

Pony errors behave very much the same as those in C++, Java, C#, Python, and Ruby. The key difference is that Pony errors do not have a type or instance associated with them. This makes them the same as C++ exceptions would be if a fixed literal was always thrown, e.g. `throw 3;`. This difference simplifies error handling for the programmer and allows for much better runtime error handling performance.

The `else` handler in a `try` expression is just like a `catch(...)` in C++, `catch(Exception e)` in Java or C#, `except:` in Python, or `rescue` in Ruby. Since exceptions do not have types there is no need for handlers to specify types or to have multiple handlers in a single try block.

The `then` block in a `try` expression is just like a `finally` in Java, C#, or Python and `ensure` in Ruby.

If required, error handlers can "reraise" by using the `error` command within the handler.


72
73
74
75
76
77
78
79
80
81interface Seq[A]
"""
A sequence of elements.
"""
new create(len: USize = 0)
"""
Create a sequence, reserving space for len elements.
"""

fun ref reserve(len: USize)
"""


let first_w = str_new.find("w") ?
// find first occurrence of letter "d"
let first_d = str_new.find("d") ?

// get substring capturing "world"
let substr = str_new.substring(first_w, first_d+1)
// clone substring
let substr_clone = substr.clone()

// print our substr
env.out.print(consume substr)
end
```
"""
var _size: USize
var _alloc: USize
var _ptr: Pointer[U8]

new create(len: USize = 0) =>
"""


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


fun box mulc(
y: I16 val)
: (I16 val , Bool val)

Parameters¶

y: I16 val

Returns¶

(I16 val , Bool val)

divc¶
[Source]
fun box divc(
y: I16 val)
: (I16 val , Bool val)

Parameters¶


fun box sctp_cmt_base()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_cmt_mptcp¶
[Source]


fun _search(key: box->K!): (USize, Bool) =>
"""
Return a slot number and whether or not it's currently occupied.
"""
var idx_del = _array.size()
let mask = idx_del - 1
let h = H.hash(key).usize()
var idx = h and mask

try
for i in Range(0, _array.size()) do
let entry = _array(idx)?

match entry
| (let k: this->K!, _) =>
if H.eq(k, key) then
return (idx, true)
end
| _MapEmpty =>


532
533
534
535
536
537
538
539
540
541
542use "time"

use @ponyint_o_rdonly[I32]()
use @ponyint_o_rdwr[I32]()
use @ponyint_o_creat[I32]()
use @ponyint_o_trunc[I32]()
use @ponyint_o_directory[I32]()
use @ponyint_o_cloexec[I32]()
use @ponyint_at_removedir[I32]()
use @openat[I32](fd: I32, path: Pointer[U8] tag, flags: I32, ...)


Returns¶

None val

union¶
[Source]
The union of this and that.
fun ref union(
that: Flags[A, B] box)
: None val

Parameters¶

that: Flags[A, B] box

Returns¶

None val


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


fun ref difference(
that: Flags[A, B] box)
: None val

Parameters¶

that: Flags[A, B] box

Returns¶

None val

remove¶
[Source]
Unset flags that are set in that.
fun ref remove(
that: Flags[A, B] box)
: None val


recover ThrowItAway end, "", "7669")

In general, unless you have a very specific use case, we strongly advise that
you don't implement a load shedding scheme where you drop data.
Read¶
If your application is unable to keep up with data being sent to it over
a TCPConnection you can use the builtin read backpressure support to
pause reading the socket which will in turn start to exert backpressure on
the corresponding writer on the other end of that socket.
The mute behavior allow any other actors in your application to request
the cessation of additional reads until such time as unmute is called.
Please note that this cessation is not guaranteed to happen immediately as
it is the result of an asynchronous behavior call and as such will have to
wait for existing messages in the TCPConnection's mailbox to be handled.
On non-windows platforms, your TCPConnection will not notice if the
other end of the connection closes until you unmute it. Unix type systems
like FreeBSD, Linux and OSX learn about a closed connection upon read. On
these platforms, you must call unmute on a muted connection to have
it close. Without calling unmute the TCPConnection actor will never
exit.


: None val

Parameters¶

s: String box = "
"

Returns¶

None val

lstrip¶
[Source]
Remove all leading characters within the string that are in s. By default,
leading whitespace is removed.
fun ref lstrip(
s: String box = "
")
: None val


 Example code
```pony
// Parses the file 'example.ini' in the current working directory
// Output all the content
use "ini"
use "files"

actor Main
new create(env:Env) =>
try
let ini_file = File(FilePath(FileAuth(env.root), "example.ini"))
let sections = IniParse(ini_file.lines())?
for section in sections.keys() do
env.out.print("Section name is: " + section)
for key in sections(section)?.keys() do
env.out.print(key + " = " + sections(section)?(key)?)
end
end
end
```


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


[Source]
fun box neg_unsafe()
: ILong val

Returns¶

ILong val

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

Parameters¶

y: ILong val

Returns¶


fun ref u128(
min: U128 val = call,
max: U128 val = call)
: U128 val

Parameters¶

min: U128 val = call
max: U128 val = call

Returns¶

U128 val

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


class HashMap[K, V, H: HashFunction[K] val]
"""
A quadratic probing hash map. Resize occurs at a load factor of 0.75. A
resized map has 2 times the space. The hash function can be plugged in to the
type to create different kinds of maps.
"""
var _size: USize = 0
var _array: Array[((K, V) | _MapEmpty | _MapDeleted)]

new create(prealloc: USize = 6) =>
"""
Create an array with space for prealloc elements without triggering a
resize. Defaults to 6.
"""
let len = (prealloc * 4) / 3
let n = len.max(8).next_pow2()
_array = _array.init(_MapEmpty, n)

fun size(): USize =>


let fi = FileInfo(path')?

if fi.directory and not fi.symlink then
let directory = open(target)?

for entry in directory.entries()?.values() do
if not directory.remove(entry) then
return false
end
end

0 == @unlinkat(_fd, target.cstring(), @ponyint_at_removedir())
else
0 == @unlinkat(_fd, target.cstring(), 0)
end
else
path'.remove()
end
else
false


fun box tcp_repair_options()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

tcp_rxt_conndroptime¶
[Source]


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


_seek(-offset.i64(), 2)
end

fun ref seek(offset: ISize) =>
"""
Move the cursor position.
"""
if path.caps(FileSeek) then
_seek(offset.i64(), 1)
end

fun ref sync() =>
"""
Sync the file contents to physical storage.
"""
if path.caps(FileSync) and (_fd != -1) then
ifdef windows then
let r = @FlushFileBuffers(@_get_osfhandle(_fd))
if r == true then
_errno = FileError


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

Returns¶

String val

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

Parameters¶


fun box ipproto_blt()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipproto_carp¶
[Source]


val->A ?

values¶
[Source]
Returns an iterator over the elements of the list.
fun box values()
: Iterator[val->A] ref^

Returns¶

Iterator[val->A] ref^

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


Bool val

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

Parameters¶

that: FormatExp val

Returns¶

Bool val


[Source]
Change the notifier.
be set_notify(
notify: TCPListenNotify iso)

Parameters¶

notify: TCPListenNotify iso

dispose¶
[Source]
Stop listening.
be dispose()

Public Functions¶
local_address¶
[Source]
Return the bound IP address.


actor Actor2
be dispose() => None // dispose of resources here.

actor Actor3
be dispose() => None // dispose of resources here.

actor Main
new create(env: Env) =>
let actor1 = Actor1
let actor2 = Actor2
let actor3 = Actor3

let custodian = Custodian
custodian(actor1)
custodian(actor2)
custodian(actor3)

SignalHandler(TermHandler(custodian), Sig.term())


those that do not.

```pony
let my_list = List[String].from(["a"; "b"; "c"])
(let lt_b, let gt_b) = my_list.partition( {(s: String): Bool => s < "b"} )  // lt_b is ["a"], while gt_b is ["b"; "c"]
```
"""
let l1 = List[this->A!]
let l2 = List[this->A!]
for item in values() do
if f(item) then l1.push(item) else l2.push(item) end
end
(l1, l2)

fun drop(n: USize): List[this->A!]^ =>
"""
Builds a `List` by dropping the first `n` elements.

```pony
let my_list = List[String].from(["a"; "b"; "c"])


new from_u64(x: U64 = 5489) =>
"""
Use seed x to seed a [SplitMix64](random-SplitMix64.md) and use this to
initialize the 128 bits of state.
"""
let sm = SplitMix64(x)
_x = sm.next()
_y = sm.next()

new create(x: U64 = 5489, y: U64 = 0) =>
"""
Create with the specified seed. Returned values are deterministic for a
given seed.
"""
_x = x
_y = y
next()

fun ref next(): U64 =>


Fulfill[A: Any #share, B: Any #share]¶
[Source]
A function from A to B that is called when a promise is fulfilled.
interface iso Fulfill[A: Any #share, B: Any #share]

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

Parameters¶


fun box ipx_frame_snap()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipx_getnetinfo¶
[Source]


fun box connect()
: U64 val

Returns¶

U64 val

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

Returns¶

U64 val

getsockname¶
[Source]


```pony
let array: Array[String] = ["dog"; "cat"; "wombat"]
let is_second_element_wobat = try
// indexes start from 0, so 1 is the second element
array(1)? == "wombat"
else
false
end
```

Adding and removing elements to and from the end of the Array can be done via
`push` and `pop` methods. You could treat the array as a LIFO stack using
those methods:
```pony
while (array.size() > 0) do
let elem = array.pop()?
// do something with element
end
```


Unsafe operation.
If y is 0, the result is undefined.
If the operation overflows, the result is undefined.
"""
ifdef native128 then
(this *~ y, this /~ y)
else
divrem(y)
end

fun div_unsafe(y: U128): U128 =>
"""
Unsafe operation.
If y is 0, the result is undefined.
If the operation overflows, the result is undefined.
"""
ifdef native128 then
this /~ y
else
this / y


nanos.pony

1
2
3
4
5
6
7
8
9
10
11


white¶
[Source]
White text.
fun box white()
: String val

Returns¶

String val

bright_red¶
[Source]
Bright red text.
fun box bright_red()
: String val

Returns¶


792
793
794
795
796
797use "collections"

class Reader
"""
Store network data and provide a parsing interface.

`Reader` provides a way to extract typed data from a sequence of
bytes. The `Reader` manages the underlying data structures to
provide a read cursor over a contiguous sequence of bytes. It is
useful for decoding data that is received over a network or stored
in a file. Chunk of bytes are added to the `Reader` using the
`append` method, and typed data is extracted using the getter
methods.

For example, suppose we have a UDP-based network data protocol where


i8¶
fun box i8()
: I8 val

Returns¶

I8 val

i16¶
fun box i16()
: I16 val

Returns¶

I16 val


492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509"""


Promises Package¶
A Promise represents a value that will be available at a later
time. Promises can either be fulfilled with a value or rejected. Any
number of function handlers can be added to the Promise, to be
called when the Promise is fulfilled or rejected. These handlers
themselves are also wrapped in Promises so that they can be chained
together in order for the fulfilled value of one Promise to be used
to compute a value which will be used to fulfill the next Promise in
the chain, or so that if the Promise is rejected then the subsequent
reject functions will also be called. The input and output types of a
fulfill handler do not have to be the same, so a chain of fulfill
handlers can transform the original value into something new.
Fulfill and reject handlers can either be specified as classes that


"""
Home key.
"""
(let ctrl, let alt, let shift) = _mod()
_notify.home(ctrl, alt, shift)
_esc_clear()

fun ref _end() =>
"""
End key.
"""
(let ctrl, let alt, let shift) = _mod()
_notify.end_key(ctrl, alt, shift)
_esc_clear()

fun ref _page_up() =>
"""
Page up key.
"""
(let ctrl, let alt, let shift) = _mod()


array.insert(array.size(), 0xBE)?     // append:  [0xDE; 0xBE]
array.insert(1, 0xAD)?                // insert:  [0xDE; 0xAD; 0xBE]
array.insert(array.size() + 1, 0xEF)? // error
```
"""
if i <= _size then
reserve(_size + 1)
_ptr._offset(i)._insert(1, _size - i)
_ptr._update(i, consume value)
_size = _size + 1
else
error
end

fun ref delete(i: USize): A^ ? =>
"""
Delete an element from the array. Elements after this are moved down by one
index, compacting the array.
An out of bounds index raises an error.
The deleted element is returned.


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


"""
_size

fun _tail_offset(): USize =>
"""
Return the amount of values in the root.
"""
_size - _tail.size()

fun apply(i: USize): val->A ? =>
"""
Get the i-th element, raising an error if the index is out of bounds.
"""
if i < _tail_offset() then
(_root as _VecNode[A])(_depth, i)?
else
_tail(i - _tail_offset())?
end

fun val update(i: USize, value: val->A): Vec[A] ? =>


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


fun tipc_link_state():I32 => @pony_os_sockopt_option(I32(1062))
fun tipc_low_importance():I32 => @pony_os_sockopt_option(I32(1063))
fun tipc_max_bearer_name():I32 => @pony_os_sockopt_option(I32(1064))
fun tipc_max_if_name():I32 => @pony_os_sockopt_option(I32(1065))
fun tipc_max_link_name():I32 => @pony_os_sockopt_option(I32(1066))
fun tipc_max_media_name():I32 => @pony_os_sockopt_option(I32(1067))
fun tipc_max_user_msg_size():I32 => @pony_os_sockopt_option(I32(1068))
fun tipc_medium_importance():I32 => @pony_os_sockopt_option(I32(1069))
fun tipc_node_recvq_depth():I32 => @pony_os_sockopt_option(I32(1070))
fun tipc_node_scope():I32 => @pony_os_sockopt_option(I32(1071))
fun tipc_ok():I32 => @pony_os_sockopt_option(I32(1072))
fun tipc_published():I32 => @pony_os_sockopt_option(I32(1073))
fun tipc_reserved_types():I32 => @pony_os_sockopt_option(I32(1074))
fun tipc_retdata():I32 => @pony_os_sockopt_option(I32(1075))
fun tipc_sock_recvq_depth():I32 => @pony_os_sockopt_option(I32(1076))
fun tipc_src_droppable():I32 => @pony_os_sockopt_option(I32(1077))
fun tipc_subscr_timeout():I32 => @pony_os_sockopt_option(I32(1078))
fun tipc_sub_cancel():I32 => @pony_os_sockopt_option(I32(1079))
fun tipc_sub_ports():I32 => @pony_os_sockopt_option(I32(1080))
fun tipc_sub_service():I32 => @pony_os_sockopt_option(I32(1081))


# Runtime options for Pony programs

Besides using the `cli` package, there are also several built-in options for the generated binary (_not for use with ponyc_) starting with `--pony*`, see `ponyc --help`, to tweak runtime performance. You can override the number of initial threads, tune cycle detection (_CD_), the garbage collector and even turn off yield, which is not really recommended.


392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411


FileAuth¶
[Source]
primitive val FileAuth

Constructors¶
create¶
[Source]
new val create(
from: AmbientAuth val)
: FileAuth val^

Parameters¶


VecKeys[A: Any #share]¶
[Source]
class ref VecKeys[A: Any #share]

Constructors¶
create¶
[Source]
new ref create(
v: Vec[A] val)
: VecKeys[A] ref^

Parameters¶


h: TestHelper val)
: ForAll4[T1, T2, T3, T4] ref

Parameters¶

gen1: Generator[T1] val
gen2: Generator[T2] val
gen3: Generator[T3] val
gen4: Generator[T4] val
h: TestHelper val

Returns¶

ForAll4[T1, T2, T3, T4] ref

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


1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271


: None val

Parameters¶

listen: TCPListener ref

Returns¶

None val

not_listening¶
[Source]
Called if it wasn't possible to bind the listener to an address.
It is expected to implement proper error handling. You need to opt in to
ignoring errors, which can be implemented like this:
fun ref not_listening(listen: TCPListener ref) =>
None

fun ref not_listening(


MapValues[K: Any #share, V: Any #share, H: HashFunction[K] val]¶
[Source]
class ref MapValues[K: Any #share, V: Any #share, H: HashFunction[K] val]

Constructors¶
create¶
[Source]
new ref create(
m: HashMap[K, V, H] val)
: MapValues[K, V, H] ref^

Parameters¶


fun box sctp_get_peer_addresses()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_get_remote_addr_size¶
[Source]


U8 val

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

Returns¶

U16 val

u32¶
[Source]
fun box u32()
: U32 val

Returns¶


772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791


[Source]
Set the last access and modification times of the directory to the given
values.
fun box set_time(
atime: (I64 val , I64 val),
mtime: (I64 val , I64 val))
: Bool val

Parameters¶

atime: (I64 val , I64 val)
mtime: (I64 val , I64 val)

Returns¶

Bool val

infoat¶
[Source]


Returns¶

None val

push_u32[optional B: (A & Real[B] val & U8 val)]¶
[Source]
Add a U32 to the end of the array. This is only allowed for an array of U8s.
fun ref push_u32[optional B: (A & Real[B] val & U8 val)](
value: U32 val)
: None val

Parameters¶

value: U32 val

Returns¶

None val


: I128 val

Parameters¶

y: I128 val

Returns¶

I128 val

rem_unsafe¶
[Source]
Unsafe operation.
If y is 0, the result is undefined.
If the operation overflows, the result is undefined.
fun box rem_unsafe(
y: I128 val)
: I128 val


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


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

Returns¶

None val

left¶
[Source]
Move left.
fun ref left(
ctrl: Bool val = false,
alt: Bool val = false,
shift: Bool val = false)
: None val

Parameters¶


fun box usize()
: USize val

Returns¶

USize val

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

Returns¶

F32 val

f64¶
[Source]


1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211


intarg> := ['-'] numchar...
floatarg ::= ['-'] numchar... ['.' numchar...]
stringarg ::= anychar

Some examples:
usage: ls [<options>] [<args> ...]
usage: make [<options>] <command> [<options>] [<args> ...]
usage: chat [<options>] <command>  <subcommand> [<options>] [<args> ...]

Usage¶
The types in the cli package are broken down into three groups:
Specs¶
Pony programs use constructors to create the spec objects to specify their
command line syntax. Many aspects of the spec are checked for correctness at
compile time, and the result represents everything the parser needs to know
when parsing a command line or forming syntax help messages.
Option and Arg value types¶
Options and Args parse values from the command line as one of four Pony types:
Bool, String, I64 and F64. Values of each of these types can then be
retrieved using the corresponding accessor funtions.


mod_partial¶
[Source]
Calculates the modulo of this number and y after floored division (fld).
The result has the sign of the divisor.
If y is 0 or the operation overflows, this function errors.
fun box mod_partial(
y: A)
: A ?

Parameters¶

y: A

Returns¶

A ?

neg_unsafe¶


### Examples

```pony
Iter[I64]([2; 4; 6].values())
.all({(x) => (x % 2) == 0 })
```
`true`

```pony
Iter[I64]([2; 3; 4].values())
.all({(x) => (x % 2) == 0 })
```
`false`
"""
for x in _iter do
if not (try f(x)? else false end) then
return false
end
end
true


512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531


fun box fld_unsafe(
y: U32 val)
: U32 val

Parameters¶

y: U32 val

Returns¶

U32 val

mod¶
[Source]
fun box mod(
y: U32 val)
: U32 val

Parameters¶


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


fun box i64_unsafe()
: I64 val

Returns¶

I64 val

i128_unsafe¶
[Source]
fun box i128_unsafe()
: I128 val

Returns¶

I128 val

ilong_unsafe¶
[Source]


By default, a `consume` expression returns a type with the capability of the variable that you are assigning to. You can see this in the example above, where we say that `b` is `Wombat iso`, and as such the result of the `consume` expression is `Wombat iso`. We could also have said that `b` is a `Wombat val`, but we can instead give an explicit reference capability to the `consume` expression:

```pony
fun test(a: AnIncrediblyLongTypeName iso) =>
var b = consume val a
```

The expression in line 2 of the example above is equivalent to saying `var b: AnIncrediblyLongTypeName val = consume a`.

__Can I `consume` a field?__ Definitely not! Consuming something means it is empty, that is, it has no value. There's no way to be sure no other alias to the object will access that field. If we tried to access a field that was empty, we would crash. But there's a way to do what you want to do: _destructive read_.


fun box sctp_blk_logging_enable()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_cause_cookie_in_shutdown¶
[Source]


ifdef ilp32 then
(let r, let o) =
@"llvm.sadd.with.overflow.i32"(this.i32(), y.i32())
(r.isize(), o)
else
(let r, let o) =
@"llvm.sadd.with.overflow.i64"(this.i64(), y.i64())
(r.isize(), o)
end

fun subc(y: ISize): (ISize, Bool) =>
ifdef ilp32 then
(let r, let o) =
@"llvm.ssub.with.overflow.i32"(this.i32(), y.i32())
(r.isize(), o)
else
(let r, let o) =
@"llvm.ssub.with.overflow.i64"(this.i64(), y.i64())
(r.isize(), o)
end


to_0 = to_i
target_0 = target_i
end

if
((to_i - to_0) == 2)
and (to_clean.compare_sub("..", 2, to_0) is Equal)
then
error
end

if to_0.usize() != to_clean.size() then
let result = recover String end

try
while true do
to_i = to_clean.find(sep(), to_i)? + 1
result.append("..")
result.append(sep())
end


fun box sctp_data_sack_immediately()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_default_prinfo¶
[Source]


# Compiling the program

Now compile it:

```bash
$ ponyc
Building .
Building builtin
Generating
Optimising
Writing ./helloworld.o
Linking ./helloworld
```

(If you're using Docker, you'd write something like `$ docker run -v Some_Absolute_Path/helloworld:/src/main ponylang/ponyc`, depending of course on what the absolute path to your `helloworld` directory is.)

Look at that! It built the current directory, `.`, plus the stuff that is built into Pony, `builtin`, it generated some code, optimised it, created an object file (don't worry if you don't know what that is), and linked it into an executable with whatever libraries were needed. If you're a C/C++ programmer, that will all make sense to you, otherwise, it probably won't, but that's ok, you can ignore it.

__Wait, it linked too?__ Yes. You won't need a build system (like `make`) for Pony. It handles that for you (including handling the order of dependencies when you link to C libraries, but we'll get to that later).


: U128 val

Returns¶

U128 val

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

Returns¶

ULong val

usize¶
[Source]
fun ref usize()


# What does this look like?

The `recover` expression wraps a list of expressions and is terminated by an `end`, like this:

```pony
recover Array[String].create() end
```

This expression returns an `Array[String] iso`, instead of the usual `Array[String] ref` you would get. The reason it is `iso` and not any of the other mutable reference capabilities is because there is a default reference capability when you don't specify one. The default for any mutable reference capability is `iso` and the default for any immutable reference capability is `val`.

Here's a more complicated example from the standard library:

```pony
recover
var s = String((prec + 1).max(width.max(31)))
var value = x

try
if value == 0 then
s.push(table(0)?)


fun box max(
y: A)
: A

Parameters¶

y: A

Returns¶

A

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

Returns¶


When a failing sample is found, the PonyCheck engine is trying to find a
smaller or more simple sample by shrinking it with `shrink`.
If the generator did not provide any shrinked samples
as a result of `generate`, its `shrink` method is called
to obtain simpler results. PonyCheck obtains more shrunken samples until
the property is not failing anymore.
The last failing sample, which is considered the most simple one,
is then reported to the user.
"""
let _gen: GenObj[T]

new create(gen: GenObj[T]) =>
_gen = gen

fun generate(rnd: Randomness): GenerateResult[T] ? =>
"""
Let this generator generate a value
given a source of `Randomness`.

Also allow for returning a value and pre-generated shrink results


if
not _shutdown and
(_connect_count == 0) and
(_pending_writev_total == 0)
then
_shutdown = true

if _connected then
@pony_os_socket_shutdown(_fd)
else
_shutdown_peer = true
end
end

if _connected and _shutdown and _shutdown_peer then
hard_close()
end

fun ref hard_close() =>
"""


fun box i16()
: I16 val

Returns¶

I16 val

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

Returns¶

I32 val

i64¶
[Source]


String iso^

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

Parameters¶

y: U8 val

Returns¶

U8 val

sub_unsafe¶
[Source]


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


652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671use @_open[I32](path: Pointer[U8] tag, flags: I32, ...) if windows


```pony
let my_list = List[String].from(["a"; "b"; "c"])
let other_list = my_list.drop(1)  // ["a"]
```
"""
let l = List[this->A!]

if size() > 0 then
try
var node = head()?

for i in Range(0, n.min(size())) do
l.push(node()?)
node = node.next() as this->ListNode[A]
end
end
end
l


## Every actor is single threaded

The code within a single actor is never run concurrently. This means that, within a single actor, data updates cannot cause problems. It's only when we want to share data between actors that we have problems.

__OK, safely sharing data concurrently is tricky. How do reference capabilities help?__

By sharing only immutable data and exchanging only isolated data we can have safe concurrent programs without locks. The problem is that it's very difficult to do that correctly. If you accidentally hang on to a reference to some isolated data you've handed over or change something you've shared as immutable then everything goes wrong. What you need is for the compiler to force you to live up to your promises. Pony reference capabilities allow the compiler to do just that.


base64.pony

1
2
3
4
5
6
7
8
9
10
11


fun box remc(
y: USize val)
: (USize val , Bool val)

Parameters¶

y: USize val

Returns¶

(USize val , Bool val)

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

Parameters¶


fun box af_inet6()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

dccp_nr_pkt_types¶
[Source]


12
13
14
15
16
17
18
19
20
21
22
23
24
25primitive Platform
fun bsd(): Bool => freebsd() or dragonfly() or openbsd()
fun freebsd(): Bool => compile_intrinsic
fun dragonfly(): Bool => compile_intrinsic
fun openbsd(): Bool => compile_intrinsic
fun linux(): Bool => compile_intrinsic
fun osx(): Bool => compile_intrinsic


fun ref has_next(): Bool =>
_cur > _to

fun ref next(): T =>
let res = _cur - 1
_cur = res
res

trait box GenObj[T]
fun generate(rnd: Randomness): GenerateResult[T] ?

fun shrink(t: T): ValueAndShrink[T] =>
(consume t, Poperator[T].empty())

fun generate_value(rnd: Randomness): T^ ? =>
"""
Simply generate a value and ignore any possible
shrink values.
"""


## Get and Pass Pointers to FFI

If you want to receive a pointer to an opaque C type, using a pointer to a primitive can be useful:

```pony
use @XOpenDisplay[Pointer[_XDisplayHandle]](name: Pointer[U8] tag)
use @eglGetDisplay[Pointer[_EGLDisplayHandle]](disp: Pointer[_XDisplayHandle])

primitive _XDisplayHandle
primitive _EGLDisplayHandle

let x_dpy = @XOpenDisplay(Pointer[U8])
if x_dpy.is_null() then
env.out.print("XOpenDisplay failed")
end

let e_dpy = @eglGetDisplay(x_dpy)
if e_dpy.is_null() then
env.out.print("eglGetDisplay failed")
end


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


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


# Message Passing

If you are familiar with actor-based languages like Erlang, you are familiar with the concept of "message passing". It's how actors communicate with one another. Behaviours are the Pony equivalent. When you call a behavior on an actor, you are sending it a message.

If you aren't familiar with message passing, don't worry about it. We've got you covered. All will be explained below.


y: U64 val

Returns¶

U64 val ?

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

Parameters¶

y: U64 val

Returns¶


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


fun box ge(
y: USize val)
: Bool val

Parameters¶

y: USize val

Returns¶

Bool val

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

Parameters¶


## Reading from a `tag` variable

This one is easy: `tag` variables are opaque! They can't be read from.


792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811


nanoseconds: I64 val = 0)
: PosixDate ref^

Parameters¶

seconds: I64 val = 0
nanoseconds: I64 val = 0

Returns¶

PosixDate ref^

Public fields¶
var nsec: I32 val¶
[Source]

var sec: I32 val¶
[Source]


fun box tipc_sub_ports()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

tipc_top_srv¶
[Source]


fun peek_i16_le(offset: USize = 0): I16 ? =>
"""
Peek at a little-endian I16.
"""
peek_u16_le(offset)?.i16()

fun peek_u32_be(offset: USize = 0): U32 ? =>
"""
Peek at a big-endian U32.
"""
(peek_u16_be(offset)?.u32() << 16) or peek_u16_be(offset + 2)?.u32()

fun peek_u32_le(offset: USize = 0): U32 ? =>
"""
Peek at a little-endian U32.
"""
peek_u16_le(offset)?.u32() or (peek_u16_le(offset + 2)?.u32() << 16)

fun peek_i32_be(offset: USize = 0): I32 ? =>
"""


# Mostly insignificant whitespace

Pony reads a bit like Python, which is a _whitespace significant_ language. That is, the amount of indentation on a line means something in Python. In Pony, the amount of indentation is meaningless.

That means Pony programmers can format their code in whatever way suits them.

There are three exceptions:

1. A `-` at the beginning of a line starts a new expression (unary negation), whereas a `-` in the middle of an expression is a binary operator (subtraction).
2. A `(` at the beginning of a line starts a new expression (a tuple), whereas a `(` in the middle of an expression is a method call.
3. A `[` at the beginning of a line starts a new expression (an array literal), whereas a `[` in the middle of an expression is generic formal parameters.

That stuff may seem a little esoteric right now, but we'll explain it all later. The `-` part should make sense though.

```pony
a - b
```

That means "subtract b from a".


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:

```pony
(let c_secs: I64, let c_nanos: I64) = file_info.change_time
```

On Windows this will be the file creation time.
"""

let file: Bool = false
"""`true` if `filepath` points to an a regular file."""

let directory: Bool = false
"""`true` if `filepath` points to a directory."""

let pipe: Bool = false
"""`true` if `filepath` points to a named pipe."""


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


i

fun tag _strings_from_pointers(
data: Pointer[Pointer[U8]] val,
len: USize)
: Array[String] iso^
=>
let array = recover Array[String](len) end
var i: USize = 0

while i < len do
let entry = data._apply(i = i + 1)
array.push(recover String.copy_cstring(entry) end)
end

array


fun box ipproto_emcon()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipproto_eon¶
[Source]


Directory¶
[Source]
Operations on a directory.
The directory-relative functions (open, etc) use the *at interface on FreeBSD
and Linux. This isn't available on OS X prior to 10.10, so it is not used. On
FreeBSD, this allows the directory-relative functions to take advantage of
Capsicum.
class ref Directory

Constructors¶
create¶
[Source]
This will raise an error if the path doesn't exist or it is not a


reserve(_size)
_set(i, encoded._2)
if encoded._1 > 1 then
_set(i + 1, encoded._3)
if encoded._1 > 2 then
_set(i + 2, encoded._4)
if encoded._1 > 3 then
_set(i + 3, encoded._5)
end
end
end
_set(_size, 0)

fun _copy_to(ptr: Pointer[U8] ref, copy_len: USize,
from_offset: USize = 0, to_offset: USize = 0) =>
"""
Copy `copy_len` bytes from this to that at specified offsets.
"""
_ptr._offset(from_offset)._copy_to(ptr._offset(to_offset), copy_len)


fun box sctp_pcb_flags_dont_wake()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_pcb_flags_do_not_pmtud¶
[Source]


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


to happen to complete your test, but don't want to have to collect them
all yourself into a single actor that calls the complete method.

The order of calls to expect_action don't matter - the actions may be
completed in any other order to complete the test.
"""
_runner.expect_action(name)

fun complete_action(name: String) =>
"""
MUST be called for each action expectation that was set up in a long test
to fulfill the expectations. Any expectations that are still outstanding
when the long test timeout runs out will be printed by name when it fails.

Completing all outstanding actions is enough to finish the test. There's no
need to also call the complete method when the actions are finished.

Calling the complete method will finish the test immediately, without
waiting for any outstanding actions to be completed.
"""


## Example

The following example creates a temporary directory in the [set_up()](pony_test-UnitTest.md#set_up) function
and removes it in the [tear_down()](pony_test-UnitTest.md#tear_down) function, thus
simplifying the test function itself:

```pony
use "pony_test"
use "files"

class iso TempDirTest
var tmp_dir: (FilePath | None) = None

fun name(): String => "temp-dir"

fun ref set_up(h: TestHelper)? =>
tmp_dir = FilePath.mkdtemp(FileAuth(h.env.root), "temp-dir")?

fun ref tear_down(h: TestHelper) =>
try


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


fun box ipv6_hopopts()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipv6_join_anycast¶
[Source]


fun box sctp_pcb_flags_do_not_pmtud()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_pcb_flags_explicit_eor¶
[Source]


A

divrem¶
[Source]
fun box divrem(
y: A)
: (A , A)

Parameters¶

y: A

Returns¶

(A , A)

rem¶


12
13
14
15
16
17
18
19
20
21
22
23
24primitive LeastCommonMultiple
"""
Get the least common multiple of x and y where both x and y >= 1.

Providing 0 or numbers that overflow the integer width will result in an
error.

Example usage:


EraseRight¶
[Source]
primitive val EraseRight

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

Returns¶

EraseRight val^


FormatGeneral¶
[Source]
primitive val FormatGeneral is
FormatSpec val

Implements¶

FormatSpec val

Constructors¶
create¶
[Source]


Listens for IPv4 connections.
new tag ip4(
auth: TCPListenAuth val,
notify: TCPListenNotify iso,
host: String val = "",
service: String val = "0",
limit: USize val = 0,
read_buffer_size: USize val = 16384,
yield_after_reading: USize val = 16384,
yield_after_writing: USize val = 16384)
: TCPListener tag^

Parameters¶

auth: TCPListenAuth val
notify: TCPListenNotify iso
host: String val = ""
service: String val = "0"
limit: USize val = 0
read_buffer_size: USize val = 16384


Parameters¶

gen: Generator[U32 val] box
min: USize val = 0
max: USize val = 100

Returns¶

Generator[String val] box

unicode¶
[Source]
Create a generator for unicode strings,
with a minimum length of min codepoints (default: 0)
and a maximum length of max codepoints (default: 100).
Note that the byte length of the generated string can be up to 4 times
the size in code points.
fun box unicode(


# Integers


I64 val

ilong_unsafe¶
fun box ilong_unsafe()
: ILong val

Returns¶

ILong val

isize_unsafe¶
fun box isize_unsafe()
: ISize val

Returns¶

ISize val


Parameters¶

dir_path: FilePath val
dir_entries: Array[String val] ref

Returns¶

None val


else
true
end

fun exists(f: {(this->A!): Bool} box): Bool =>
"""
Returns `true` if at least one element satisfies the predicate, otherwise returns `false`.

```pony
let my_list = List[String].from(["a"; "b"; "c"])
let b_exists = my_list.exists( {(s: String): Bool => s == "b"} ) // true
```
"""
try
_exists(head()?, f)
else
false
end

fun _exists(ln: this->ListNode[A], f: {(this->A!): Bool} box): Bool =>


let r = HashSet[this->A!, K](size())

for value in values() do
try
that(value)?
else
r.set(value)
end
end
r

fun clone[K: HashFunction[this->A!] val = H](): HashSet[this->A!, K]^ =>
"""
Create a clone. The element type may be different due to aliasing and
viewpoint adaptation.
"""
let r = HashSet[this->A!, K](size())

for value in values() do
r.set(value)


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


fun ref clear()
"""
Removes all elements from the sequence.
"""

fun ref push(value: A)
"""
Adds an element to the end of the sequence.
"""

fun ref pop(): A^ ?
"""
Removes an element from the end of the sequence.
"""

fun ref unshift(value: A)
"""
Adds an element to the beginning of the sequence.
"""


: Bool val

Parameters¶

that: Base64 val

Returns¶

Bool val


PropertyParams¶
[Source]
Parameters to control Property Execution.

seed: the seed for the source of Randomness
num_samples: the number of samples to produce from the property generator
max_shrink_rounds: the maximum rounds of shrinking to perform
max_generator_retries: the maximum number of retries to do if a generator fails to generate a sample
timeout: the timeout for the PonyTest runner, in nanoseconds
async: if true the property is expected to finish asynchronously by calling
PropertyHelper.complete(...)

class val PropertyParams is


[Source]
fun box sub_unsafe(
y: A)
: A

Parameters¶

y: A

Returns¶

A

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