diff --git a/Changelog.md b/Changelog.md index 2f2a944d..ba354704 100644 --- a/Changelog.md +++ b/Changelog.md @@ -1,5 +1,6 @@ ## Next +* Add `at` and `get` to `Blob` (#424). * Optimized `sort` and `sortInPlace` for `VarArray`, `List`, `Array` (#422). * Simplify `isSorted` logic (#421). * Add `isSorted` to `Array` and `VarArray` (#414). @@ -96,4 +97,4 @@ ## 0.1.0 -* Initial release \ No newline at end of file +* Initial release diff --git a/src/Blob.mo b/src/Blob.mo index e9318e72..2ccc1ae2 100644 --- a/src/Blob.mo +++ b/src/Blob.mo @@ -1,6 +1,6 @@ /// Module for working with Blobs (immutable sequences of bytes). /// -/// Blobs represent sequences of bytes. They are immutable, iterable, but not indexable and can be empty. +/// Blobs represent sequences of bytes. They are immutable, iterable, indexable and can be empty. /// /// Byte sequences are also often represented as `[Nat8]`, i.e. an array of bytes, but this representation is currently much less compact than `Blob`, taking 4 physical bytes to represent each logical byte in the sequence. /// If you would like to manipulate Blobs, it is recommended that you convert @@ -69,6 +69,33 @@ module { /// ``` public func size(blob : Blob) : Nat = blob.size(); + /// Returns the byte at index `index` as an option. + /// Returns `null` when `index >= size`. Indexing is zero-based. + /// + /// Example: + /// ```motoko include=import + /// let blob : Blob = "abcdefgh\08"; + /// assert Blob.get(blob, 8) == ?8; + /// assert Blob.get(blob, 10) == null; + /// ``` + /// + /// Runtime: `O(1)` + /// + /// Space: `O(1)` + public func get(blob : Blob, index : Nat) : ?Nat8 = if (index < blob.size()) ?(blob.get index) else null; + + /// Returns the byte at index `index`. Indexing is zero-based. + /// Traps if `index >= size`, error message may not be descriptive. + /// + /// Example: + /// ```motoko include=import + /// let blob : Blob = "abcdefgh\08"; + /// assert Blob.at(blob, 8) == 8; + /// ``` + /// + /// Runtime: `O(1)` + public func at(blob : Blob, index : Nat) : Nat8 = blob.get index; + /// Creates a `Blob` from an array of bytes (`[Nat8]`), by copying each element. /// /// Example: diff --git a/validation/api/api.lock.json b/validation/api/api.lock.json index 737b5753..69474554 100644 --- a/validation/api/api.lock.json +++ b/validation/api/api.lock.json @@ -49,12 +49,14 @@ { "name": "Blob", "exports": [ + "public func at(blob : Blob, index : Nat) : Nat8", "public type Blob", "public func compare(b1 : Blob, b2 : Blob) : Order.Order", "public func empty() : Blob", "public func equal(blob1 : Blob, blob2 : Blob) : Bool", "public func fromArray(bytes : [Nat8]) : Blob", "public func fromVarArray(bytes : [var Nat8]) : Blob", + "public func get(blob : Blob, index : Nat) : ?Nat8", "public func greater(blob1 : Blob, blob2 : Blob) : Bool", "public func greaterOrEqual(blob1 : Blob, blob2 : Blob) : Bool", "public func hash(blob : Blob) : Types.Hash",