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


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


y: I16 val

Returns¶

I16 val

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

Returns¶

I16 val

eq¶
[Source]


Parameters¶

y: ISize val

Returns¶

ISize val ?

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

Parameters¶

y: USize val

Returns¶


: 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
yield_after_reading: USize val = 16384
yield_after_writing: USize val = 16384

Returns¶

TCPListener tag^

ip4¶
[Source]


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


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


Bool val

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

Parameters¶

that: FormatFixLarge val

Returns¶

Bool val


Modifying the Array can be done via update, insert and delete methods
which alter the Array at an arbitrary index, moving elements left (when
deleting) or right (when inserting) as necessary.
Iterating over the elements of an Array can be done using the values method:
for element in array.values() do
// do something with element
end

Memory allocation¶
Array allocates contiguous memory. It always allocates at least enough memory
space to hold all of its elements. Space is the number of elements the Array
can hold without allocating more memory. The space() method returns the
number of elements an Array can hold. The size() method returns the number
of elements the Array holds.
Different data types require different amounts of memory. Array[U64] with size
of 6 will take more memory than an Array[U8] of the same size.
When creating an Array or adding more elements will calculate the next power
of 2 of the requested number of elements and allocate that much space, with a
lower bound of space for 8 elements.


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

Returns¶

String iso^


## Nominal subtyping in Pony

The primary means of doing nominal subtyping in Pony is using __traits__. A __trait__ looks a bit like a __class__, but it uses the keyword `trait` and it can't have any fields.

```pony
trait Named
fun name(): String => "Bob"

class Bob is Named
```

Here, we have a trait `Named` that has a single function `name` that returns a String. It also provides a default implementation of `name` that returns the string literal "Bob".

We also have a class `Bob` that says it `is Named`. This means `Bob` is in the `Named` category. In Pony, we say _Bob provides Named_, or sometimes simply _Bob is Named_.

Since `Bob` doesn't have its own `name` function, it uses the one from the trait. If the trait's function didn't have a default implementation, the compiler would complain that `Bob` had no implementation of `name`.

```pony
trait Named
fun name(): String => "Bob"


U64 val

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

Returns¶

I8 val

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

Returns¶


fun has_next(): Bool =>
"""
Indicates whether there are any values remaining in the iterator.
"""
_next isnt None

fun ref next(): N->A ? =>
"""
Return the next node in the iterator, advancing the iterator by one element.

Order of return is determined by `reverse` argument during creation.
"""
match _next
| let next': N =>
if _reverse then
_next = next'.prev()
else
_next = next'.next()
end


This class buffers the file contents to accumulate full lines. If the file
does not contain linebreaks, the whole file content is read and buffered, which
might exceed memory resources. Take care.
"""
let _reader: Reader = Reader
let _file: File
let _min_read_size: USize
var _last_line_length: USize
var _buffer_cursor: USize
"""Internal cursor for keeping track until where in the file we already buffered."""
var _cursor: USize
"""Keeps track of the file position we update after every returned line."""
var _has_next: Bool

new create(file: File, min_read_size: USize = 256) =>
"""
Create a FileLines instance on a given file.

This instance returns lines from the position of the given `file`
at the time this constructor is called. Later manipulation of the file position


t = t - range
if t >= range then
t = t % range
end
end
while (l < t) do
x = u64()
m = x.u128() * range.u128()
l = m.u64()
end
end
(m >> 64).u64()

fun ref real(): F64 =>
"""
A random number in [0, 1)
"""
(next() >> 11).f64() * (F64(1) / 9007199254740992)

fun ref shuffle[A](array: Array[A]) =>


I16 val

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

Parameters¶

y: U16 val

Returns¶

I16 val

shr_unsafe¶
[Source]


```pony
actor Main
new create(env: Env) =>
try
// construct a new string
let str = "Hello"

// make an uppercased version
let str_upper = str.upper()
// make a reversed version
let str_reversed = str.reverse()

// add " world" to the end of our original string
let str_new = str.add(" world")

// count occurrences of letter "l"
let count = str_new.count("l")

// find first occurrence of letter "w"


# Authority hierarchies

Let's have a look at the authorizations available in the standard library's `net` package.

```pony
primitive NetAuth
new create(from: AmbientAuth) =>
None

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

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

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


fun fld_partial(y: I128): I128 ? =>
_SignedPartialArithmetic.fld_partial[I128, U128](this, y)?

fun mod_partial(y: I128): I128 ? =>
_SignedPartialArithmetic.mod_partial[I128, U128](this, y)?

type Signed is (I8 | I16 | I32 | I64 | I128 | ILong | ISize)


_set_notify(consume notify)
_chunk_size = chunk_size

be dispose() =>
"""
Clear the notifier in order to shut down input.
"""
_set_notify(None)

fun ref _set_notify(notify: (InputNotify iso | None)) =>
"""
Set the notifier.
"""
if notify is None then
if _use_event and not _event.is_null() then
// Unsubscribe the event.
@pony_asio_event_unsubscribe(_event)
_event = AsioEvent.none()
end
elseif _notify is None then


fun box sctp_pcb_flags_frag_interleave()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_pcb_flags_in_tcppool¶
[Source]


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


Parameters¶

y: A

Returns¶

A

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

Parameters¶

y: A

Returns¶


fun box i64()
: I64 val

Returns¶

I64 val

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

Returns¶

I128 val

ilong¶
[Source]


actor Main
new create(env: Env) =>
let critters = Array[Critter].>push(Wombat).>push(Capybara)
for critter in critters.values() do
env.out.print(critter.wash())
try
env.out.print((critter as Capybara).swim())
end
end
```

You can do the same with interfaces as well. In the example below, we have an Array of `Any` which is an interface where we want to try wash any entries that conform to the `Critter` interface.

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


try
(consume rejected').apply()?
else
p.reject()
end
end)

outer

fun tag add[B: Any #share = A](p: Promise[B]): Promise[(A, B)] =>
"""
Add two promises into one promise that returns the result of both when
they are fulfilled. If either of the promises is rejected then the new
promise is also rejected.
"""
let p' = Promise[(A, B)]

let c =
object


# But Caveat Emptor

But Pony can use external C libraries via the **FFI** which does not have this luxury.

So you **can** use any external C library out there, but the question is if you **need to** and if you **should**.

The biggest problem is external heap memory, created by an external FFI call, or created to support an external call. But external stack space might also need some thoughts, esp. when being created from actors.

Pony does have **finalisers** (callbacks which are called by the garbage collector which may be used to free resources allocated by an FFI call); However, the garbage collector is _not timely_ (as with pure reference counting), it is not triggered immediately when some object goes out of scope.

A blocked actor will keep its memory allocated, only a dead actor will release it eventually.


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

Behavior is undefined if `min` > `max`.
"""
u64(min.u64(), max.u64()).ulong()

fun ref usize(
min: USize = USize.min_value(),
max: USize = USize.max_value())
: USize
=>
"""


: I128 val

Returns¶

I128 val

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

Returns¶

U128 val

add_unsafe¶


# What about inheritance?

In some object-oriented languages, a type can _inherit_ from another type, like how in Java something can __extend__ something else. Pony doesn't do that. Instead, Pony prefers _composition_ to _inheritance_. In other words, instead of getting code reuse by saying something __is__ something else, you get it by saying something __has__ something else.

On the other hand, Pony has a powerful __trait__ system (similar to Java 8 interfaces that can have default implementations) and a powerful __interface__ system (similar to Go interfaces, i.e. structurally typed).

We'll talk about all that stuff in detail later.


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


y: B)
: A

Parameters¶

y: B

Returns¶

A

shr_unsafe¶
[Source]
Unsafe operation.
If non-zero bits are shifted-out, the result is undefined.
fun box shr_unsafe(
y: B)
: A


y: I128 val

Returns¶

I128 val ?

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

Parameters¶

y: I128 val

Returns¶


Parameters¶

y: ISize val

Returns¶

ISize val

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

Parameters¶

y: ISize val

Returns¶


let sx = Serialised(serialise, csw)?
let y = sx(deserialise)? as CStringWrapper
y.print()
else
env.err.print("there was an error")
end
```

```c
// custser.c


fun ref get_so_sndbuf(): (U32, U32) =>
"""
Wrapper for the FFI call `getsockopt(fd, SOL_SOCKET, SO_SNDBUF, ...)`
"""
_OSSocket.get_so_sndbuf(_fd)

fun ref get_tcp_nodelay(): (U32, U32) =>
"""
Wrapper for the FFI call `getsockopt(fd, SOL_SOCKET, TCP_NODELAY, ...)`
"""
_OSSocket.getsockopt_u32(_fd, OSSockOpt.sol_socket(), OSSockOpt.tcp_nodelay())

fun ref set_so_rcvbuf(bufsize: U32): U32 =>
"""
Wrapper for the FFI call `setsockopt(fd, SOL_SOCKET, SO_RCVBUF, ...)`
"""
_OSSocket.set_so_rcvbuf(_fd, bufsize)


Peek at a big-endian I32.
"""
peek_u32_be(offset)?.i32()

fun peek_i32_le(offset: USize = 0): I32 ? =>
"""
Peek at a little-endian I32.
"""
peek_u32_le(offset)?.i32()

fun peek_u64_be(offset: USize = 0): U64 ? =>
"""
Peek at a big-endian U64.
"""
(peek_u32_be(offset)?.u64() << 32) or peek_u32_be(offset + 4)?.u64()

fun peek_u64_le(offset: USize = 0): U64 ? =>
"""
Peek at a little-endian U64.
"""


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

Returns¶

I64 val

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

Returns¶

I128 val


MapKeys[K, V, H, this->HashMap[K, V, H]](this)

fun values(): MapValues[K, V, H, this->HashMap[K, V, H]]^ =>
"""
Return an iterator over the values.
"""
MapValues[K, V, H, this->HashMap[K, V, H]](this)

fun pairs(): MapPairs[K, V, H, this->HashMap[K, V, H]]^ =>
"""
Return an iterator over the keys and values.
"""
MapPairs[K, V, H, this->HashMap[K, V, H]](this)

class MapKeys[K, V, H: HashFunction[K] val, M: HashMap[K, V, H] #read] is
Iterator[M->K]
"""
An iterator over the keys in a map.
"""
let _map: M


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

fun fld(y: I32): I32 =>
_SignedArithmetic.fld[I32, U32](this, y)

fun fld_unsafe(y: I32): I32 =>
_SignedUnsafeArithmetic.fld_unsafe[I32, U32](this, y)

fun mod(y: I32): I32 =>
_SignedArithmetic.mod[I32, U32](this, y)

fun mod_unsafe(y: I32): I32 =>
_SignedUnsafeArithmetic.mod_unsafe[I32, U32](this, y)

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

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


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


sep¶
[Source]
Return the path separator as a string.
fun tag sep()
: String val

Returns¶

String val

is_abs¶
[Source]
Return true if the path is an absolute path.
fun box is_abs(
path: String val)
: Bool val

Parameters¶


fun box local_peereuuid()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

local_peeruuid¶
[Source]


[Source]
Maximum positive value representable.
new val max_value()
: F64 val^

Returns¶

F64 val^

min_normalised¶
[Source]
Minimum positive value representable at full precision (ie a normalised
number).
new val min_normalised()
: F64 val^

Returns¶

F64 val^


let nodes = my_list.nodes()  // node with "a" is before node with "c"

fun box nodes()
: ListNodes[A, this->ListNode[A] ref] ref^

Returns¶

ListNodes[A, this->ListNode[A] ref] ref^

rnodes¶
[Source]
Return an iterator on the nodes in the List in reverse order.
let my_list = List[String].from(["a"; "b"; "c"])
let rnodes = my_list.rnodes()  // node with "c" is before node with "a"

fun box rnodes()
: ListNodes[A, this->ListNode[A] ref] ref^

Returns¶


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


match pipe.near_fd
| _stdout.near_fd =>
if _read_len >= _expect then
_notifier.stdout(this, consume data)
end
| _stderr.near_fd =>
_notifier.stderr(this, consume data)
| _err.near_fd =>
let step: U8 = try data.read_u8(0)? else -1 end
match step
| _StepChdir() =>
_notifier.failed(this, ProcessError(ChdirError))
| _StepExecve() =>
_notifier.failed(this, ProcessError(ExecveError))
else
_notifier.failed(this, ProcessError(UnknownError))
end
end


The [Serialise.signature](serialise-Serialise.md#signature) method is provided
for the purposes of comparing communicating Pony binaries to determine if they
are the same. Confirming this before deserialising data can help mitigate the
risk of accidental serialisation across different Pony binaries, but does not on
its own address the security issues of accepting data from untrusted sources.
"""

use @"internal.signature"[Array[U8] val]()
use @pony_ctx[Pointer[None]]()
use @pony_alloc[Pointer[U8]](ctx: Pointer[None], size: USize)
use @pony_alloc_final[Pointer[U8]](ctx: Pointer[None], size: USize)
use @pony_serialise[None](ctx: Pointer[None], data: Any box, typ: Pointer[None],
arr_out: Array[U8] tag, alloc_fn: @{(Pointer[None], USize): Pointer[U8]},
throw_fn: @{(): None ?}) ?
use @pony_deserialise[Any iso^](ctx: Pointer[None], typ: Pointer[None],
arr_in: Array[U8] val, alloc_fn: @{(Pointer[None], USize): Pointer[U8]},
alloc_final_fn: @{(Pointer[None], USize): Pointer[U8]}, throw_fn: @{(): None ?}) ?

primitive Serialise


32
33
34
35
36
37
38use "collections"

primitive EnvVars
fun apply(
envs: (Array[String] box | None),
prefix: String = "",
squash: Bool = false):
Map[String, String] val
=>
"""
Turns an array of strings that look like environment variables, ie.
key=value, into a map of string to string. Can optionally filter for
keys matching a 'prefix', and will squash resulting keys to lowercase
iff 'squash' is true.


(Less val | Equal val | Greater val)


end
// NOTE: this _moves_ the elements so second_list consequently ends up empty
env.out.print("Append *moves* the nodes from the second list so that now has "
+ my_second_list.size().string() + " nodes.") // 0

// Create a third List from a Seq(ence)
// (In this case a literal array of Strings)
let my_third_list = List[String].from(["First"; "Second"; "Third"])
env.out.print("A list created from an array of three strings has size: "
+ my_third_list.size().string()) // 3
for n in my_third_list.values() do
env.out.print("\t" + n.string())
end

// Map over the third List, concatenating some "BOOM!'s" into a new List
let new_list = my_third_list.map[String]({ (n) => n + " BOOM!" })
env.out.print("Mapping over our three-node list produces a new list of size: "
+ new_list.size().string()) // 3
env.out.print("Each node-value in the resulting list is now far more exciting:")
for n in new_list.values() do


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


# Safe packages

The normal way to handle that is to be sure you're using just the code you need to use in your program. Pretty simple! Don't use some random package from the internet without looking at the code and making sure it doesn't do nasty FFI stuff.

But we can do better than that.

In Pony, you can optionally declare a set of _safe_ packages on the `ponyc` command line, like this:

```sh
ponyc --safe=files:net:process my_project
```

Here, we are declaring that only the `files`, `net` and `process` packages are allowed to use C-FFI calls. We've established our trust boundary: any other packages that try to use C-FFI calls will result in a compile-time error.


U8 val

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

Returns¶

U16 val

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

Returns¶


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

Returns¶

F32 val

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

Returns¶

F64 val


fun sinh(): A
fun tanh(): A

fun acos(): A
fun asin(): A
fun atan(): A
fun atan2(y: A): A

fun acosh(): A
fun asinh(): A
fun atanh(): A

fun copysign(sign: A): A

fun string(): String iso^ =>
_ToString._f64(f64())

type Number is (Int | Float)

type Int is (Signed | Unsigned)


fun box ipv6_pmtudisc_do()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipv6_pmtudisc_interface¶
[Source]


Bool val

next¶
[Source]
fun ref next()
: B->A ?

Returns¶

B->A ?

rewind¶
[Source]
fun ref rewind()
: ArrayValues[A, B] ref

Returns¶


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


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

Returns¶

String iso^

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

Parameters¶


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

Parameters¶

y: I32 val

Returns¶

I32 val

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

Parameters¶


fun box ipproto_ipv4()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipproto_irtp¶
[Source]


: ANSITerm tag^

Parameters¶

notify: ANSINotify iso
source: DisposableActor tag
timers: Timers tag = reference

Returns¶

ANSITerm tag^

Public Behaviours¶
apply¶
[Source]
Receives input from stdin.
be apply(
data: Array[U8 val] iso)


1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311


y: A

Returns¶

A

mul_unsafe¶
[Source]
Unsafe operation.
If the operation overflows, the result is undefined.
fun box mul_unsafe(
y: A)
: A

Parameters¶

y: A


# What can you use a __primitive__ for?

There are three main uses of primitives (four, if you count built-in "machine word" primitives).

1. As a "marker value". For example, Pony often uses the __primitive__ `None` to indicate that something has "no value". Of course, it _does_ have a value, so that you can check what it is, and the value is the single instance of `None`.
2. As an "enumeration" type. By having a __union__ of __primitive__ types, you can have a type-safe enumeration. We'll cover __union__ types later.
3. As a "collection of functions". Since primitives can have functions, you can group functions together in a primitive type. You can see this in the standard library, where path handling functions are grouped in the __primitive__ `Path`, for example.

```pony
// 2 "marker values"
primitive OpenedDoor
primitive ClosedDoor

// An "enumeration" type
type DoorState is (OpenedDoor | ClosedDoor)

// A collection of functions
primitive BasicMath
fun add(a: U64, b: U64): U64 =>
a + b


fun box sol_ipx()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sol_local¶
[Source]


ILong val^

max_value¶
[Source]
new val max_value()
: ILong val^

Returns¶

ILong val^

Public Functions¶
abs¶
[Source]
fun box abs()
: ULong val

Returns¶


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


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


fun box u8()
: U8 val

Returns¶

U8 val

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

Returns¶

U16 val

u32¶
[Source]


fun from_millis(t: U64): U64 =>
t * 1_000_000

fun from_micros(t: U64): U64 =>
t * 1_000

fun from_seconds_f(t: F64): U64 =>
(t * 1_000_000_000).trunc().u64()

fun from_millis_f(t: F64): U64 =>
(t * 1_000_000).trunc().u64()

fun from_micros_f(t: F64): U64 =>
(t * 1_000).trunc().u64()

fun from_wall_clock(wall: (I64, I64)): U64 =>
((wall._1 * 1000000000) + wall._2).u64()


or @ponyint_o_directory()
or @ponyint_o_cloexec())
@fdopendir(fd)
else
@opendir(path'.cstring())
end

if h.is_null() then
error
end

while true do
let p = @ponyint_unix_readdir(h)
if p.is_null() then break end
list.push(recover String.from_cstring(consume p) end)
end

@closedir(h)
elseif windows then
var find = @ponyint_windows_find_data()


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


# Reference Capabilities

So if the object _is_ the capability, what controls what we can do with the object? How do we express our _access rights_ on that object?

In Pony, we do it with _reference capabilities_.


232
233
234
235
236
237
238
239
240use "random"

class ref Randomness
"""
Source of randomness, providing methods for generatic uniformly distributed
values from a given closed interval: [min, max]
in order for the user to be able to generate every possible value for a given
primitive numeric type.

All primitive number method create numbers in range [min, max)
"""
let _random: Random


count¶
[Source]
Return the number of values in the iterator.
Example¶
Iter[I64]([1; 2; 3].values())
.count()

3
fun ref count()
: USize val

Returns¶

USize val

cycle¶
[Source]
Repeatedly cycle through the values from the iterator.


fun box tcp_quickack()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

tcp_repair_options¶
[Source]


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


Bool val

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

Parameters¶

that: PrefixSign val

Returns¶

Bool val


If there is no reject function, of if the reject function raises an error,
then the next promise in the chain will be rejected.
"""
let attach = _Then[A, B](consume fulfill, consume rejected)
let promise = attach.promise()
_attach(consume attach)
promise

fun tag flatten_next[B: Any #share](
fulfill: Fulfill[A, Promise[B]],
rejected: Reject[Promise[B]] = RejectAlways[Promise[B]])
: Promise[B]
=>
"""
Chain a promise after this one and unwrap the promise returned from this
one.

`flatten_next` is a companion to `next`. It operates in an identical
fashion except for the type of the fulfilled promise. Whereas `next` takes
a function that returns a type `B`, `flatten_next` takes a function that


ListValues[A: A, N: ListNode[A] #read]¶
[Source]
Iterate over the values in a List.
class ref ListValues[A: A, N: ListNode[A] #read] is
Iterator[N->A] ref

Implements¶

Iterator[N->A] ref

Constructors¶
create¶


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


Returns¶

Array[U8 val] iso^ ?

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

Parameters¶

keep_line_breaks: Bool val = false

Returns¶


[Source]
Builds a new list by reversing the elements in the list.
fun val reverse()
: (Cons[A] val | Nil[A] val)

Returns¶

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

prepend¶
[Source]
Builds a new list with an element added to the front of this list.
fun val prepend(
a: val->A!)
: Cons[A] val

Parameters¶

a: val->A!


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


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


// define a client that implements the ProcessNotify interface
class ProcessClient is ProcessNotify
let _env: Env

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

fun ref stdout(process: ProcessMonitor ref, data: Array[U8] iso) =>
let out = String.from_array(consume data)
_env.out.print("STDOUT: " + out)

fun ref stderr(process: ProcessMonitor ref, data: Array[U8] iso) =>
let err = String.from_array(consume data)
_env.out.print("STDERR: " + err)

fun ref failed(process: ProcessMonitor ref, err: ProcessError) =>
_env.out.print(err.string())

fun ref dispose(process: ProcessMonitor ref, child_exit_status: ProcessExitStatus) =>


Promise[Array[A] val] tag

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

Parameters¶

that: Promises[A] val

Returns¶

Bool val

ne¶


fun divrem(y: I128): (I128, I128) =>
ifdef native128 then
(this / y, this % y)
else
if y == 0 then
return (0, 0)
end

var num: I128 = if this >= 0 then this else -this end
var den: I128 = if y >= 0 then y else -y end

(let q, let r) = num.u128().divrem(den.u128())
(var q', var r') = (q.i128(), r.i128())

if this < 0 then
r' = -r'

if y > 0 then
q' = -q'


fun box u128_unsafe()
: U128 val

Returns¶

U128 val

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

Returns¶

ULong val

usize_unsafe¶
[Source]


Returns¶

F32 val

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

Returns¶

F32 val

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


V!

insert¶
[Source]
Set a value in the map. Returns the new value, allowing reuse.
fun ref insert(
key: K,
value: V)
: V!

Parameters¶

key: K
value: V

Returns¶

V!


FulfillIdentity[A: Any #share]¶
[Source]
An identity function for fulfilling promises.
class iso FulfillIdentity[A: Any #share]

Constructors¶
create¶
[Source]
new iso create()
: FulfillIdentity[A] iso^

Returns¶


primitive FetchIssue
fun apply(number: I64, repo: Repository): Promise[Issue] =>
repo.get_issue(number)

primitive PrintIssueTitle
fun apply(out: OutStream, issue: Issue) =>
out.print(issue.title())

Our promise Issue, is no longer a Promise[Promise[Issue]]. By using
flatten_next, we have a much more manageable Promise[Issue] instead.
Other than unwrapping promises for you, flatten_next otherwise acts the
same as next so all the same rules apply to fulfillment and rejection.
fun tag flatten_next[B: Any #share](
fulfill: Fulfill[A, Promise[B] tag] iso,
rejected: Reject[Promise[B] tag] iso = qualify)
: Promise[B] tag

Parameters¶

fulfill: Fulfill[A, Promise[B] tag] iso


Returns¶

I16 val ?

peek_i16_le¶
[Source]
Peek at a little-endian I16.
fun box peek_i16_le(
offset: USize val = 0)
: I16 val ?

Parameters¶

offset: USize val = 0

Returns¶

I16 val ?


fun ref u64(): U64 =>
"""
A random integer in [0, 2^64)
"""
next()

fun ref u128(): U128 =>
"""
A random integer in [0, 2^128)
"""
(next().u128() << 64) or next().u128()

fun ref ulong(): ULong =>
"""
A random integer in [0, ULong.max_value()]
"""
ifdef ilp32 or llp64 then
(next() >> 32).ulong()
else


fun box ipproto_send()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipproto_shim6¶
[Source]


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


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


ISize val

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

Parameters¶

y: ISize val

Returns¶

ISize val

fld_unsafe¶


# Primitives and equality

As you might remember from [Chapter 2](/types/primitives.md), primitives are the same as classes except for two important differences:

* A primitive has no fields.
* There is only one instance of a user-defined primitive.

This means, that every primitive of a given type, is always structurally equal and equal based on identity. So, for example, None is always None.

```pony
if None is None then
// this is always true
end

if None == None then
// this is also always true
end
```


fun box i16_unsafe()
: I16 val

Returns¶

I16 val

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

Returns¶

I32 val

i64_unsafe¶
[Source]


copy_to¶
[Source]
Copy len elements from this(src_idx) to dst(dst_idx).
fun box copy_to(
dst: Array[this->A!] ref,
src_idx: USize val,
dst_idx: USize val,
len: USize val)
: None val

Parameters¶

dst: Array[this->A!] ref
src_idx: USize val
dst_idx: USize val
len: USize val

Returns¶


# Usage
```pony
use "collections/persistent"

actor Main
new create(env: Env) =>
try
let m1 = Map[String, U32] // {}
// Update returns a new map with the provided key set
// to the provided value. The old map is unchanged.
let m2 = m1("a") = 5 // {a: 5}
let m3 = m2("b") = 10 // {a: 5, b: 10}
let m4 = m3.remove("a")? // {b: 10}
// You can create a new map from key value pairs.
let m5 = Map[String, U32].concat([("a", 2); ("b", 3)].values()) // {a: 2, b: 3}
end
```
"""
let _root: _MapSubNodes[K, V, H]
let _size: USize


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


552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571


fun box ipv6_addr_preferences()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipv6_authhdr¶
[Source]


new val create()
: PrefixDefault val^

Returns¶

PrefixDefault val^

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

Parameters¶

that: PrefixDefault val

Returns¶


_iter.next()?
end)

fun ref take(n: USize): Iter[A]^ =>
"""
Return an iterator for the first n elements.


112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129use @pony_os_stat[Bool](path: Pointer[U8] tag, file: FileInfo tag)
use @pony_os_fstat[Bool](fd: I32, path: Pointer[U8] tag, file: FileInfo tag)
use @pony_os_fstatat[Bool](fd: I32, path: Pointer[U8] tag, file: FileInfo tag)


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


fun box mul(
y: I64 val)
: I64 val

Parameters¶

y: I64 val

Returns¶

I64 val

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

Parameters¶


y: U32 val

Returns¶

Bool val

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

Parameters¶

y: U32 val

Returns¶


acc' = f(consume acc', a)?
end
acc'

fun ref interleave(other: Iterator[A]): Iter[A!] =>
"""
Return an iterator that alternates the values of the original iterator and
the other until both run out.


fun box sub(
y: F64 val)
: F64 val

Parameters¶

y: F64 val

Returns¶

F64 val

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

Parameters¶


fun ref set_up(
h: TestHelper val)
: None val ?

Parameters¶

h: TestHelper val

Returns¶

None val ?

tear_down¶
[Source]
Tidy up after the test has completed.
Called for each run test, whether that test passed, succeeded or timed out.
The default is to do nothing.
fun ref tear_down(
h: TestHelper val)


CommandHelp¶
[Source]
CommandHelp encapsulates the information needed to generate a user help
message for a given CommandSpec, optionally with a specific command
identified to print help about. Use Help.general() or Help.for_command()
to create a CommandHelp instance.
class box CommandHelp

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


Public Types¶

primitive CreateFile
class Directory
class File
primitive FileAuth
primitive FileBadFileNumber
type FileCaps
primitive FileChmod
primitive FileChown
primitive FileCreate
primitive FileEOF
type FileErrNo
primitive FileError
primitive FileExec
primitive FileExists
class FileInfo
class FileLines
primitive FileLink


r = r << (ex' - 52)
else
r = r >> (52 - ex')
end

r.u128()

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

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


@write(err.far_fd, addressof step, USize(1))
@_exit(_EXOSERR())
end
| None => None
end

step = _StepExecve()
if 0 > @execve(path.cstring(), argp.cpointer(),
envp.cpointer())
then
@write(err.far_fd, addressof step, USize(1))
@_exit(_EXOSERR())
end

fun tag _dup2(oldfd: U32, newfd: U32) =>
"""
Creates a copy of the file descriptor oldfd using the file
descriptor number specified in newfd. If the file descriptor newfd
was previously open, it is silently closed before being reused.
If dup2() fails because of EINTR we retry.


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


fun ref all(
f: {(A!): Bool ?}[A] box)
: Bool val

Parameters¶

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

Returns¶

Bool val

any¶
[Source]
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.
Examples¶
Iter[I64]([2; 4; 6].values())


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


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


| Symbol  | Usage                                                                           |
| ------- | ------------------------------------------------------------------------------- |
| `,`     | to separate parameters in a function signature, or the items of a tuple         |
| `.`     | (1) to call a field or a function on a variable (field access or method call)   |
|         | (2) to qualify a type/method with its package name                              |
| `.>`    | to call a method on an object and return the receiver (chaining)                |
| `'`     | used as alternative name in parameters (prime)                                  |
| `"`     | to delineate a literal string                                                   |
| `"""`   | to delineate a documentation string                                             |
| `(`     | (1) start of line: start of a tuple                                             |
|         | (2) middle of line: method call                                                 |
| `()`    | (1) parentheses, for function or behavior parameters                            |
|         | (2) making a tuple (values separated by `,`)                                    |
|         | (3) making an enumeration (values separated by |)                          |
| `[`     | (1) start of line: start of an array literal                                    |
|         | (2) middle of line: generic formal parameters                                   |
| `[]`    | (1) to indicate a generic type, for example `Range[U64]`                        |
|         | (2) to indicate the return type of an FFI function call                         |
| `{}`    | a function type                                                                 |
| `:`     | (1) after a variable: is followed by the type name                              |


Parameters¶

count: U32 val

Returns¶

Bool val

dispose¶
[Source]
Called if the signal is disposed. This is also called if the notifier
returns false.
fun ref dispose()
: None val

Returns¶

None val


fun box sctp_pcb_flags_was_aborted()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_pcb_flags_zero_copy_active¶
[Source]


Returns¶

I64 val ?

i64_le¶
[Source]
Get a little-endian I64.
fun ref i64_le()
: I64 val ?

Returns¶

I64 val ?

u128_be¶
[Source]
Get a big-endian U128.


I16 val^

max_value¶
[Source]
new val max_value()
: I16 val^

Returns¶

I16 val^

Public Functions¶
abs¶
[Source]
fun box abs()
: U16 val

Returns¶


fun box modc(
y: I8 val)
: (I8 val , Bool val)

Parameters¶

y: I8 val

Returns¶

(I8 val , Bool val)

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

Parameters¶


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

Parameters¶

that: None val

Returns¶

Bool val

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


F64 val

pow¶
[Source]
fun box pow(
y: F64 val)
: F64 val

Parameters¶

y: F64 val

Returns¶

F64 val

powi¶
[Source]


fun box sctp_ss_priority()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_ss_round_robin_packet¶
[Source]


fun ref bool(): Bool =>
"""
Generate a random Bool value.
"""
(_random.next() % 2) == 0

fun ref shuffle[T](array: Array[T] ref) =>
_random.shuffle[T](array)


"""
Clear the screen.
"""
_out.write(ANSI.clear())
_refresh_line()

fun ref _swap() =>
"""
Swap the previous character with the current one.
"""
try
if (_cur_pos > 0) and (_cur_pos < _edit.size().isize()) then
_edit(_cur_pos.usize())? =
_edit((_cur_pos - 1).usize())? =
_edit(_cur_pos.usize())?
end

_refresh_line()
end


"""
Indicates whether there are any nodes remaining in the iterator.
"""
_next isnt None

fun ref next(): N ? =>
"""
Return the next node in the iterator, advancing the iterator by one element.

Order of return is determined by `reverse` argument during creation.
"""
match _next
| let next': N =>
if _reverse then
_next = next'.prev()
else
_next = next'.next()
end

next'


Bool val

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

Parameters¶

y: U16 val

Returns¶

Bool val

ge¶
[Source]


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


: Bool val

Returns¶

Bool val

help_string¶
[Source]
Returns a formated help string for this arg.
fun box help_string()
: String val

Returns¶

String val

deb_string¶
[Source]


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

Parameters¶

value: I16 val

Returns¶

I16 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 |


# Function Call Side Effects

Consider the following code:

```pony
class Foo
fun fn(x: U64) => None

actor Main
new create(env: Env) =>
var x: U64 = 0
try foo()?.fn(x = 42) end
env.out.print(x.string())

fun foo(): Foo ? => error
```

What do you think it will print? Probably `0` right? Or maybe you realized this code is in the gotchas section so it must be `42`. If you went with `42`, you'd be right. Why?

Expressions for arguments in function calls are evaluated before the expression for the function receiver. The use of assignment expressions like `x = 42` is quite rare so we don't think many folks will be bitten by this. However, it's definitely something you want to be aware of. Also remember that if `fn` were to be called, it would be called with `0` (the result of the assignment expression).


fun box ip_fw_table_list()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ip_hdrincl¶
[Source]


172
173
174
175use mut = "collections"

type Map[K: (mut.Hashable val & Equatable[K]), V: Any #share] is
HashMap[K, V, mut.HashEq[K]]
"""
A map that uses structural equality on the key.
"""

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

class val HashMap[K: Any #share, V: Any #share, H: mut.HashFunction[K] val]
"""
A persistent map based on the Compressed Hash Array Mapped Prefix-tree from
'Optimizing Hash-Array Mapped Tries for Fast and Lean Immutable JVM


u64¶
[Source]
fun box u64(
base: U8 val = 0)
: U64 val ?

Parameters¶

base: U8 val = 0

Returns¶

U64 val ?

u128¶
[Source]
fun box u128(
base: U8 val = 0)
: U128 val ?


fun box rose_qbitincl()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

rose_ship_absent¶
[Source]


U128 val

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

Returns¶

U128 val

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

Returns¶


Iter[(A, B, C, D, E)](
object is Iterator[(A, B, C, D, E)]
let _i1: Iterator[A] = _iter
let _i2: Iterator[B] = i2
let _i3: Iterator[C] = i3
let _i4: Iterator[D] = i4
let _i5: Iterator[E] = i5

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

fun ref next(): (A, B, C, D, E) ? =>
(_i1.next()?, _i2.next()?, _i3.next()?, _i4.next()?, _i5.next()?)
end)

primitive _None


data: F64 val

Returns¶

None val

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

Parameters¶

data: F64 val

Returns¶


SyntaxError¶
[Source]
SyntaxError summarizes a syntax error in a given parsed command line.
class val SyntaxError

Constructors¶
create¶
[Source]
new val create(
token': String val,
msg': String val)
: SyntaxError val^


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


try
FileInfo(this)?.directory
else
false
end

fun val remove(): Bool =>
"""
Remove the file or directory. The directory contents will be removed as
well, recursively. Symlinks will be removed but not traversed.
"""
if not caps(FileRemove) then
return false
end

try
let info = FileInfo(this)?

if info.directory and not info.symlink then
let directory = Directory(this)?


: (CommandHelp | SyntaxError)
=>
if argv.size() > 0 then
try
let cname = argv(0)?
if cs.commands().contains(cname) then
match cs.commands()(cname)?
| let ccs: CommandSpec box =>
let cch = CommandHelp._create(ch, ccs)
return _parse(ccs, cch, argv.slice(1))
end
end
return SyntaxError(cname, "unknown command")
end
end
ch

class box CommandHelp
"""
CommandHelp encapsulates the information needed to generate a user help


# Differences between traits and interfaces

It is common for new Pony users to ask, __Should I use traits or interfaces in my own code?__ Both! Interfaces are more flexible, so if you're not sure what you want, use an interface. But traits are a powerful tool as well.


Returns¶

Bool val


fun box mrt_mfc_flags_all()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

mrt_mfc_flags_disable_wrongvif¶
[Source]


```

becomes:

```pony
var foo = Foo.create(x, 37 where crash = false)
```

__What if I want to use a constructor that isn't named create?__ Then the sugar can't help you and you have to write it out yourself.

__If the create I want to call takes no arguments can I still put in the parentheses?__ No. Calls of the form `Type()` use the combined create-apply sugar (see below). To get `Type.create()` just use `Type`.


fun box ipport_userreserved()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipv6_2292hoplimit¶
[Source]


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


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

fun _every(ln: this->ListNode[A], f: {(this->A!): Bool} box): Bool =>
"""
Private helper for `every`, recursively working with `ListNode`s.
"""
try
if not(f(ln()?)) then
false
else
_every(ln.next() as this->ListNode[A], f)
end


fun box ip_multicast_all()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ip_multicast_ifindex¶
[Source]


# Actor finalisers

Like classes, actors can have finalisers. The finaliser definition is the same (`fun _final()`). All guarantees and restrictions for a class finaliser are also valid for an actor finaliser. In addition, an actor will not receive any further message after its finaliser is called.


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


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

Parameters¶

that: IniIncompleteSection val

Returns¶

Bool val

ne¶
[Source]


1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131


fun box so_numrcvpkt()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

so_oobinline¶
[Source]


PONY_API size_t pony_os_send(asio_event_t* ev, const char* buf, size_t len)
{
ssize_t sent = send(ev->fd, buf, len, 0);

if(sent < 0)
{
if(errno == EWOULDBLOCK || errno == EAGAIN)
return 0;

pony_error();
}

return (size_t)sent;
}
```

A function that calls the `pony_error` function should only be called from inside a `try` block in Pony. If this is not done, the call to `pony_error` will result in a call to C's `abort` function, which will terminate the program.


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

Parameters¶

value: U64 val

Returns¶

U64 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 |


fun box bytewidth()
: USize val

Returns¶

USize val

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

Parameters¶

y: U128 val

Returns¶


# Errors

Pony doesn't feature exceptions as you might be familiar with them from languages like Python, Java, C++ et al. It does, however, provide a simple partial function mechanism to aid in error handling. Partial functions and the `error` keyword used to raise them look similar to exceptions in other languages but have some important semantic differences. Let's take a look at how you work with Pony's error and then how it differs from the exceptions you might be used to.


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


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


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


# Enumeration with values with namespace

```pony
primitive Colours
fun black(): U32 => 0xFF000000
fun red(): U32 => 0xFFFF0000
```


class ref Reader

Constructors¶
create¶
[Source]
new iso create()
: Reader iso^

Returns¶

Reader iso^

Public Functions¶
size¶
[Source]
Return the number of available bytes.
fun box size()
: USize val


.map[U^]({(t) => fn(consume t) })

end)

fun flat_map[U](fn: {(T): Generator[U]} box): Generator[U] =>
"""
For each value of this generator, create a generator that is then combined.
"""
// TODO: enable proper shrinking:
Generator[U](
object is GenObj[U]
fun generate(rnd: Randomness): GenerateResult[U] ? =>
let value: T = _gen.generate_value(rnd)?
fn(consume value).generate_and_shrink(rnd)?

end)

fun union[U](other: Generator[U]): Generator[(T | U)] =>
"""
Create a generator that produces the value of this generator or the other


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


[Source]
Returns true if this is null (ie apply would raise an error).
fun box is_none()
: Bool val

Returns¶

Bool val


fun box sctp_pcb_flags_socket_allgone()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_pcb_flags_socket_gone¶
[Source]


or rejected, immediately fulfill or reject the incoming step. Otherwise,
keep it in a list.
"""
if _value is _Pending then
_list.push(consume attach)
elseif _value is _Reject then
attach.reject()
else
try attach(_value as A) end
end

primitive Promises[A: Any #share]
fun join(ps: Iterator[Promise[A]]): Promise[Array[A] val] =>
"""
Create a promise that is fulfilled when all promises in the given sequence
are fulfilled. If any promise in the sequence is rejected then the new
promise is also rejected. The order that values appear in the final array
is based on when each promise is fulfilled and not the order that they are
given.


false

fun ref _complete_reads(len: U32) =>
"""
The OS has informed us that `len` bytes of pending reads have completed.
This occurs only with IOCP on Windows.
"""
ifdef windows then
if len == 0 then
// The socket has been closed from the other side, or a hard close has
// cancelled the queued read.
_readable = false
_shutdown_peer = true
close()
return
end

_read_buf_offset = _read_buf_offset + len.usize()

while (not _muted) and (_read_buf_offset >= _expect)


Bool val

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

Parameters¶

that: FormatUTF32 val

Returns¶

Bool val


fun box ipproto_tcp()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipproto_tp¶
[Source]


Bool val


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

Returns¶

String iso^

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

Parameters¶


fun box f64_unsafe()
: F64 val

Returns¶

F64 val

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

Parameters¶

that: USize val

Returns¶


"""
FileInfo._descriptor(_fd, path)?

fun chmod(mode: FileMode box): Bool =>
"""
Set the FileMode for this directory.
"""
_FileDes.chmod(_fd, path, mode)

fun chown(uid: U32, gid: U32): Bool =>
"""
Set the owner and group for this directory. Does nothing on Windows.
"""
_FileDes.chown(_fd, path, uid, gid)

fun touch(): Bool =>
"""
Set the last access and modification times of the directory to now.
"""
_FileDes.touch(_fd, path)


y: box->A

Returns¶

Bool val

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

Parameters¶

y: box->A

Returns¶


A

sin¶
[Source]
fun box sin()
: A

Returns¶

A

tan¶
[Source]
fun box tan()
: A

Returns¶


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.
"""
_OSSocket.setsockopt_u32(_fd, level, option_name, option)

fun ref get_so_error(): (U32, U32) =>
"""
Wrapper for the FFI call `getsockopt(fd, SOL_SOCKET, SO_ERROR, ...)`
"""
_OSSocket.get_so_error(_fd)

fun ref get_so_rcvbuf(): (U32, U32) =>
"""
Wrapper for the FFI call `getsockopt(fd, SOL_SOCKET, SO_RCVBUF, ...)`
"""
_OSSocket.get_so_rcvbuf(_fd)


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


fun box tcp_maxolen()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

tcp_maxwin¶
[Source]


U128 val

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

Parameters¶

y: U128 val

Returns¶

U128 val

add_unsafe¶
[Source]


that: ChdirError val

Returns¶

Bool val

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

Parameters¶

that: ChdirError val

Returns¶


__Will my then block really always be executed, even if I return inside the try?__ Yes, your `then` expression will __always__ be executed when the `try` block is complete. The only way it won't be is if the `try` never completes (due to an infinite loop), the machine is powered off, or the process is killed (and then, maybe).


Parameters¶

name': String val
descr': String val = ""
default': (F64 val | None val) = reference

Returns¶

ArgSpec val^

string_seq¶
[Source]
Creates an Arg with a ReadSeq[String] typed value that can be used like
<cmd> file1 file2 file3
to yield a sequence of three strings equivalent to
cmd.arg("file").string_seq() (equiv) ["file1"; "file2"; "file3"].
new val string_seq(
name': String val,


USize val

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

Returns¶

I8 val

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

Returns¶


2 4 6
fun ref filter(
f: {(A!): Bool ?}[A] box)
: Iter[A!] ref^

Parameters¶

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

Returns¶

Iter[A!] ref^

find¶
[Source]
Return the nth value in the iterator that satisfies the predicate f.
Examples¶
Iter[I64]([1; 2; 3].values())


CommonPrefix¶
[Source]
Creates a string that is the common prefix of the supplied strings, possibly
empty.
primitive val CommonPrefix

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

Returns¶


_idx = _min
else
_empty = true
_infinite = false
_idx = _max // has_next() will return false without code modification
end

fun has_next(): Bool =>
if _infinite then
return true
end
if _forward then
_idx < _max
else
_idx > _max
end

fun ref next(): A ? =>
if has_next() then
_idx = _idx + _inc


ULong val

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

Parameters¶

y: ULong val

Returns¶

ULong val

hash¶
[Source]


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


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

Parameters¶

that: AlignLeft val

Returns¶

Bool val

ne¶
[Source]


fun box neg()
: U64 val

Returns¶

U64 val

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

Parameters¶

y: U64 val

Returns¶


Returns¶

String val

options¶
[Source]
Returns a map by name of the named options of this command.
fun box options()
: HashMap[String val, OptionSpec val, HashEq[String val] val] box

Returns¶

HashMap[String val, OptionSpec val, HashEq[String val] val] box

commands¶
[Source]
Returns a map by name of the child commands of this command.


class Dice
class MT
type Rand
trait Random
class SplitMix64
class XorOshiro128Plus
class XorOshiro128StarStar
class XorShift128Plus


_x = 0

new from_int(x: U32) =>
_x = x

class Bar
fun f() =>
var a: Foo = Foo.create()
var b: Foo = Foo.from_int(3)
```

Functions are always called on an object. Again just specify the object, followed by a dot, followed by the name of the function to call. If the object to call on is omitted then the current object is used (i.e. `this`).

```pony
class Foo
var _x: U32

new create() =>
_x = 0


fun box ipv6_tlv_hao()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipv6_tlv_pad1¶
[Source]


Bool val


[Source]
fun box name()
: String val

Returns¶

String val

config¶
[Source]
fun box config()
: BenchConfig val

Returns¶

BenchConfig val

overhead¶


Create a symlink to a file or directory.

Note that on Windows a program must be running with elevated priviledges to
be able to create symlinks.
"""
if not caps(FileLink) or not link_name.caps(FileCreate) then
return false
end

ifdef windows then
try
var err: U32 = 0

// look up the ID of the SE_CREATE_SYMBOLIC_LINK privilege
let priv_name = "SeCreateSymbolicLinkPrivilege"
var luid: U64 = 0
var ret = @LookupPrivilegeValueA(
USize(0),
priv_name.cstring(),
addressof luid)


U64 val

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

Returns¶

U64 val

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

Returns¶


fun box sctp_max_burst()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_max_cwnd¶
[Source]


ansi_term.pony

1
2
3
4
5
6
7
8
9
10
11


and _i3.has_next()
and _i4.has_next()

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

fun ref zip4[B, C, D, E](
i2: Iterator[B],
i3: Iterator[C],
i4: Iterator[D],
i5: Iterator[E])
: Iter[(A, B, C, D, E)]^
=>
"""
Zip five iterators together so that each call to next() results in
a tuple with the next value of each of the iterators. The number of
items returned is the minimum of the number of items returned by the
iterators.
"""


Public Functions¶
entries¶
[Source]
The entries will include everything in the directory, but it is not
recursive. The path for the entry will be relative to the directory, so it
will contain no directory separators. The entries will not include "." or
"..".
fun box entries()
: Array[String val] iso^ ?

Returns¶

Array[String val] iso^ ?

open¶
[Source]
Open a directory relative to this one. Raises an error if the path is not
within this directory hierarchy.
fun box open(


option_name: I32 val,
option_max_size: USize val = 4)
: (U32 val , Array[U8 val] iso^)

Parameters¶

level: I32 val
option_name: I32 val
option_max_size: USize val = 4

Returns¶

(U32 val , Array[U8 val] iso^)

getsockopt_u32¶
[Source]
Wrapper for UDP sockets to the getsockopt(2) system call where
the kernel's returned option value is a C uint32_t type / Pony
type U32.


Returns¶

Bool val

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

Parameters¶

that: DeserialiseAuth val

Returns¶

Bool val


"""
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 neg_unsafe(): A =>
"""
Unsafe operation.
If the operation overflows, the result is undefined.
"""
-~this

fun addc(y: A): (A, Bool)
"""
Add `y` to this integer and return the result and a flag indicating overflow.
"""
fun subc(y: A): (A, Bool)
"""


fun box tcpolen_sack_permitted()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

tcpolen_timestamp¶
[Source]


class val FileInfo
"""
This contains file system metadata for a path.

A symlink will report information about itself, other than the size which
will be the size of the target. A broken symlink will report as much as it
can and will set the broken flag.
"""
let filepath: FilePath

let mode: FileMode val = recover FileMode end
"""UNIX-style file mode."""

let hard_links: U32 = 0
"""Number of hardlinks to this `filepath`."""

let device: U64 = 0
"""
OS id of the device containing this `filepath`.


PrefixNumber¶
[Source]
type PrefixNumber is
(PrefixDefault val | PrefixSpace val | PrefixSign val)

Type Alias For¶

(PrefixDefault val | PrefixSpace val | PrefixSign val)


The smallest shrunken sample will then be reported to the user.

A [Property1](pony_check-Property1.md) can be run with
[Ponytest](pony_test--index.md).
To that end it needs to be wrapped into a
[Property1UnitTest](pony_check-Property1UnitTest.md).
"""
fun name(): String
"""
The name of the property used for reporting during execution.
"""

fun params(): PropertyParams =>
"""
Returns parameters to customize execution of this Property.
"""
PropertyParams

fun gen(): Generator[T]
"""


fun box sctp_pluggable_ss()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_pr_assoc_status¶
[Source]


DebugStream¶
[Source]
type DebugStream is
(DebugOut val | DebugErr val)

Type Alias For¶

(DebugOut val | DebugErr val)


Walks a directory structure starting at this.

`handler(dir_path, dir_entries)` will be called for each directory
starting with this one. The handler can control which subdirectories are
expanded by removing them from the `dir_entries` list.
"""
try
with dir = Directory(this)? do
var entries: Array[String] ref = dir.entries()?
handler(this, entries)
for e in entries.values() do
let p = this.join(e)?
let info = FileInfo(p)?
if info.directory and (follow_links or not info.symlink) then
p.walk(handler, follow_links)
end
end
end
else
return


fun box u32()
: U32 val

Returns¶

U32 val

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

Returns¶

U64 val

u128¶
[Source]


var vec = this
var prev = value
for idx in mut.Range(i, _size) do
vec = vec.update(idx, prev = this(idx)?)?
end
vec.push(this(_size - 1)?)

fun val delete(i: USize): Vec[A] ? =>
"""
Return a vector with an element deleted. Elements after this are moved
down by one index, compacting the vector. An out of bounds index raises an
error.
"""
if i >= _size then error end
var vec = pop()?
for idx in mut.Range(i + 1, _size) do
vec = vec.update(idx - 1, this(idx)?)?
end
vec


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


platform.pony

1
2
3
4
5
6
7
8
9
10
11


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


i32¶
fun box i32()
: I32 val

Returns¶

I32 val

i64¶
fun box i64()
: I64 val

Returns¶

I64 val

ilong¶
fun box ilong()


(ULong val , Bool val)

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

Parameters¶

y: ULong val

Returns¶

(ULong val , Bool val)

mulc¶
[Source]


read_seq.pony

1
2
3
4
5
6
7
8
9
10
11


CreateFile¶
[Source]
Open a File for read/write, creating if it doesn't exist, preserving the
contents if it does exist.
primitive val CreateFile

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

Returns¶


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


(u8()?.u16() << 8) or u8()?.u16()
end
else
error
end

fun ref u16_le(): U16 ? =>
"""
Get a little-endian U16.
"""
let num_bytes = U16(0).bytewidth()
if _available >= num_bytes then
let node = _chunks.head()?
(var data, var offset) = node()?
if (data.size() - offset) >= num_bytes then
let r =
ifdef littleendian then
data.read_u16(offset)?
else
data.read_u16(offset)?.bswap()


ISize val^

max_value¶
[Source]
new val max_value()
: ISize val^

Returns¶

ISize val^

Public Functions¶
abs¶
[Source]
fun box abs()
: USize val

Returns¶


USize val

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

Returns¶

F32 val

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

Returns¶


Returns¶

None val

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

Parameters¶

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

Returns¶


# The list of reference capabilities

There are six reference capabilities in Pony and they all have strict definitions and rules on how they can be used. We'll get to all of that later, but for now here are their names and what you use them for:

__Isolated__, written `iso`. This is for references to isolated data structures. If you have an `iso` variable then you know that there are no other variables that can access that data. So you can change it however you like and give it to another actor.

__Value__, written `val`. This is for references to immutable data structures. If you have a `val` variable then you know that no-one can change the data. So you can read it and share it with other actors.

__Reference__, written `ref`. This is for references to mutable data structures that are not isolated, in other words, "normal" data. If you have a `ref` variable then you can read and write the data however you like and you can have multiple variables that can access the same data. But you can't share it with other actors.

__Box__. This is for references to data that is read-only to you. That data might be immutable and shared with other actors or there may be other variables using it in your actor that can change the data. Either way, the `box` variable can be used to safely read the data. This may sound a little pointless, but it allows you to write code that can work for both `val` and `ref` variables, as long as it doesn't write to the object.

__Transition__, written `trn`. This is used for data structures that you want to write to, while also holding read-only (`box`) variables for them. You can also convert the `trn` variable to a `val` variable later if you wish, which stops anyone from changing the data and allows it be shared with other actors.

__Tag__. This is for references used only for identification. You cannot read or write data using a `tag` variable. But you can store and compare `tag`s to check object identity and share `tag` variables with other actors.

Note that if you have a variable referring to an actor then you can send messages to that actor regardless of what reference capability that variable has.


fun box u8_unsafe()
: U8 val

Returns¶

U8 val

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

Returns¶

U16 val

u32_unsafe¶
[Source]


fun box so_dontlinger()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

so_donttrunc¶
[Source]


fun box ipproto_mpls()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipproto_mux¶
[Source]


I32 val

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

Returns¶

I64 val

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

Returns¶


IniParse¶
[Source]
This is used to parse INI formatted text as a nested map of strings.
primitive val IniParse

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

Returns¶


: Bool val

Parameters¶

expect: A
actual: A
msg: String val = ""
loc: SourceLoc val = __loc

Returns¶

Bool val

assert_isnt[A: A]¶
[Source]
Assert that the 2 given expressions resolve to different instances.
fun box assert_isnt[A: A](
not_expect: A,
actual: A,


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

Parameters¶

y: USize val

Returns¶

USize val

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

Parameters¶


(F64 val , U32 val)

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

Returns¶

F64 val

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

Returns¶


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

Parameters¶

y: I128 val

Returns¶

I128 val

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

Parameters¶


[Source]
new ref create(
iter: Iterator[A] ref)
: Iter[A] ref^

Parameters¶

iter: Iterator[A] ref

Returns¶

Iter[A] ref^

maybe¶
[Source]
new ref maybe(
value: (A | None val))
: Iter[A] ref^


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

Parameters¶

y: F64 val

Returns¶

F64 val

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

Parameters¶


972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990class Array[A] is Seq[A]
"""


Parameters¶

t: U64 val

Returns¶

U64 val

from_seconds_f¶
[Source]
fun box from_seconds_f(
t: F64 val)
: U64 val

Parameters¶

t: F64 val


[Source]
The command line used to start the program.

let vars: Array[String val] val¶
[Source]
The program's environment variables.

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


CountdownIter[optional T: ((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) & Integer[T] val)]¶
[Source]
class ref CountdownIter[optional T: ((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) & Integer[T] val)] is
Iterator[T] ref

Implements¶

Iterator[T] ref


list_node.pony

1
2
3
4
5
6
7
8
9
10
11


fun box u128()
: U128 val

Returns¶

U128 val

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

Returns¶

ULong val

usize¶
[Source]


end
```


fun box rotr(
y: USize val)
: USize val

Parameters¶

y: USize val

Returns¶

USize val

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

Returns¶


fun box tcp_cookie_max()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

tcp_cookie_out_never¶
[Source]


new max_value() => 0x7FFF

fun abs(): U16 => if this < 0 then (-this).u16() else this.u16() end
fun bit_reverse(): I16 => @"llvm.bitreverse.i16"(this.u16()).i16()
fun bswap(): I16 => @"llvm.bswap.i16"(this.u16()).i16()
fun popcount(): U16 => @"llvm.ctpop.i16"(this.u16())
fun clz(): U16 => @"llvm.ctlz.i16"(this.u16(), false)
fun ctz(): U16 => @"llvm.cttz.i16"(this.u16(), false)

fun clz_unsafe(): U16 =>
"""
Unsafe operation.
If this is 0, the result is undefined.
"""
@"llvm.ctlz.i16"(this.u16(), true)

fun ctz_unsafe(): U16 =>
"""
Unsafe operation.
If this is 0, the result is undefined.


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


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


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

Parameters¶

that: AlignCenter val

Returns¶

Bool val


Bool val


",
n: USize val = 0)
: Array[String val] iso^

Parameters¶

delim: String val = "
"
n: USize val = 0

Returns¶

Array[String val] iso^

strip¶
[Source]
Remove all leading and trailing characters from the string that are in s.
fun ref strip(
s: String box = "


fun box netlink_rx_ring()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

netlink_selinux¶
[Source]


fun sctp_pcb_flags_frag_interleave():I32 => @pony_os_sockopt_option(I32(702))
fun sctp_pcb_flags_interleave_strms():I32 => @pony_os_sockopt_option(I32(703))
fun sctp_pcb_flags_in_tcppool():I32 => @pony_os_sockopt_option(I32(704))
fun sctp_pcb_flags_multiple_asconfs():I32 => @pony_os_sockopt_option(I32(705))
fun sctp_pcb_flags_needs_mapped_v4():I32 => @pony_os_sockopt_option(I32(706))
fun sctp_pcb_flags_nodelay():I32 => @pony_os_sockopt_option(I32(707))
fun sctp_pcb_flags_no_fragment():I32 => @pony_os_sockopt_option(I32(708))
fun sctp_pcb_flags_pdapievnt():I32 => @pony_os_sockopt_option(I32(709))
fun sctp_pcb_flags_portreuse():I32 => @pony_os_sockopt_option(I32(710))
fun sctp_pcb_flags_recvassocevnt():I32 => @pony_os_sockopt_option(I32(711))
fun sctp_pcb_flags_recvdataioevnt():I32 => @pony_os_sockopt_option(I32(712))
fun sctp_pcb_flags_recvnsendfailevnt():I32 => @pony_os_sockopt_option(I32(713))
fun sctp_pcb_flags_recvnxtinfo():I32 => @pony_os_sockopt_option(I32(714))
fun sctp_pcb_flags_recvpaddrevnt():I32 => @pony_os_sockopt_option(I32(715))
fun sctp_pcb_flags_recvpeererr():I32 => @pony_os_sockopt_option(I32(716))
fun sctp_pcb_flags_recvrcvinfo():I32 => @pony_os_sockopt_option(I32(717))
fun sctp_pcb_flags_recvsendfailevnt():I32 => @pony_os_sockopt_option(I32(718))
fun sctp_pcb_flags_recvshutdownevnt():I32 => @pony_os_sockopt_option(I32(719))
fun sctp_pcb_flags_socket_allgone():I32 => @pony_os_sockopt_option(I32(720))
fun sctp_pcb_flags_socket_cant_read():I32 => @pony_os_sockopt_option(I32(721))


# What is denied

We're going to talk about reference capability guarantees in terms of what's _denied_. By this, we mean: what can other variables _not_ do when you have a variable with a certain reference capability?

We need to distinguish between the actor that contains the variable in question and _other_ actors.

This is important because data reads and writes from other actors may occur concurrently. If two actors can both read the same data and one of them changes it then it will change under the feet of the other actor. This leads to data-races and the need for locks. By ensuring this situation can never occur, Pony eliminates the need for locks.

All code within any one actor always executes sequentially. This means that data accesses from multiple variables within a single actor do not suffer from data-races.


Returns¶

U32 val

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

Returns¶

U32 val

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


_edit.clear()
home()
| 0x17 => _delete_prev_word() // ctrl-w
| 0x7F => _backspace() // backspace
| if input < 0x20 => None // unknown control character
else
// Insert.
_edit.insert_byte(_cur_pos, input)
_cur_pos = _cur_pos + 1
_refresh_line()
end

fun ref prompt(term: ANSITerm ref, value: String) =>
"""
Set a new prompt, unblock, and handle the pending queue.
"""
_cur_prompt = value
_blocked = false

try


op_or¶
[Source]
The union of this and that.
fun box op_or(
that: Flags[A, B] box)
: Flags[A, B] iso^

Parameters¶

that: Flags[A, B] box

Returns¶

Flags[A, B] iso^

op_and¶
[Source]
The intersection of this and that.


proxy.pony

1
2
3
4
5
6
7
8
9
10
11


ProcessErrorType¶
[Source]
type ProcessErrorType is
(ExecveError val | PipeError val | ForkError val | WaitpidError val | WriteError val | KillError val | CapError val | ChdirError val | UnknownError val)

Type Alias For¶

(ExecveError val | PipeError val | ForkError val | WaitpidError val | WriteError val | KillError val | CapError val | ChdirError val | UnknownError val)


U64 val

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

Parameters¶

y: U64 val

Returns¶

U64 val

shr_unsafe¶
[Source]


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


y: I16 val

Returns¶

Bool val

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

Returns¶

USize val

hash64¶
[Source]


vec.pony

1
2
3
4
5
6
7
8
9
10
11


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

Returns¶

String iso^

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

Parameters¶


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

Returns¶

String val

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

Parameters¶


n: N

Returns¶

N

real¶
[Source]
fun ref real()
: F64 val

Returns¶

F64 val

shuffle[A: A]¶
[Source]


| let prev_value: A! =>
if (_prev_hash == cur_hash) and H.eq(prev_value, cur_value) then
this.next()?
else
_prev_value = cur_value
_prev_hash = cur_hash
cur_value
end
| None =>
_prev_value = cur_value
_prev_hash = cur_hash
cur_value
end
end)

fun ref enum[B: (Real[B] val & Number) = USize](): Iter[(B, A)]^ =>
"""
An iterator which yields the current iteration count as well as the next
value from the iterator.


fun box bitwidth()
: U8 val

Returns¶

U8 val

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

Returns¶

USize val

min¶
[Source]


I32 val^

max_value¶
[Source]
new val max_value()
: I32 val^

Returns¶

I32 val^

Public Functions¶
abs¶
[Source]
fun box abs()
: U32 val

Returns¶


| let se: SyntaxError => return se
end
| None => return SyntaxError(_short_string(c), "unknown short option")
end
end
options

fun _parse_arg(token: String, arg_pos: USize): (Arg | SyntaxError) =>
try
let arg_spec = _spec.args()(arg_pos)?
_ArgParser.parse(arg_spec, token)
else
return SyntaxError(token, "too many positional arguments")
end

fun _option_with_name(name: String): (OptionSpec | None) =>
try
return _spec.options()(name)?
end
match _parent


fun box sctp_auth_delete_key()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_auth_supported¶
[Source]


Nil[A] val

prepend¶
[Source]
Builds a new list with an element added to the front of this list.
fun box prepend(
a: val->A!)
: Cons[A] val

Parameters¶

a: val->A!

Returns¶

Cons[A] val


U64 val

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

Returns¶

I8 val

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

Returns¶


Returns¶

String val

underline¶
[Source]
Underlined text. Does nothing on Windows.
fun box underline(
state: Bool val = true)
: String val

Parameters¶

state: Bool val = true

Returns¶

String val


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


rnd: Randomness ref

Returns¶

(T^ | (T^ , Iterator[T^] ref)) ?

shrink¶
[Source]
fun box shrink(
t: T)
: (T^ , Iterator[T^] ref)

Parameters¶

t: T

Returns¶

(T^ , Iterator[T^] ref)


I16 val

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

Returns¶

I32 val

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

Returns¶


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

Parameters¶

y: ULong val

Returns¶

(ULong val , Bool val)

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

Parameters¶


Returns¶

U8 val

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

Returns¶

U8 val

bitwidth¶
[Source]


fun box icmp_port_unreach()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

icmp_prec_violation¶
[Source]


Returns¶

USize val

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

Returns¶

U64 val

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


offset: ISize = 0,
base: U8 = 0)
: (A, USize /* chars used */) ?
=>
"""
Read an integer from the specified location in this string. The integer
value read and the number of bytes consumed are reported.
The base parameter specifies the base to use, 0 indicates using the prefix,
if any, to detect base 2, 10 or 16.
If no integer is found at the specified location, then (0, 0) is returned,
since no characters have been used.
An integer out of range for the target type throws an error.
A leading minus is allowed for signed integer types.
Underscore characters are allowed throughout the integer and are ignored.
"""
let start_index = offset_to_index(offset)
var index = start_index
var value: A = 0
var had_digit = false


(A , A) ?

fld_partial¶
[Source]
fun box fld_partial(
y: A)
: A ?

Parameters¶

y: A

Returns¶

A ?

mod_partial¶
[Source]


actual: ReadSeq[A],
msg: String = "",
loc: SourceLoc = __loc)
: Bool
=>
"""
Assert that the contents of the 2 given ReadSeqs are equal.

The type parameter of this function is the type parameter of the
elements in both ReadSeqs. For instance, when comparing two `Array[U8]`,
you should call this method as follows:

```pony
fun apply(h: TestHelper) =>
let a: Array[U8] = [1; 2; 3]
let b: Array[U8] = [1; 2; 3]
h.assert_array_eq[U8](a, b)
```
"""
var ok = true


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


32
33
34
35
36
37
38
39
40
41interface UDPNotify
"""
Notifications for UDP connections.

For an example of using this class please see the documentatoin for the
`UDPSocket` actor.
"""
fun ref listening(sock: UDPSocket ref) =>
"""
Called when the socket has been bound to an address.
"""


So:
`<PREFIX><KEY>=<VALUE>`
becomes:
`{KEY, VALUE}` or `{key, VALUE}`
"""
let envsmap = recover Map[String, String]() end
match envs
| let envsarr: Array[String] box =>
let prelen = prefix.size().isize()
for e in envsarr.values() do
let eqpos = try e.find("=")? else ISize.max_value() end
let ek: String val = e.substring(0, eqpos)
let ev: String val = e.substring(eqpos + 1)
if (prelen == 0) or ek.at(prefix, 0) then
if squash then
envsmap.update(ek.substring(prelen).lower(), ev)
else
envsmap.update(ek.substring(prelen), ev)
end


String iso^

upper_in_place¶
[Source]
Transforms the string to upper case.
fun ref upper_in_place()
: None val

Returns¶

None val

reverse¶
[Source]
Returns a reversed version of the string.
fun box reverse()
: String iso^


[Source]
fun box oneshot()
: U32 val

Returns¶

U32 val

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

Returns¶

U32 val

eq¶


# Caveat

The runtime backpressure is a powerful system. By intervening, programmers can
create deadlocks. Any call to `Backpressure.apply` should be matched by a
corresponding call to `Backpressure.release`. Authorization via the
`ApplyReleaseBackpressureAuth` capability is required to apply or release
backpressure. By requiring that the caller have a token to apply or release a
backpressure, rouge 3rd party library code can't run wild and unknowingly
interfere with the runtime.
"""

use @pony_apply_backpressure[None]()
use @pony_release_backpressure[None]()

primitive Backpressure
fun apply(auth: ApplyReleaseBackpressureAuth) =>
@pony_apply_backpressure()

fun release(auth: ApplyReleaseBackpressureAuth) =>
@pony_release_backpressure()


from: (AmbientAuth val | NetAuth val | TCPAuth val)

Returns¶

TCPConnectAuth val^

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

Parameters¶

that: TCPConnectAuth val

Returns¶


Benchmark Overhead                        552 ns            552 ns      ±0.39%      300000
_Timer (10000 ns)                       10780 ns          10800 ns      ±3.60%       10000

It is recommended that a PonyBench program is compiled with the --runtimebc
option, if possible, and run with the --ponynoyield option.
Public Types¶

class AsyncBenchContinue
trait AsyncMicroBenchmark
class AsyncOverheadBenchmark
class BenchConfig
type Benchmark
interface BenchmarkList
trait MicroBenchmark
class OverheadBenchmark
actor PonyBench


end
else
let r = @fsync(_fd)
if r < 0 then
_errno = _get_error()
end
end
end
_unsynced_data = false
_unsynced_metadata = false

fun ref datasync() =>
"""
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


that: Assert val)
: Bool val

Parameters¶

that: Assert val

Returns¶

Bool val


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


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


852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871


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


fun box tcp_noopt()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

tcp_notsent_lowat¶
[Source]


1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031


fun box bytewidth()
: USize val

Returns¶

USize val

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

Parameters¶

y: U16 val

Returns¶


flags: U32 val

Returns¶

Bool val

disposable¶
[Source]
Returns true if the event should be disposed of.
fun box disposable(
flags: U32 val)
: Bool val

Parameters¶

flags: U32 val

Returns¶


y: U128 val

Returns¶

U128 val

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

Parameters¶

y: U128 val

Returns¶


y: U16 val

Returns¶

U16 val

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

Parameters¶

y: U16 val

Returns¶


Returns¶

None val


fun box hash64()
: U64 val

Returns¶

U64 val

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

Returns¶

String iso^

mul¶
[Source]


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


fun box rds_info_connection_flag_connecting()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

rds_info_connection_stats¶
[Source]


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


(_read_buf, let len, let errno) =
pipe.read(_read_buf = recover Array[U8] end, _read_len)

let next = _read_buf.space()
match len
| -1 =>
if (errno == _EAGAIN()) then
return // nothing to read right now, try again later
end
pipe.close()
return
| 0  =>
pipe.close()
return
end

_read_len = _read_len + len.usize()

let data = _read_buf = recover Array[U8] .> undefined(next) end
data.truncate(_read_len)


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


fun floor(): F32 => @"llvm.floor.f32"(this)
fun round(): F32 => @"llvm.round.f32"(this)
fun trunc(): F32 => @"llvm.trunc.f32"(this)

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

fun fld(y: F32): F32 =>
(this / y).floor()

fun fld_unsafe(y: F32): F32 =>
(this /~ y).floor()

fun mod(y: F32): F32 =>
let r = this % y
if r == F32(0.0) then
r.copysign(y)
elseif (r > 0) xor (y > 0) then
r + y
else


fun box f64()
: F64 val

Returns¶

F64 val

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

Returns¶

I8 val

i16_unsafe¶
[Source]


fun ref set_ip_multicast_loop(loopback: Bool): U32 =>
"""
Wrapper for the FFI call `setsockopt(fd, SOL_SOCKET, IP_MULTICAST_LOOP, ...)`
"""
var word: Array[U8] ref =
_OSSocket.u32_to_bytes4(if loopback then 1 else 0 end)
_OSSocket.setsockopt(_fd, OSSockOpt.sol_socket(), OSSockOpt.ip_multicast_loop(), word)

fun ref set_ip_multicast_ttl(ttl: U8): U32 =>
"""
Wrapper for the FFI call `setsockopt(fd, SOL_SOCKET, IP_MULTICAST_TTL, ...)`
"""
var word: Array[U8] ref = _OSSocket.u32_to_bytes4(ttl.u32())
_OSSocket.setsockopt(_fd, OSSockOpt.sol_socket(), OSSockOpt.ip_multicast_ttl(), word)

fun ref set_so_broadcast(state: Bool): U32 =>
"""
Wrapper for the FFI call `setsockopt(fd, SOL_SOCKET, SO_BROADCAST, ...)`
"""
var word: Array[U8] ref =


if s != _alloc then
_size = s
end

fun ref truncate(len: USize) =>
"""
Truncates the string at the minimum of len and space. Ensures there is a
null terminator. Does not check for null terminators inside the string.

Note that memory is not freed by this operation.
"""
if len >= _alloc then
_size = len.min(_alloc)
reserve(_alloc + 1)
else
_size = len.min(_alloc - 1)
end

_set(_size, 0)


# Calling FFI functions from Interfaces or Traits

We mentioned in the previous section that FFI declarations are scoped to a single Pony package, with separate packages possibly defining different FFI signatures for the same C function. Importing an external package will not import any FFI declarations, since any name collisions would produce multiple declarations for the same C function name, and thus deciding which declaration to use would be ambiguous.

Given the above fact, if you define any default methods (or behaviors) in an interface or trait, you will not be able to perform an FFI call from them. For example, the code below will fail to compile:

```pony
use @printf[I32](fmt: Pointer[None] tag, ...)

trait Foo
fun apply() =>
// Error: Can't call an FFI function in a default method or behavior
@printf("Hello from trait Foo\n".cstring())

actor Main is Foo
new create(env: Env) =>
this.apply()
```

If the trait `Foo` above was part of the public API of a package, allowing its `apply` method to perform an FFI call would render `Foo` unusable for any external users, given that the declaration for `printf` would not be in scope.


By making the change above, we avoid exposing the call to `printf` to any consumers of our trait, thus making it usable by external users.


fun box divrem_partial(
y: U64 val)
: (U64 val , U64 val) ?

Parameters¶

y: U64 val

Returns¶

(U64 val , U64 val) ?

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

Parameters¶


52
53
54
55
56
57trait UnitTest
"""
Each unit test class must provide this trait. Simple tests only need to
define the name() and apply() functions. The remaining functions specify
additional test options.
"""

fun name(): String
"""
Report the test name, which is used when printing test results and on the
command line to select tests to run.
"""

fun exclusion_group(): String =>
"""


fun box div(
y: A)
: A

Parameters¶

y: A

Returns¶

A

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

Parameters¶


fun box u32()
: U32 val

Returns¶

U32 val

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

Returns¶

U64 val

u128¶
[Source]


Generator[(T1 , T2)] box

zip3[T1: T1, T2: T2, T3: T3]¶
[Source]
Zip three generators into a generator of a 3-tuple
containing the values generated by those three generators.
fun box zip3[T1: T1, T2: T2, T3: T3](
gen1: Generator[T1] box,
gen2: Generator[T2] box,
gen3: Generator[T3] box)
: Generator[(T1 , T2 , T3)] box

Parameters¶

gen1: Generator[T1] box
gen2: Generator[T2] box
gen3: Generator[T3] box

Returns¶


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


KillError¶
[Source]
primitive val KillError

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

Returns¶

KillError val^


USize val

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

Parameters¶

that: I128 val

Returns¶

(Less val | Equal val | Greater val)


## Private methods

A key difference between traits and interfaces is that interfaces can't have private methods. So, if you need private methods, you'll need to use a trait and have users opt in via nominal typing. Interfaces can't have private methods because otherwise, users could use them to break encapsulation and access private methods on concrete types from other packages. For example:

```pony
actor Main
new create(env: Env) =>
let x: String ref = "sailor".string()
let y: Foo = x
y._set(0, 'f')
env.out.print("Hello, " + x)

interface Foo
fun ref _set(i: USize, value: U8): U8
```

In the code above, the interface `Foo` allows access to the private `_set` method of `String` and allows for changing `sailor` to `failor` or it would anyway, if interfaces were allowed to have private methods.


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26class Dice
"""
A simple dice roller.
"""
var r: Random


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

Returns¶

U16 val

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

Returns¶

U32 val


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


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


is undefined.
The operation isn't required to fully comply to IEEE 754 semantics.
fun box neg_unsafe()
: A

Returns¶

A

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


StdStream¶
[Source]
Asynchronous access to stdout and stderr. The constructors are private to
ensure that access is provided only via an environment.
actor tag StdStream

Public Behaviours¶
print¶
[Source]
Print some bytes and insert a newline afterwards.
be print(
data: (String val | Array[U8 val] val))


_fail()
end

be _run_iteration(n: U64 = 0, a: U64 = 0) =>
if n == _aggregator.iterations then
_complete(a)
else
try
_bench.before_iteration()?
let s =
ifdef x86 then
Time.perf_begin()
else
Time.nanos()
end
_bench()?
let e =
ifdef x86 then
Time.perf_end()
else


```pony
class Foo
var x: String ref

class Bar
fun f() =>
var y: Foo trn = get_foo_trn()
var z: String box = y.x
```


fun box ilong_unsafe()
: ILong val

Returns¶

ILong val

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

Returns¶

ISize val

u8_unsafe¶
[Source]


file_caps.pony

1
2
3
4
5
6
7
8
9
10
11


(ISize val , Bool val)

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

Parameters¶

y: ISize val

Returns¶

(ISize val , Bool val)

fldc¶


: Bool val

Parameters¶

value: box->A!

Returns¶

Bool val

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

Returns¶

None val


Nanos¶
[Source]
Collection of utility functions for converting various durations of time
to nanoseconds, for passing to other functions in the time package.
primitive val Nanos

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

Returns¶


"""
Return a vector with the i-th element changed, raising an error if the
index is out of bounds.
"""
if i < _tail_offset() then
let root = (_root as _VecNode[A]).update(_depth, i, value)?
_create(root, _tail, _size, _depth)
else
let tail =
recover val _tail.clone() .> update(i - _tail_offset(), value)? end
_create(_root, tail, _size, _depth)
end

fun val insert(i: USize, value: val->A): Vec[A] ? =>
"""
Return a vector with an element inserted. Elements after this are moved
up by one index, extending the vector. An out of bounds index raises an
error.
"""
if i >= _size then error end


Array[A: A]¶
[Source]
Contiguous, resizable memory to store elements of type A.
Usage¶
Creating an Array of String:
let array: Array[String] = ["dog"; "cat"; "wombat"]
// array.size() == 3
// array.space() >= 3

Creating an empty Array of String, which may hold at least 10 elements before
requesting more space:
let array = Array[String](10)
// array.size() == 0


qty: USize val = 0

Returns¶

None val ?

set_nodelay¶
[Source]
Turn Nagle on/off. Defaults to on. This can only be set on a connected
socket.
fun ref set_nodelay(
state: Bool val)
: None val

Parameters¶

state: Bool val

Returns¶


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


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


Returns¶

this->A ?

push¶
[Source]
Push an item into the heap.
The time complexity of this operation is O(log(n)) with respect to the size
of the heap.
fun ref push(
value: A)
: None val

Parameters¶

value: A

Returns¶


fun box sctp_sack_rwnd_logging_enable()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_sat_network_min¶
[Source]


None val

trim_in_place¶
[Source]
Trim the array to a portion of itself, covering from until to.
Unlike slice, the operation does not allocate a new array nor copy elements.
fun ref trim_in_place(
from: USize val = 0,
to: USize val = call)
: None val

Parameters¶

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

Returns¶

None val


This might error, which does not necessarily mean that the Iterator is exhausted.
fun ref next()
: A ?

Returns¶

A ?


a: A

Returns¶

A^

eq¶
[Source]
fun box eq(
that: Sort[A, B] val)
: Bool val

Parameters¶

that: Sort[A, B] val

Returns¶

Bool val


else
@"llvm.sqrt.f32"(this)
end

fun sqrt_unsafe(): F32 =>
"""
Unsafe operation.
If this is negative, the result is undefined.
"""
@"llvm.sqrt.f32"(this)

fun cbrt(): F32 => @cbrtf(this)
fun exp(): F32 => @"llvm.exp.f32"(this)
fun exp2(): F32 => @"llvm.exp2.f32"(this)

fun cos(): F32 => @"llvm.cos.f32"(this)
fun sin(): F32 => @"llvm.sin.f32"(this)
fun tan(): F32 => @tanf(this)

fun cosh(): F32 => @coshf(this)


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


### Example

```pony
Iter[I64]([1; 2; 3].values())
.map[I64]({(x) => x * x })
```
`1 4 9`
"""
map_stateful[B]({(a: A!): B ? => f(a) ? })

fun ref nth(n: USize): A ? =>
"""
Return the nth value of the iterator.


File¶
[Source]
Operations on a file.
class ref File

Constructors¶
create¶
[Source]
Attempt to open for read/write, creating if it doesn't exist, preserving
the contents if it does exist.
Set errno according to result.
new ref create(
from: FilePath val)


```pony
fun test(a: Wombat trn) =>
var b: Wombat box = a // Allowed!
```

__What about aliasing other stuff?__ For both `iso` and `trn`, the guarantees require that aliases must give up on some ability (reading and writing for `iso`, writing for `trn`). For the other capabilities (`ref`, `val`, `box` and `tag`), aliases allow for the same operations, so such a reference can just be aliased as itself.


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 fld_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.
"""

fun divrem_unsafe(y: A): (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.


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


Listens for IPv4 connections.
"""
_limit = limit
_notify = consume notify
_event =
@pony_os_listen_tcp4(this, host.cstring(), service.cstring())
_read_buffer_size = read_buffer_size
_yield_after_reading = yield_after_reading
_yield_after_writing = yield_after_writing
_fd = @pony_asio_event_fd(_event)
_notify_listening()

new ip6(
auth: TCPListenAuth,
notify: TCPListenNotify iso,
host: String = "",
service: String = "0",
limit: USize = 0,
read_buffer_size: USize = 16384,
yield_after_reading: USize = 16384,


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


Returns¶

Generator[I16 val] box

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

Parameters¶

min: I32 val = call
max: I32 val = call

Returns¶


Parameters¶

i: USize val

Returns¶

Vec[A] val ?

remove¶
[Source]
Return a vector with n elements removed, beginning at index i.
fun val remove(
i: USize val,
n: USize val)
: Vec[A] val ?

Parameters¶

i: USize val


1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111


fun box sctp_idata()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_initiation¶
[Source]


U32 val

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

Returns¶

U32 val

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


Public Functions¶
value¶
[Source]
fun box value()
: U32 val

Returns¶

U32 val

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

Parameters¶


acc: B)
: B
=>
"""
Private helper for `fold`, recursively working with `ListNode`s.
"""
let nextAcc: B = try f(acc, ln()?) else consume acc end
let h = try
ln.next() as this->ListNode[A]
else
return nextAcc
end

_fold[B](h, f, consume nextAcc)

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

```pony


Returns¶

None val

expect¶
[Source]
Called when the process monitor has been told to expect a certain quantity
of bytes. This allows nested notifiers to change the expected quantity,
which allows a lower level protocol to handle any framing.
fun ref expect(
process: ProcessMonitor ref,
qty: USize val)
: USize val

Parameters¶

process: ProcessMonitor ref
qty: USize val


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


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


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


min: USize = 0,
max: USize = 100)
: Generator[String]
=>
"""
Create a generator for unicode strings
from the basic multilingual plane only,
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.
"""
let range_1 = u32(0x0, 0xD7FF)
let range_1_size: USize = 0xD7FF
// excluding surrogate pairs
// this might be duplicate work but increases efficiency
let range_2 = u32(0xE000, 0xFFFF)
let range_2_size = U32(0xFFFF - 0xE000).usize()


fun box sctp_cookie_echoed()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_cwnd_logging_enable¶
[Source]


Return a set with elements that are in either this or that, but not both.
fun val op_xor(
that: (HashSet[A, H] val | Iterator[A] ref))
: HashSet[A, H] val

Parameters¶

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

Returns¶

HashSet[A, H] val

without¶
[Source]
Return a set with the elements of this that are not in that.
fun val without(
that: (HashSet[A, H] val | Iterator[A] ref))
: HashSet[A, H] val


fun box ipv6_pmtudisc_probe()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipv6_prefer_src_cga¶
[Source]


DisposableActor¶
[Source]
An interface used to asynchronously dispose of an actor.
interface tag DisposableActor

Public Behaviours¶
dispose¶
[Source]
be dispose()


U8 val

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

Returns¶

U16 val

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

Returns¶


fun box hash()
: USize val

Returns¶

USize val

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

Parameters¶

y: U64 val

Returns¶


Parameters¶

f: {(A!): Iterator[B] ?}[A, B] box

Returns¶

Iter[B] ref^

fold[B: B]¶
[Source]
Apply a function to every element, producing an accumulated value.
Example¶
Iter[I64]([1; 2; 3].values())
.fold[I64](0, {(sum, x) => sum + x })

6
fun ref fold[B: B](
acc: B,
f: {(B, A!): B^}[A, B] box)


```

Both `Bob` and `Larry` are in the category `HasName`. `Bob` because it has declared that it is a `HasName` and `Larry` because it is structurally a `HasName`.