OxL Справочник OxL
РусскийEnglish

module std.core

Methods of List, Map, Set and String. Intrinsics map to liboxlrt (oxl_list_*, oxl_map_*).

Example:

oxl✓ проверяется в CI
fn main() io {
  var words = ["pear", "fig", "apple"]
  words.sort()
  let lengths = {"pear": 4, "fig": 3}
  var seen: Set<str> = Set.new()
  seen.insert("fig")
  print("{words} {lengths.get("fig")} {seen.contains("fig")} {"a,b".split(",")}")
}
Вывод
["apple", "fig", "pear"] 3 true ["a", "b"]

Dynamic configuration in the prelude (§14.2, D-5190..D-5239): dynamic Limits { rps: u32 = 100 newSearch: Flag = Flag.off }.

The compiler (sema/DynamicSema.cpp) turns the declaration into a data type whose fields are live handles — DynHandle<T> for a typed value, Flag for a flag — and a static Limits.get() that opens them:

oxl
let l = Limits.get()
if current > l.rps.get() { throttle() }
for await v in l.rps.changes() { limiter.set(v) }
if l.newSearch.on(for: ctx.caller) { newSearch(q) } else { oldSearch(q) }

Values live in the cluster (group 0 system KV; a local file on a single node), with one override per layer: global, role, zone, node, tenant of the caller; the most specific wins. Every change is type-checked (refinements included), versioned and can be rolled back. The runtime is runtime/src/dynconf; the compiled policy Limits { allow set if … } is the function passed to open.

Each opened field is served: a daemon task answers the requests of oxl config set|unset|rollback (policy, type check) so that the checks run the program's own code.

Prelude functions (§2.2).

Lazy iterators (§3.8, §5.6, §5.9, the std.iter row of II.1) and query groups.

D-2000: an iter<T> is a synchronous pull closure fn() -> T?; next() calls it and none ends the sequence. Adapters wrap the iterator they consume in a new closure, so nothing runs until the result is pulled. The intrinsics live in compiler/src/codegen/CGQuery.cpp. An iter<T> is affine (it is moved, never copied); adapters take move self, and the functions they receive are escaping (captured by move, borrows rejected). Effects of the functions an adapter receives are charged where the adapter is called (F below).

Numeric specialisations of the lazy iterators (generated by scripts/gen_std_iter_numbers.py — do not edit). sum / product of iter<T> (D-2000).

The running node in the prelude (§2.4, §8.5): node.background.spawn(…).

Methods of the numeric primitives (generated by scripts/gen_std_numbers.py — do not edit). Checked / wrapping / saturating arithmetic, conversions (§3.1), basic float math, List sums. Intrinsics are implemented in compiler/src/codegen/CGIntrinsicsStd.cpp.

Services in the prelude (§10.1, §13.2, D-2900..): the types a program names around service / rpc.

The service declarations themselves are compiled by the compiler (sema/ServiceSema.cpp, codegen/CGService.cpp); the runtime is runtime/src/rpc. What is here: node identity, Principal, the ctx of a handler, Client<S> and the helpers the compiler calls (oxl_rpc_ctx, oxl_rpc_dep).

stream<T, E> (§10.3, D-2600..D-2609): the pull primitives the std.stream operators are written with.

A stream is single-consumer and affine. for await x in s { } is the normal way to consume one (the loop owns the stream and drops it - cancelling the producer - when it ends or is left by break/return/?). The functions here are for library code that needs finer control: one pull, with an optional time limit. Intrinsics: compiler/src/codegen/CGStream.cpp over runtime/src/sched/stream.cpp.

Concurrency primitives of the prelude (§8.3–8.7).

Test helpers of the prelude (§18.2, D-3210..D-3215). They are plain functions: a failed check panics, and oxl test reports the panic message with the values that were compared.

Methods of str, bytes, char, bool and List<str> (§3.2). Intrinsics: compiler/src/codegen/CGIntrinsicsStd.cpp over the runtime (oxl_str_*, runtime/src/std_extra.cpp). Indices are byte offsets (D-803).

Types of topics (§10.5) that the generated declarations of a topic name without an import: they live in the prelude. The functions are in std.topic (std/topic/topic.oxl).

std.core — the prelude (§2.2): imported automatically into every module.

Built-in nominal types are declared with @builtin("Name"); their layout and operations are provided by the compiler and the runtime (liboxlrt). Functions marked @intrinsic have no OxL body: codegen maps them to runtime calls or inline IR. Both attributes are reserved for the standard library.

Zero-copy views of encoded values ([С §9.6], D-6500..D-6549).

decode_view<T>(buf) checks the structure of buf (the OxL binary format, §9.3–9.4) and returns a view T: a borrow of the buffer that reads the fields of T lazily, one field per access, without decoding the rest. view T is the type View<T> below; like &T it must not outlive the buffer, be stored in fields, be captured by escaping closures or be sent to another task (§7.2, diagnostic borrow-escape). v.own() decodes the whole value.

Типы

data AccessDeniedThe policy of the callee refuses the caller (§13).
data ActorRefReference to a local actor (§8.8); messages are sent with method-call syntax.
data AllFailedany combinator: every task failed (§8.3).
data ArcAtomically counted pointer; T must be frozen or sync to be shared between tasks (§7.3).
type boolпсевдоним · std.core
type bytesпсевдоним · std.core
data CallOne recorded call of a mocked rpc (S.calls(.m), §18.3).
data CancelledThe call was cancelled (the caller's task was cancelled or its deadline passed).
data CapturesA match with its capture groups; group 0 is the whole match, groups[i] is none when group i did not take part.
type charпсевдоним · std.core
data ClientClient of service S
data ClientTlstls: of S.connect(addr, tls
interface CloneTypes with an explicit deep copy
data ClosedChannel closed (§8.7).
data ClusterApiThe cluster as seen from a program that did not import std.cluster (cluster.self(), cluster.leader(…) { …
enum ClusterEventMembership changes cluster.on can report (§12.3).
data ClusterIdscluster.ids (§12.6)
data ClusterMemberA member of the cluster as the registry sees it (§12.2, D-4206)
data CompensationFailedA saga could not undo a step after SAGA_UNDO_RETRIES attempts; the saga is stuck and needs manual work (§11.3, D-5103).
interface CopyMarks a type whose values are copied instead of moved (@derive(Copy)).
data CronCron expression (§17.4).
data CtxThe context of a request, available as ctx in impl of a service and propagated into the calls a handler makes.
data DateCalendar date (§17.1).
data DbHandle of an open database (std.orm, §12.8)
data DbErrorA database operation failed
enum DbErrorKindWhy a database operation failed.
enum DecodeErrorWhy bytes could not be decoded into a value ([С §9.4]).
interface DefaultTypes with a default value
interface DropTypes with cleanup code that runs when a value goes out of scope (impl Drop).
data DurationExact time interval in nanoseconds (§17.1).
data DynErrorWhy a dynamic value could not be changed.
type DynGateThe compiled policy Name { allow set if …
data DynHandleA live typed value of a dynamic config (§14.2).
enum DynScopeWhere an override applies (§14.2)
enum EncodeErrorWhy a value could not be encoded (std.ser re-exports it; §9, D-2115).
interface EqTypes whose values can be compared with == (@derive(Eq)).
interface ErrorTracee.trace() on a value of an @error type, and r.trace() on a union that holds one (§6.5, D-3960)
type f32псевдоним · std.core
type f64псевдоним · std.core
data FenceThe fencing token of a held lock (cluster.lockFenced).
data FlagA feature flag with rules (§14.2)
enum FlagByHow a Flag splits traffic (§14.2)
data GroupGroup produced by group by …
data HandleHandle of a spawned task (§8.3).
interface HashTypes that can be keys of a Map or elements of a Set (@derive(Eq, Hash)).
data HlcA hybrid logical clock stamp (§17.3)
type i128псевдоним · std.core
type i16псевдоним · std.core
type i32псевдоним · std.core
type i64псевдоним · std.core
type i8псевдоним · std.core
data InstantMonotonic clock reading, for measurements only (§17.1).
data InvalidValueA value violates the predicate of a refined type (§3.6).
data IoErrorFile system / OS error (std.io, std.os).
enum IoErrorKindWhy a file or OS operation failed
type isizeпсевдоним · std.core
data iterLazy synchronous sequence, source for for (§3.8).
interface IterableSource for for and queries (§4.6)
data LaggedA Broadcast subscriber fell behind and was disconnected (.Disconnect, §10.4); missed elements did not fit.
data ListDynamic array (§3.3).
data LocalDateTimeDate and time without a time zone (§17.1).
data LockTimeoutcluster.lock could not take the lock within the wait time.
data MapHash map with insertion-ordered iteration (§3.3).
data MatchA match: the matched text and its byte range [start, end) in the searched text.
interface MiddlewareThe handler of a user attribute (attr Logged { …
type NetErrorThe errors every rpc, actor message and cluster call can return in addition to its own
type NextThe rest of the chain
data NodeApiThe running node.
data NodeBackgroundThe background scope of the node (§8.5)
data NodeIdIdentity of a node of the cluster (cluster.self(), ctx.node).
interface OrdTypes with a natural order
enum OrderingResult of <=>.
data OutOfRangeChecked conversion out of range (§3.1).
data PanickedA child task panicked (§6.6, §8.5).
data ParseErrorstr.parse<T>() failed
enum PickByHow cluster.pick chooses among the nodes that serve a service.
enum PreferPlacement preference of cluster.pick.
enum PrincipalWho calls (§13.2, D-4672).
data ProtocolErrorEverything else that can go wrong on the wire (§6.5, §10.1)
enum PulledOutcome of one pull (stream.pull, stream.pullWithin).
data Rangea..b (§5.2).
data RangeInclusivea..=b (§5.2).
data RcSingle-task reference counted pointer (§3.9, §7.3)
data ReceiverThe receiving end of a channel made by chan<T>(cap).
data RegexRegular expression (§1.5, D-1802, D-3140); re"…" literals have this type.
data ResponseWhat a middleware returns
data SchemaCompatThe environment with schema(old
data secretA value hidden from logs and traces (§13.3).
data SenderChannel endpoints (§8.7).
interface SerializableTypes that std.ser can encode and decode, and that can cross the network (@derive(Serializable), implicit for plain data).
data SetHash set with insertion-ordered iteration (§3.3).
data ShardInfoOne shard group of the cluster (cluster.shards()).
type SharedA value shared between tasks without copying
interface ShowTypes that can be interpolated into text ("{x}") and printed; every data type has it automatically.
type strпсевдоним · std.core
data streamAsynchronous sequence of T that ends normally or with one error E; source for for await (§10.3, D-2600..).
data StringMutable string buffer (§3.2); freeze() turns it into str.
data TableA table of a database, db.User for a @table type (§12.8); from u in db.User where …
data TaskLazy asynchronous computation with value T or error E (§8.3).
data TestClusterThe environment with cluster(nodes
enum TestDbWhere the data of an integration test lives (db
data TimeUTC instant, nanoseconds since the Unix epoch (§17.1).
data TimeoutA network call did not finish in time (an rpc, an actor message, a socket read).
data TopicErrorThe error of a topic operation
enum TopicErrorKindWhy a topic operation failed.
enum TopicStartWhere a new subscription starts.
data TraceFrameOne frame of an error trace
enum TypeKindKind of a type as seen by comptime reflection (reflect(T).kind, §15.2, D-1906).
data TzIANA time zone (§17.1).
type u128псевдоним · std.core
type u16псевдоним · std.core
type u32псевдоним · std.core
type u64псевдоним · std.core
type u8псевдоним · std.core
data UnavailableThe callee cannot be reached or refuses work right now (refused, reset, no replica, overload).
type usizeпсевдоним · std.core
data Utf8UTF-8 text/bytes conversion (II.1 Utf8).
data Viewview T ([С §9.6])
enum VisibilityVisibility of a field or method as seen by comptime reflection (§2.3, §15.2, D-1908).

Функции

assert_eqFails the test unless left == right; the message shows both values.
assert_failsTest helper (§18.2)
assert_neFails the test unless left != right; the message shows the value.
assert_snapshotCompares {value} with the snapshot of this test in snapshots/ (§18.2, D-7080); oxl test --update-snapshots rewrites it.
chanCreates a channel; cap
dbgDebug print (D-7800)
decode_viewChecks the structure of buf (missing fields, invariants, malformed input
dropDestroys a value immediately (§5.8).
envEnvironment variable, none if unset.
eprintWrites x and a newline to stderr.
freezeMoves value into an immutable shared Arc<frozen T> (§7.3).
fromFnBuilds an iterator from a pull function
iterateInfinite sequence seed, step(seed), step(step(seed)), ….
nowCurrent UTC time (§17.3).
oxl_aroundThe lowering of a handler with user attributes (ServiceSema.cpp)
oxl_atomicallyThe runner of atomic { body } (§8.9, D-7521; the compiler lowers the block to this call)
oxl_rpc_ctxThe ctx of the current request (bound to the name ctx inside handlers by the compiler).
oxlAbRunRuns the experiment spec on its recorded traffic; prints the comparison and fails the test on a violated guard.
oxlContractRoundtripx as an old peer of the contract test's old schema reads it and writes it back (D-7071)
oxlFixtureFinishSecond pull: runs the code after yield and checks that the fixture really ends.
oxlFixtureValueFirst pull of a fixture
oxlFuzzArgA generated argument of a fuzz test (D-7060)
oxlMockCallsOfS.calls(.m) -> List<Call> (§18.3)
oxlMockHitHow many earlier calls the mock arm key answered (the index of the response to give).
oxlMockUnmatchedA call no arm of the mock matches (or an arm whose responses are used up)
oxlProvideSetprovide T = value in a test (§18.2, D-6107)
oxlTestClusterThe environment with cluster(nodes
oxlTestSchemaThe environment with schema(old
panicAborts the current task with a message (§6.6).
printWrites x (via Show) and a newline to stdout.
repeatInfinite sequence of copies of x.
setenvSets an environment variable of this process.
shieldRuns body protected from cancellation (§8.6).
sleepSuspends the current task (§17.4).
unreachableMarks code that must never run (§6.6).

См. также