length: int- Модуль
- std.
bytes → - Получатель
- Bytes
- Минимальное число аргументов
- 0
- Максимальное число аргументов
- 0
Declaration and parameters
СсылкаДоступность
Включено по умолчанию · Не определено
Import std.bytes in language mode 5.21.
The current compiler selects std/bytes.tpz for this language mode. Availability in other released editions and inclusion in each installed distribution are Pending.
Получатель
Bytes
Ограничения параметров
Bytes.length and ByteBuffer.length are read-only int properties that report the number of bytes.
JSONValue.length is an Option<int> property. Arrays and objects return Some(count) for their element or member count. Other JSON kinds return None().
JSONValue.keys and JSONValue.values are properties returning Option<Array<string>> and Option<Array<JSON. Objects return Some(keys) or Some(values). Other JSON kinds return None().
Read these properties without parentheses, as with Array.length, Map.length, Map.keys, Map.values, and Set.length. Calling a property value is rejected as a non-callable value.
Связанное правило · Read collection sizes, keys, and values as properties →Test whether a Bytes, Map, or Set value is empty by comparing its length property with zero. The comparison is true exactly when the collection has no bytes, entries, or elements.
Bytes, Map, and Set do not expose an isEmpty member. Read the length property and use the ordinary equality operator.
Связанное правило · Test collection emptiness with length →A Bytes value is an immutable ordered sequence of octets. Each octet is an int from 0 through 255.
Bytes.empty returns the empty sequence. Bytes.fromArray accepts an Array<int> and returns an independent snapshot in Ok.
Bytes.fromArray returns Err with a string identifying the first element outside 0 through 255. It does not wrap, clamp, or return a partial sequence.
Bytes.toArray returns a new Array<int> in byte order. Mutating that array or the original input array does not change an existing Bytes value.
Bytes.concat returns the receiver bytes followed by the argument bytes. Either input may be empty and both inputs retain their contents.
Bytes.get uses a zero-based byte index. It returns Some(byte) within the sequence and None() for every negative or past-end index.
Bytes.length is the number of bytes and is read as a property. Compare it with zero to test emptiness.
Receivers and supplied arguments evaluate once from left to right before the operation begins. These operations perform no I/O or text normalization.
A correctly typed lookup or concatenation has no data-dependent Result failure. Allocation exhaustion is an operational failure and is not a decoded data error.
Связанное правило · Construct and inspect immutable byte sequences →Результат
The declared result type is int.
Эффекты
Ошибки
Result and effects
СсылкаSelect this field from a value of its named type without call parentheses.
Read the number of bytes as a read-only int property. Compare it with zero to test emptiness.
Why
СсылкаCollection observations use the same property syntax as Array, Map, and Set. Parentheses identify calls rather than stored or derived values.
Related entries
СсылкаRead collection sizes, keys, and values as properties
СсылкаRead collection sizes, keys, and values as properties
Bytes.length and ByteBuffer.length are read-only int properties that report the number of bytes.
JSONValue.length is an Option<int> property. Arrays and objects return Some(count) for their element or member count. Other JSON kinds return None().
JSONValue.keys and JSONValue.values are properties returning Option<Array<string>> and Option<Array<JSON. Objects return Some(keys) or Some(values). Other JSON kinds return None().
Read these properties without parentheses, as with Array.length, Map.length, Map.keys, Map.values, and Set.length. Calling a property value is rejected as a non-callable value.
Причина
The same collection observation should use the same syntax across core collections and library values. Keeping JSONValue results optional preserves its distinction between collections and scalar values.
Read the same properties on core collections
Ссылкаimport std.iolet array = [2, 3]let entries = map { "name": "Topaz" }let values = set { 2, 3 }io.writeLine("{array.length}:{entries.length}:{values.length}")io.writeLine(entries.keys[0])io.writeLine(entries.values[0])
2:1:2
name
Topaz
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
2:1:2nameTopaz
Read a byte sequence size
Ссылкаimport std.bytes { Bytes }import std.iolet bytes = Bytes.empty()let size: int = bytes.lengthio.writeLine("{size}")
0
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
0
Read a byte buffer size
Ссылкаimport std.bytes { ByteBuffer }import std.iolet buffer = ByteBuffer.allocate(3)let size: int = buffer.lengthio.writeLine("{size}")
3
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
3
Read JSON sizes and preserve optional results
Ссылкаimport std.jsonimport std.testimport std.iolet array = test.assertOk(json.parse("[1,2]"))let object = test.assertOk(json.parse("\{\"name\":\"Topaz\"\}"))let scalar = test.assertOk(json.parse("42"))let arraySize: Option<int> = array.lengthlet objectSize: Option<int> = object.lengthlet scalarSize: Option<int> = scalar.lengthtest.assertEq(test.assertSome(arraySize), 2)test.assertEq(test.assertSome(objectSize), 1)test.assertNone(scalarSize)io.writeLine("JSON sizes read")
JSON sizes read
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
JSON sizes read
Read JSON object keys
Ссылкаimport std.jsonimport std.testimport std.iolet object = test.assertOk(json.parse("\{\"name\":\"Topaz\"\}"))let array = test.assertOk(json.parse("[]"))let scalar = test.assertOk(json.parse("42"))let names: Option<Array<string>> = object.keystest.assertEq(test.assertSome(names)[0], "name")test.assertNone(array.keys)test.assertNone(scalar.keys)io.writeLine("JSON keys read")
JSON keys read
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
JSON keys read
Read JSON object values
Ссылкаimport std.jsonimport std.testimport std.iolet object = test.assertOk(json.parse("\{\"name\":\"Topaz\"\}"))let array = test.assertOk(json.parse("[]"))let scalar = test.assertOk(json.parse("42"))let values = test.assertSome(object.values)test.assertEq(test.assertSome(values[0].asString()), "Topaz")test.assertNone(array.values)test.assertNone(scalar.values)io.writeLine("JSON values read")
JSON values read
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
JSON values read
Reject calling Bytes.length
Ссылкаimport std.bytes { Bytes }function inspect(value: Bytes) -> () {let result = value.length()return ()}
Нет стандартного вывода.Ожидаемый результат
Ожидаемый результат
Этап отклонения check. Ненулевой код завершения.
stdlib-property-not-callable at
main.tpz:3:22
Reject calling ByteBuffer.length
Ссылкаimport std.bytes { ByteBuffer }function inspect(value: ByteBuffer) -> () {let result = value.length()return ()}
Нет стандартного вывода.Ожидаемый результат
Ожидаемый результат
Этап отклонения check. Ненулевой код завершения.
stdlib-property-not-callable at
main.tpz:3:22
Reject calling JSONValue.length
Ссылкаimport std.json { JSONValue }function inspect(value: JSONValue) -> () {let result = value.length()return ()}
Нет стандартного вывода.Ожидаемый результат
Ожидаемый результат
Этап отклонения check. Ненулевой код завершения.
stdlib-property-not-callable at
main.tpz:3:22
Reject calling JSONValue.keys
Ссылкаimport std.json { JSONValue }function inspect(value: JSONValue) -> () {let result = value.keys()return ()}
Нет стандартного вывода.Ожидаемый результат
Ожидаемый результат
Этап отклонения check. Ненулевой код завершения.
stdlib-property-not-callable at
main.tpz:3:22
Reject calling JSONValue.values
Ссылкаimport std.json { JSONValue }function inspect(value: JSONValue) -> () {let result = value.values()return ()}
Нет стандартного вывода.Ожидаемый результат
Ожидаемый результат
Этап отклонения check. Ненулевой код завершения.
stdlib-property-not-callable at
main.tpz:3:22
Diagnostics
СсылкаTest collection emptiness with length
СсылкаTest collection emptiness with length
Test whether a Bytes, Map, or Set value is empty by comparing its length property with zero. The comparison is true exactly when the collection has no bytes, entries, or elements.
Bytes, Map, and Set do not expose an isEmpty member. Read the length property and use the ordinary equality operator.
Причина
A collection already exposes its count through length. Comparing that value with zero expresses emptiness for every collection without another query name or a type-specific method.
Test empty and nonempty maps with length
Ссылкаimport std.iolet empty: Map<string, int> = map {}let filled = map { "one": 1 }io.writeLine("{empty.length == 0}:{filled.length == 0}")
true:false
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
true:false
Test empty and nonempty sets with length
Ссылкаimport std.iolet empty: Set<int> = set {}let filled = set { 1 }io.writeLine("{empty.length == 0}:{filled.length == 0}")
true:false
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
true:false
Test empty and nonempty byte sequences with length
Ссылкаimport std.bytes { Bytes }import std.testimport std.iolet empty = Bytes.empty()let filled = test.assertOk(Bytes.fromArray([1]))io.writeLine("{empty.length == 0}:{filled.length == 0}")
true:false
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
true:false
Reject Bytes.isEmpty
Ссылкаimport std.bytes { Bytes }function inspect(value: Bytes) -> () {let result = value.isEmpty()return ()}
Нет стандартного вывода.Ожидаемый результат
Ожидаемый результат
Этап отклонения check. Ненулевой код завершения.
stdlib-removed-member at
main.tpz:3:22
Reject Map.isEmpty
Ссылкаfunction inspect(value: Map<string, int>) -> () {let result = value.isEmpty()return ()}
Нет стандартного вывода.Ожидаемый результат
Ожидаемый результат
Этап отклонения check. Ненулевой код завершения.
stdlib-removed-member at
main.tpz:2:22
Reject Set.isEmpty
Ссылкаfunction inspect(value: Set<int>) -> () {let result = value.isEmpty()return ()}
Нет стандартного вывода.Ожидаемый результат
Ожидаемый результат
Этап отклонения check. Ненулевой код завершения.
stdlib-removed-member at
main.tpz:2:22
Diagnostics
СсылкаConstruct and inspect immutable byte sequences
СсылкаConstruct and inspect immutable byte sequences
A Bytes value is an immutable ordered sequence of octets. Each octet is an int from 0 through 255.
Bytes.empty returns the empty sequence. Bytes.fromArray accepts an Array<int> and returns an independent snapshot in Ok.
Bytes.fromArray returns Err with a string identifying the first element outside 0 through 255. It does not wrap, clamp, or return a partial sequence.
Bytes.toArray returns a new Array<int> in byte order. Mutating that array or the original input array does not change an existing Bytes value.
Bytes.concat returns the receiver bytes followed by the argument bytes. Either input may be empty and both inputs retain their contents.
Bytes.get uses a zero-based byte index. It returns Some(byte) within the sequence and None() for every negative or past-end index.
Bytes.length is the number of bytes and is read as a property. Compare it with zero to test emptiness.
Receivers and supplied arguments evaluate once from left to right before the operation begins. These operations perform no I/O or text normalization.
A correctly typed lookup or concatenation has no data-dependent Result failure. Allocation exhaustion is an operational failure and is not a decoded data error.
Причина
Exact octets keep binary payloads independent of text encoding. Snapshot conversion prevents later array edits from silently changing a payload.
Preserve empty values and byte order
Ссылкаimport std.bytes { Bytes }import std.ioimport std.testlet empty = test.assertOk(Bytes.fromArray([]))let value = test.assertOk(Bytes.fromArray([0, 128, 255]))io.writeLine(Bytes.empty().toHex())io.writeLine(empty.concat(value).toHex())io.writeLine(value.concat(test.assertOk(Bytes.fromArray([1]))).toHex())
0080ff
0080ff01
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
0080ff0080ff01
Reject out-of-range array elements
Ссылкаimport std.bytes { Bytes }import std.iofor values in ([[0, -1, 255], [0, 256, 255]]) {match (Bytes.fromArray(values)) {case Err(_) => io.writeLine("invalid byte")case Ok(_) => io.writeLine("accepted")}}
invalid byte
invalid byte
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
invalid byteinvalid byte
Read optional bytes at both boundaries
Ссылкаimport std.bytes { Bytes }import std.ioimport std.testlet value = test.assertOk(Bytes.fromArray([0, 128, 255]))for index in ([-1, 0, 2, 3]) {match (value.get(index)) {case Some(byte) => io.writeLine("{byte}")case None() => io.writeLine("absent")}}
absent
0
255
absent
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
absent0255absent
Keep array edits independent from bytes
Ссылкаimport std.bytes { Bytes }import std.ioimport std.testlet mut input = [0, 255]let value = test.assertOk(Bytes.fromArray(input))let mut output = value.toArray()input[0] = 7output[1] = 8io.writeLine(value.toHex())io.writeLine("{input[0]},{output[1]}")
00ff
7,8
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
00ff7,8
Evaluate the receiver before its argument
Ссылкаimport std.bytes { Bytes }import std.iofunction receiver() -> Bytes {io.writeLine("receiver")return "a".encodeUtf8()}function argument() -> Bytes {io.writeLine("argument")return "b".encodeUtf8()}io.writeLine(receiver().concat(argument()).toHex())
receiver
argument
6162
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
receiverargument6162