仓颉标准库 std.core 核心接口全解析:从 Any 到 Resource 的接口体系与实战用法

原创2026-10-14 18:26:431,946 阅读
文章标签:编程语言语言运行时标准库内存管理并发编程OpenHarmony

仓颉标准库 std.core 核心接口全解析:从 Any 到 Resource 的接口体系与实战用法

导读

std.core 是仓颉(Cangjie)标准库中最基础的软件包,内置类型、常用函数、集合、哈希与比较等能力均围绕一组核心接口展开。本文基于仓库 core_package_interfaces.md 文档,逐一定义并讲解 Any、CType、Collection、Comparable、Countable、Hashable、Hasher、Iterable、Resource、ThreadContext、ToString 等 18 个核心接口的签名、语义、默认实现与源码佐证,并附上可直接运行的验证示例,帮助读者在自研类型或业务代码中正确实现、组合这些接口。std.core 包无需显式导入(core_package_overview.md),因此本文所有示例都可以直接编译运行。


一、接口体系总览

根据 core_package_overview.md,std.core 包对外提供如下 18 个核心接口:

接口 一句话定位 核心成员
Any 所有类型的父类型 无
CType C 语言互操作能力标记 无
Collection<T> 集合抽象(继承 Iterable<T>) size、isEmpty()、toArray()
Comparable<T> 组合式大小比较 compare、<、<=、==、>、>=
Countable<T> 可计数类型 next(Int64)、position()
Equal<T> 相等比较 ==
NotEqual<T> 不等比较 !=
Equatable<T> 相等 + 不等组合 !=(默认实现)
Less<T> 小于比较 <
Greater<T> 大于比较 >
LessOrEqual<T> 小于等于比较 <=
GreaterOrEqual<T> 大于等于比较 >=
Hashable 计算哈希值 hashCode()
Hasher 组合哈希运算 write(...) 系列、finish()、reset()
Iterable<E> 可迭代(for-in 目标) iterator()
Resource 资源管理(配合 try-with-resource) close()、isClosed()
ToString 字符串表示 toString()
ThreadContext 线程上下文(spawn 可选参数) end()、hasEnded()

这些接口在源码中分散定义于 stdlib/libs/std/core 目录,例如 comparable.cj、equatable.cj、hashable.cj、collection.cj、iterator.cj、countable.cj、resource.cj、to_string.cj、object.cj、c_type.cj、future.cj 等,下文将按职责分组逐一展开。


二、类型体系根基:Any 与 CType

2.1 interface Any:一切类型的父类型

public interface Any

Any 是所有类型的父类型:所有 interface 类型隐式继承它,所有非 interface 类型隐式实现它。在源码层面,object.cj 中 Object 类即通过 public open class Object <: Any 显式声明继承:

public interface Any {}

public open class Object <: Any {
    public const init() {}
}

由于 Any 是所有类型的公共上界,它常被用于需要“接受任意类型”的泛型边界或容器设计中。需要注意,Any 是空接口,本身不提供任何成员,具体能力仍由各类型自身或其实现的接口提供。

2.2 extend Byte:ASCII 字符区间判断与大小写转换

文档中与 Any 同章节出现的还有 extend Byte。Byte 在 type_alias.cj 中被定义为内建类型 UInt8 的别名:

public type Byte = UInt8

Byte 的扩展方法集中定义在 byte_extension.cj,其语义与文档完全一致:

方法 判定/转换范围 源码实现要点(byte_extension.cj)
isAscii() 0x00 ~ 0x7F this <= 0x7F
isAsciiControl() [00, 1F] ∪ {7F} `this <= 0x1F
isAsciiGraphic() [21, 7E] this >= b'!' && this <= b'~'
isAsciiHex() 0-9、a-f、A-F `isAsciiNumber()
isAsciiLetter() A-Z、a-z 大写与小写字母两个区间并集
isAsciiLowerCase() a-z this >= b'a' && this <= b'z'
isAsciiUpperCase() A-Z this >= b'A' && this <= b'Z'
isAsciiNumber() 0-9 this >= b'0' && this <= b'9'
isAsciiNumberOrLetter() 数字或字母 `isAsciiLetter()
isAsciiOct() 0-7 this >= b'0' && this <= b'7'
isAsciiPunctuation() [21,2F]∪[3A,40]∪[5B,60]∪[7B,7E] 四个区间并集
isAsciiWhiteSpace() [09,0D] ∪ {20} `(this >= 0x09 && this <= 0x0D)
toAsciiLowerCase() 大写转小写 this + ASCII_UPPER_TO_LOWER_DIFF(0x20),不可转换时原值返回
toAsciiUpperCase() 小写转大写 this - ASCII_UPPER_TO_LOWER_DIFF,不可转换时原值返回

其中大小写转换通过常量 ASCII_UPPER_TO_LOWER_DIFF: UInt8 = 0x20(byte_extension.cj)实现——这正是 ASCII 码表中大写字母与小写字母之间的固定差值。

验证示例(文档原例,可直接运行):

main() {
    // 区间判定
    let byte1: Byte = 65  // 'A'
    let byte2: Byte = 200 // 超出 ASCII 范围
    println("Is byte1 (${byte1}) within ASCII range: ${byte1.isAscii()}")
    println("Is byte2 (${byte2}) within ASCII range: ${byte2.isAscii()}")

    // 控制字符判定:[00,1F] ∪ {7F}
    let c1: Byte = 0x09  // Tab
    let c2: Byte = 0x20  // 空格
    let c3: Byte = 0x7F  // DEL
    println("Is byte1 (0x${c1}) an ASCII control character: ${c1.isAsciiControl()}")
    println("Is byte2 (0x${c2}) an ASCII control character: ${c2.isAsciiControl()}")
    println("Is byte3 (0x${c3}) an ASCII control character: ${c3.isAsciiControl()}")

    // 大小写转换(不可转换时保持原值)
    let lower = byte1.toAsciiLowerCase()
    let upper = 0x61.toAsciiUpperCase() // 'a'
    println("byte1 (0x${byte1}) converted to lowercase: 0x${lower}")
    println("0x61 converted to uppercase: 0x${upper}")
}

2.3 interface CType:C 语言互操作能力标记

sealed interface CType

CType 是语言内建的空接口,是所有可与 C 语言互操作类型的隐式实现者。源码 c_type.cj 的注释明确了隐式实现范围:

All types which can be used in C FFI implicitly implement the interface, including Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64, IntNative, UIntNative, Float32, Float64, Bool, Unit, and all @C-modified structs.

即所有内建标量类型(整数、浮点、Bool、Unit)以及所有带 @C 修饰的 struct 都隐式实现 CType。文档强调三点使用限制:

  • CType 是接口类型,本身不满足 CType 约束(不能拿接口去当 T <: CType 的具体类型);
  • 用户不能继承或扩展 CType(sealed 密封接口);
  • CType 不绕过子类型使用限制。

文档示例演示了哪些值可以被赋给 CType 类型变量:

@C
struct Data {}

@C
func foo() {}

main() {
    var c: CType = Data()            // ok:@C struct
    c = 0                            // ok:整数字面量
    c = true                         // ok:Bool
    c = CString(CPointer<UInt8>())   // ok:C 字符串
    c = CPointer<Int8>()             // ok:C 指针
    c = foo                          // ok:@C 函数引用
}

CType 是标准库众多互操作 API 的泛型边界,例如 sizeOf<T>()、alignOf<T>()、acquireArrayRawData<T>() 等函数均要求 T <: CType(见 core_package_funcs.md)。


三、比较体系:Equal / NotEqual / Equatable / Less / Greater / LessOrEqual / GreaterOrEqual / Comparable

std.core 的比较接口是一组精心设计的“原子接口 + 组合接口”体系,源码集中在 equatable.cj 与 comparable.cj。

3.1 原子接口:Equal、NotEqual、Less、Greater、LessOrEqual、GreaterOrEqual

六个原子接口各声明一个运算符重载:

public interface Equal<T> { operator func ==(rhs: T): Bool }
public interface NotEqual<T> { operator func !=(rhs: T): Bool }
public interface Less<T> { operator func <(rhs: T): Bool }
public interface Greater<T> { operator func >(rhs: T): Bool }
public interface LessOrEqual<T> { operator func <=(rhs: T): Bool }
public interface GreaterOrEqual<T> { operator func >=(rhs: T): Bool }

它们将六种比较运算拆成独立接口,使类型可以只实现自己需要的能力,避免强制实现全部运算符。

3.2 组合接口 Equatable

public interface Equatable<T> <: Equal<T> & NotEqual<T> {
    operator func !=(rhs: T): Bool
}

Equatable 组合了 Equal 与 NotEqual,并为 != 提供默认实现(源码 equatable.cj):

operator func !=(other: T): Bool {
    !(this == other)
}

即 a != b 恒等于 !(a == b),实现类只需给出 == 即可。文档列出已为以下类型实现 Equatable:Unit、Bool、Rune、Int64/Int32/Int16/Int8、UIntNative/UInt64/UInt32/UInt16/UInt8、Float64/Float32/Float16、String、Array、Box、ArrayList、HashSet 等。源码中可见基础类型通过 extend Bool <: Equatable<Bool> {} 之类的空扩展声明接入(equatable.cj),而容器类型如 ArrayList 则实现在 collection_package_class.md 对应的集合库中。

3.3 组合接口 Comparable:一站式大小比较

public interface Comparable<T> <: Equatable<T> & Less<T> & Greater<T> & LessOrEqual<T> & GreaterOrEqual<T> {
    func compare(that: T): Ordering
    operator func <(rhs: T): Bool
    operator func <=(rhs: T): Bool
    operator func ==(rhs: T): Bool
    operator func >(rhs: T): Bool
    operator func >=(rhs: T): Bool
}

Comparable 是六个原子比较接口的合体,核心是抽象方法 compare(that: T): Ordering,其余 5 个运算符均由默认实现基于 compare 的结果推导。源码 comparable.cj 给出了精确语义:

  • a.compare(b) 返回 Ordering.LT(小于)、Ordering.EQ(等于)或 Ordering.GT(大于);
  • ==:compare 返回 EQ 时为 true,否则 false;
  • <:返回 LT 时为 true;
  • >:返回 GT 时为 true;
  • <=:返回 LT | EQ 时为 true;
  • >=:返回 GT | EQ 时为 true。

Ordering 枚举定义于同一文件(comparable.cj),值为 LT | GT | EQ,且自身实现了 Comparable<Ordering>(关系为 LT < EQ < GT)与 ToString。所有内建数值类型(IntNative、Int64~Int8、UIntNative、UInt64~UInt8、Float16/Float32/Float64)均已通过 extend ... <: Comparable<...> 实现,其中 compare 采用 match 分支实现,而运算符则直接映射到 @Intrinsic 声明的内建比较函数(如 Int64Less、Float64GreaterOrEqual 等,见 comparable.cj)。

自定义类型实现 Comparable 的标准姿势:只需实现 compare 返回 Ordering,即可免费获得全部 6 个比较运算符。配合标准库的泛型函数 max<T> / min<T>(要求 T <: Comparable<T>,源码见 comparable.cj)即可直接参与求最值。示例:

struct Point <: Comparable<Point> {
    let x: Int64
    let y: Int64

    public func compare(that: Point): Ordering {
        if (this.x != that.x) {
            return if (this.x < that.x) { Ordering.LT } else { Ordering.GT }
        }
        if (this.y != that.y) {
            return if (this.y < that.y) { Ordering.LT } else { Ordering.GT }
        }
        return Ordering.EQ
    }
}

main() {
    let a = Point(1, 2)
    let b = Point(2, 1)
    println("a < b: ${a < b}")   // 自动基于 compare 推导
    println("max is: ${max(a, b).x}") // 泛型 max 直接可用
}

四、集合与迭代体系:Collection / Iterable

4.1 interface Collection

public interface Collection<T> <: Iterable<T> {
    prop size: Int64
    func isEmpty(): Bool
    func toArray(): Array<T>
}

Collection 是集合层级中的根接口,表示一组元素(允许重复与否、是否有序由具体实现决定)。源码 collection.cj 中 toArray() 甚至提供了默认实现 Array<T>(this),即通过迭代构造数组。成员语义:

  • prop size: Int64:集合元素个数;
  • func isEmpty(): Bool:是否为空;
  • func toArray(): Array<T>:转换为 Array<T>。

容器类型一般都应实现此接口(如 ArrayList、HashSet、HashMap 等,见 collection_package_interface.md)。

4.2 interface Iterable:for-in 循环的基础

public interface Iterable<E> {
    func iterator(): Iterator<E>
}

实现 Iterable 的类型(通常是容器类型)可以在 for-in 语句中被迭代,或通过 iterator() 获取迭代器后手动调用 next() 迭代。文档指出 Array、ArrayList、HashMap 等基础容器已实现本接口;用户可为自定义类型实现它以获得迭代能力。

源码 iterator.cj 同时给出了 Iterator<T> 抽象类的定义:public func next(): Option<T> 每次返回一个元素或 None,且 Iterator<T> 自身也实现 Iterable<T>。同文件还提供了丰富的惰性迭代器工具类(FilterIterator、MapIterator、StepIterator、SkipIterator、TakeIterator、ZipIterator、EnumerateIterator、ConcatIterator、FlatMapIterator 等)以及 Iterator<T> 的扩展方法(filter、map、zip、enumerate、skip、take、step、reduce、fold、all、any、count、forEach 等),这些能力虽然不是接口本身,但与 Iterable 紧密配套,是容器迭代编程的利器。

自定义可迭代类型示例:

// 一个简单的 1..n 迭代器
class CountDown <: Iterable<Int64> {
    let n: Int64
    init(n: Int64) { this.n = n }

    public func iterator(): Iterator<Int64> {
        return CountDownIterator(n)
    }
}

class CountDownIterator <: Iterator<Int64> {
    var cur: Int64
    init(n: Int64) { this.cur = n }

    public func next(): Option<Int64> {
        if (cur > 0) {
            let v = cur
            cur--
            return Some(v)
        }
        return None
    }
}

main() {
    for (x in CountDown(3)) {
        println(x) // 3 2 1
    }
}

五、计数与范围:Countable

public interface Countable<T> {
    func next(right: Int64): T
    func position(): Int64
}

Countable 表示类型“可计数”:每个实例对应一个位置值(Int64),通过向右侧移动 right 个位置可得到另一个实例。成员语义:

  • next(right: Int64): T:返回从当前实例向右移动 right 个位置后的 T 实例;
  • position(): Int64:把当前实例转换为位置值 Int64。

源码 countable.cj 定义了接口本身,并已为全部内建整数类型(IntNative、Int64~Int8、UIntNative、UInt64~UInt8)和 Rune 实现。其中无符号类型的 next 对负的 right 做了专门处理(先取绝对值再减法,见 countable.cj),Rune 的 next 则通过 Rune(UInt32(Int64(UInt32(this)) + right)) 实现(countable.cj)。整数实现均标注 @OverflowWrapping,溢出时采用回绕语义。

Countable 是区间类型 Range<T> 的三个约束之一(where T <: Countable<T> & Comparable<T> & Equatable<T>,见 core_package_structs.md),也是 RangeIterator 能够按步长推进的根本保证。文档在该节还附带介绍了 Float64 * Duration 与 Int64 * Duration 两个扩展运算符。

5.1 extend Int64 / Float64 的 Duration 乘法

public operator func *(r: Duration): Duration   // extend Int64
public operator func *(r: Duration): Duration   // extend Float64

两个运算符分别实现 Int64 * Duration 与 Float64 * Duration,返回缩放后的新 Duration;当乘法结果超出 Duration 可表示范围(纳秒精度,约 <a href="https://link.gitcode.com/i/5ea4edf5c8a751d0f1bf4d9d1d5ae170" target="_blank">-2^63, 2^63-1) 秒)时抛出 ArithmeticException。源码位于 [duration.cj,二者都通过 return r * this 委托给 Duration 自身的乘法实现(Duration 内部以 sec: Int64 + ns: UInt32 表示,常量如 Duration.second 定义于 duration.cj)。

文档原例验证:

main() {
    // Float64 * Duration
    let floatVal: Float64 = 2.5
    let result = floatVal * Duration.second
    println("Operation result: ${result}")       // 2s500ms

    // Int64 * Duration
    let intVal: Int64 = 3
    println("Operation result: ${intVal * Duration.second}") // 3s
    println("2 * Duration.second = ${2 * Duration.second}")   // 2s
}

输出:

Operation result: 2s500ms
Operation result: 3s
2 * Duration.second = 2s

六、哈希体系:Hashable 与 Hasher

6.1 interface Hashable

public interface Hashable {
    func hashCode(): Int64
}

Hashable 用于计算实例的哈希值,是哈希表(如 HashMap、HashSet)对键类型的基本要求。文档列出的已实现类型包括:Bool、Rune、IntNative、Int64~Int8、UIntNative、UInt64~UInt8、Float64/Float32/Float16、String、Box 等。

源码 hashable.cj 展示了各类型 hashCode() 的具体实现,其中几个值得注意的细节:

  • 整数类型直接返回自身或转为 Int64(如 Int64.hashCode() 返回 this,见 hashable.cj);
  • 浮点类型的哈希基于 wyhash 算法族:Float64.hashCode() 通过 CJ_CORE_Float64ToHash 结合 wyrand(i) 生成(hashable.cj),wyrand 是文档注释所称“快速伪随机函数,可消除劣质哈希带来的性能损失”(hashable.cj);
  • Ordering、Unit、Bool、Rune 等也有明确定义的哈希值(如 Bool:true 为 1、false 为 0)。

6.2 interface Hasher:组合哈希

public interface Hasher {
    func finish(): Int64
    mut func reset(): Unit
    mut func write(value: Bool): Unit
    mut func write(value: Rune): Unit
    mut func write(value: Int8): Unit
    mut func write(value: Int16): Unit
    mut func write(value: Int32): Unit
    mut func write(value: Int64): Unit
    mut func write(value: UInt8): Unit
    mut func write(value: UInt16): Unit
    mut func write(value: UInt32): Unit
    mut func write(value: UInt64): Unit
    mut func write(value: Float16): Unit
    mut func write(value: Float32): Unit
    mut func write(value: Float64): Unit
    mut func write(value: String): Unit
}

Hasher 用于处理组合哈希:通过一系列 write 函数把多个不同类型实例“喂”进哈希器,最后用 finish() 得到组合后的哈希值,reset() 将内部状态重置为 0。标准库提供了默认实现 DefaultHasher(定义于 core_package_structs.md),其核心是 hashCombine 函数——源引自 C++ boost 的经典组合公式 seed ^= hasher(v) + 0x9e3779b9 + (seed<<6) + (seed>>2)(hashable.cj)。

典型使用场景:为包含多个字段的自定义类型实现 Hashable。例如源码中 Range<T> 的哈希实现(hashable.cj)即组合了 start、end、step、isClosed 四个字段的哈希:

public func hashCode(): Int64 {
    var dfh: DefaultHasher = DefaultHasher()
    dfh.write(start.hashCode())
    dfh.write(end.hashCode())
    dfh.write(step.hashCode())
    dfh.write(isClosed.hashCode())
    return dfh.finish()
}

对自定义复合类型,可以照此模式实现:

struct User <: Hashable {
    let name: String
    let age: Int64

    public func hashCode(): Int64 {
        var h: DefaultHasher = DefaultHasher()
        h.write(name)
        h.write(age)
        return h.finish()
    }
}

七、资源管理:Resource

public interface Resource {
    func close(): Unit
    func isClosed(): Bool
}

Resource 用于资源管理,典型用于关闭并释放内存、句柄等资源。实现该接口的类型可以在 try-with-resource 语法上下文中实现资源的自动释放,其中:

  • close():关闭资源;
  • isClosed():查询资源是否已关闭。

源码定义于 resource.cj。标准库中 CPointerResource<T>、CStringResource(见 core_package_structs.md 与 struct-cstringresource)即为 Resource 的典型实现——它们把 CPointer / CString 包装成可自动释放的资源,可通过 asResource() 获取,用于管理 C 互操作内存。

使用模式示例:

// 伪代码示意:try-with-resource 自动调用 close()
class FileHandle <: Resource {
    public func close(): Unit { /* 释放句柄 */ }
    public func isClosed(): Bool { /* 返回关闭状态 */ }
}

main() {
    // try (fh <- FileHandle()) { ... }  // 语法示意,作用域结束时自动 close()
    println("Resource interface is ready for try-with-resource.")
}

八、线程上下文:ThreadContext

public interface ThreadContext {
    func end(): Unit
    func hasEnded(): Bool
}

ThreadContext 是仓颉的线程上下文接口。创建 thread 时,除默认的 spawn 表达式参数外,还可以传入不同类型 ThreadContext 的实例来选择不同的线程上下文,从而在一定程度上控制并发行为。成员语义:

  • end():终止方法,向当前上下文发送终止请求;
  • hasEnded():查询当前上下文是否已终止。

文档明确两点:用户不允许自行实现 ThreadContext;语言按使用场景提供了 MainThreadContext(具体定义在终端框架库中)。源码位于 future.cj,注释同样说明它是 spawn 表达式的可选参数类型,且“目前仅有 MainThreadContext”。

结合 core_package_classes.md 中 Thread 类(用于获取线程 ID 与名称、检查取消请求、注册未处理异常处理器等)与 Future<T>(获取线程计算结果、发送取消信号),可以构建完整的仓颉线程并发编程模型:

import std.sync.*

main() {
    // spawn 表达式默认线程上下文即可满足大多数场景
    let future = spawn { 1 + 2 }
    println("result: ${future.get()}")  // 3
}

九、字符串表示:ToString

public interface ToString {
    func toString(): String
}

ToString 为具体类型提供字符串表示,其成员 toString(): String 返回实例的字符串表示。源码 to_string.cj 定义了接口,并为所有内建类型提供了实现:

  • 整数类型:Int64 自行实现进制转换(负数加 '-' 前缀),其余整型委托给 Int64/UInt64(to_string.cj);
  • 浮点类型:Float64 通过 CJ_CORE_Float64ToCPointer 获取 C 字符串再转换,Float32/Float16 转为 Float64 后复用(to_string.cj);
  • Bool 返回 "true" / "false",Rune 返回单字符字符串,Unit 返回 "()"(to_string.cj)。

ToString 是标准库输出体系(print、println、eprint、eprintln 的泛型重载均要求 T <: ToString,见 core_package_funcs.md)以及字符串插值 "${expr}" 的基础。自定义类型实现 toString() 后即可直接参与 println 与插值输出。


十、接口组合实战:设计一个同时满足哈希、比较、迭代、字符串化的自定义类型

综合以上接口,设计一个同时实现 Comparable、Hashable、ToString、Iterable 的自定义类型(PointList 场景),展示接口组合的完整姿势:

struct Point <: Comparable<Point> & Hashable & ToString {
    let x: Int64
    let y: Int64

    // Comparable:只实现 compare,其余运算符自动推导
    public func compare(that: Point): Ordering {
        if (this.x != that.x) {
            return if (this.x < that.x) { Ordering.LT } else { Ordering.GT }
        }
        return if (this.y < that.y) { Ordering.LT }
               else if (this.y > that.y) { Ordering.GT }
               else { Ordering.EQ }
    }

    // Hashable:组合哈希
    public func hashCode(): Int64 {
        var h: DefaultHasher = DefaultHasher()
        h.write(x)
        h.write(y)
        return h.finish()
    }

    // ToString
    public func toString(): String {
        return "Point(${x}, ${y})"
    }
}

main() {
    let p1 = Point(1, 2)
    let p2 = Point(2, 1)
    println("${p1} == ${p2} ? ${p1 == p2}")  // Point(1, 2) == Point(2, 1) ? false
    println("${p1} < ${p2} ? ${p1 < p2}")    // 自动基于 compare
    println("hash: ${p1.hashCode()}")
    println("max: ${max(p1, p2)}")            // Comparable + 泛型 max
}

要点总结:

  1. 接口语义要匹配:需要全套比较就用 Comparable,只需要相等判断就用 Equatable(或更原子的 Equal),避免过度实现;
  2. 默认实现要善用:Comparable 的 5 个运算符、Equatable 的 !=、Collection 的 toArray() 都有默认实现,自定义类型只需实现最核心的抽象方法;
  3. 组合哈希用 Hasher:多字段哈希一律通过 DefaultHasher + write 组合,避免手写劣质哈希;
  4. C 互操作边界用 CType:泛型约束 T <: CType 是 FFI 类型安全的保障;
  5. 资源必须可关闭:凡涉及句柄、内存、文件等资源,实现 Resource 以便 try-with-resource 自动释放。

十一、进一步阅读

登录后查看全文
cangjie_runtime