库 Cone 一览
Scoop 工具链附带一组预编译的库 Cone,覆盖从集合、文本、TLS、HTTP/2 与终端交互到 2D 绘图和桌面 UI 的常见需求。它们都是普通的 Scoop Cone:源码随安装包发布在工具链根目录的 src/ 下(用 scoop-install show 查看 Root),每个库都有可运行的 examples/,完整 API 见 API 文档。
使用内置库
内置库的 group 都是 scoop,当前版本为 0.1.0。scoop.core 总是可用;单文件程序还默认依赖 scoop.std。其他库需要显式声明:
[dependencies]
"scoop:scoop.std" = "=0.1.0"
"scoop:scoop.json" = "=0.1.0"
"scoop:scoop.http.server" = "=0.1.0"manifest Cone 除 core 外没有隐式依赖,使用 scoop.std 也需要像上面这样声明。单文件程序默认依赖 core 与 std,其他库在文件头写 //! dep: scoop:scoop.json:0.1.0。依赖本身不会导入名称,仍需 import 对应的包,见 Cone.toml 与单文件模式。
核心与基础库
| Cone | 内容 |
|---|---|
scoop.core | 语言所需的最小核心:基本类型、String、StringBuilder、Option、数组与 ArrayList、整数与字符区间、迭代、异常、Equals/Hash/ToString/Compare 等运算符接口、协程原语与结构化并发、原子类型、Ptr/FunPtr 等 FFI 类型、编解码协议与 typeInfo。默认导入 prelude。 |
scoop.std | 平台无关的基础库:scoop.collections(List/Map/Set、HashMap、LinkedHashMap、TreeMap、ArrayDeque、PriorityQueue、排序与集合运算)、scoop.text(查找、分割、替换、数值解析与格式化)、scoop.bytes、scoop.io.encoding(Base64、Hex)、scoop.time / scoop.datetime、scoop.random、scoop.uuid。 |
scoop.math | 八种整数的受检算术、Float/Double 数学函数、不可变 BigInteger / BigDecimal,以及值类型 MathContext / RoundingMode。 |
scoop.test | 测试库:@Test 声明、断言、预期异常、前后置钩子,由 scoop test 驱动。 |
import scoop.collections.*
fun main() {
val scores = listOf<Int>(8, 3, 9, 3, 6)
val passing = scores.filter { score -> score >= 6 }.sorted()
println(passing.joinToString(", "))
val counts = LinkedHashMap<String, Int>()
for (word in listOf<String>("red", "blue", "red")) {
counts[word] = (counts[word] ?: 0) + 1
}
for ((word, count) in counts) {
println(f"${word}=${count}")
}
}//! dep: scoop:scoop.math:0.1.0
import scoop.math.*
fun factorial(n: Long): BigInteger {
var result = BigInteger(1L)
for (i in 2L..n) result = result * BigInteger(i)
return result
}
fun main() {
println(f"30! = ${factorial(30L)}")
val price = "19.95".toBigDecimal() * BigDecimal(3L)
println(f"total = ${price}")
println(f"1/3 = ${BigDecimal.ONE.div(BigDecimal(3L), MathContext(10L))}")
}平台与异步 I/O
| Cone | 内容 |
|---|---|
scoop.platform | 同步平台 API:文件系统、目录、临时文件、环境变量、进程与伪终端、线程与并发原语、网络、系统时钟与系统熵、native I/O buffer。系统字符串 OsString 用 WTF-8 无损保存 Windows 的 UTF-16 名称(包括非配对 surrogate),可用 fromUtf16/toUtf16 显式转换。 |
scoop.asyncio | 平台事件循环 PlatformEventLoop:macOS 使用系统 libdispatch,Linux 使用 io_uring/liburing,Windows 使用 IOCP;提供定时器、TCP/UDP、DNS、异步文件与目录、TTY、伪终端子进程(Windows 使用 ConPTY)、SOCKS5,复用 core 的 Job、CoroutineScope、async/launch 与取消协议。事件循环由 eventLoop() 创建,可在配置 lambda 中选择阻塞线程池。 |
scoop.concurrent | 多线程协程执行器与 worker 组、阻塞任务线程池、异步 AsyncMutex 与条件变量、channel;等待时挂起协程而不阻塞执行器线程。 |
//! dep: scoop:scoop.asyncio:0.1.0
import scoop.asyncio.*
import scoop.time.Duration
suspend fun fetch(loop: EventLoop, id: Int, delayMs: Long): String {
loop.sleep(Duration.milliseconds(delayMs))
return f"result #${id}"
}
fun main() {
val loop = eventLoop()
loop.run suspend {
val a = async<String> suspend { fetch(loop, 1, 30L) }
val b = async<String> suspend { fetch(loop, 2, 10L) }
println(a.await())
println(b.await())
}
}PlatformEventLoop.run 是同步、单次使用的根入口,等待根作用域和子任务完成,并关闭本轮遗留资源。Linux 异步后端要求内核 6.1 及实际可用的 io_uring 能力;初始化会探测所需操作,能力不足时报错,不自动切换后端。
已有宿主主循环的程序可使用 PlatformEventLoop.attach,由宿主监听通知并推进任务;macOS 提供 MainDispatchHost。具体生命周期和线程规则见异步 I/O 规范。
网络与安全
| Cone | 内容 |
|---|---|
scoop.http | 内存中的 HTTP 协议库:HTTP/1.x(llhttp)与 HTTP/2(nghttp2)编解码、头部与消息模型、SSE、NDJSON、multipart、AWS EventStream、公共后缀表。不涉及 socket。 |
scoop.http.asyncio | 在任意异步字节流上运行 HTTP 传输,连接与 TLS 由调用者提供。 |
scoop.http.client | 统一的 HTTP/1.x / HTTP/2 客户端:连接池、认证、代理、缓存、下载、SSE 与 WebSocket,类型化 JSON 请求与响应。 |
scoop.http.server | 纯 Scoop 的应用层 HTTP 服务器:显式路由、middleware、JSON、SSE、静态文件与 SPA、优雅关闭;不使用反射或 DI 容器。 |
scoop.tls / scoop.tls.asyncio | 基于 OpenSSL 的同步与异步 TLS:客户端/服务端、证书与信任配置、ALPN。Windows 上的系统信任由 Crypt32 的证书链引擎验证,使用 Windows 的用户与机器信任配置。 |
scoop.crypto | 摘要(SHA-256 等)、增量摘要、HMAC、对称加密、签名、X.509 与 JWS。 |
scoop.url | URI/IRI 解析、相对引用、组件拼装、百分号编码与表单 codec。 |
scoop.idna | 国际化域名(UTS #46)与 Punycode。 |
在这个 HTTP 服务中,scoop.codec 为查询参数和 JSON 请求体生成 decode,为 JSON 响应生成 encode。每个类型只声明路由用到的方向。
//! dep: scoop:scoop.asyncio:0.1.0
//! dep: scoop:scoop.http.server:0.1.0
import scoop.asyncio.*
import scoop.http.server.*
private struct GreetingQuery(val name: String = "world") {
@GenerateWith("scoop.codec", ["ValueDecoder<GreetingQuery>"])
public companion object: ValueDecoder<GreetingQuery>
}
private struct GreetingInput(val name: String) {
@GenerateWith("scoop.codec", ["ValueDecoder<GreetingInput>"])
public companion object: ValueDecoder<GreetingInput>
}
private struct GreetingOutput(val message: String) {
@GenerateWith("scoop.codec", ["ValueEncoder<GreetingOutput>"])
public companion object: ValueEncoder<GreetingOutput>
}
fun main() {
val loop = eventLoop()
loop.run suspend {
HttpServer.listen(this) {
get(
"/greet",
suspend {
ctx ->
val query = ctx.request.query.decode<GreetingQuery>()
json(GreetingOutput("Hello, " + query.name + "!"))
}
)
post(
"/greet",
suspend {
ctx ->
val input = ctx.request.body.json<GreetingInput>()
json(GreetingOutput("Hello, " + input.name + "!"))
}
)
}.useAsync suspend {
server ->
println("Listening at http://" + server.localAddress.toString())
server.awaitTermination()
}
}
}在一个终端启动服务:
$ scoop run --release http_server.scoop
在另一个终端请求两个端点:
$ curl 'http://127.0.0.1:8080/greet?name=Scoop'
{"message":"Hello, Scoop!"}
$ curl -X POST -H 'content-type: application/json' -d '{"name":"Ada"}' http://127.0.0.1:8080/greet
{"message":"Hello, Ada!"}
演示结束后,在运行服务的终端按 Ctrl+C 停止程序。
数据、文本与编码
| Cone | 内容 |
|---|---|
scoop.json | 严格 JSON 解析与生成、不可变值树,以及基于 ValueEncoder/ValueDecoder 的类型化编解码。数据类型可以使用 scoop.codec 生成方法,见编解码。 |
scoop.regex | 基于 PCRE2(启用 JIT)的 UTF-8 正则:编号/命名捕获、惰性搜索、替换与分割。 |
scoop.charset | 字符集严格/有损转码、NFC 规范化、字素簇分段。 |
scoop.compression | gzip、zlib、raw DEFLATE、Brotli 与 zstd;内存、增量、同步流与异步流共用一套 API。 |
//! dep: scoop:scoop.json:0.1.0
import scoop.json.*
struct User(val name: String, val scores: Array<Int>, val note: String? = None) {
@GenerateWith("scoop.codec", ["ValueEncoder<User>", "ValueDecoder<User>"])
public companion object: ValueEncoder<User>, ValueDecoder<User>
}
fun main() {
val original = User("Ada", [7, 9])
val text = Json.encodeToString(original)
println(text)
val decoded = Json.decodeFromString<User>(text)
println(f"${decoded.name}: ${decoded.scores[1L]}")
println(decoded.note ?: "no note")
}应用开发与终端
| Cone | 内容 |
|---|---|
scoop.cli | 用注解描述位置参数、选项与开关。scoop.cli 生成器为 CliArguments<T> 实现 entries 和 bind,供 CliParser 解析参数和显示帮助。 |
scoop.log | 日志 facade:库创建分类 Logger,应用选择 provider;消息惰性求值。 |
scoop.log.console | 同步的 stdout/stderr 日志 provider,支持级别、格式与源码位置。 |
scoop.terminal / scoop.terminal.asyncio | 终端控制(以 crossterm 为基线移植):ANSI 样式、光标、原始模式、输入协议解析、异步按键与尺寸事件。Windows 上使用当前 console(启用 VT 输入输出),退出时恢复原有模式与代码页。 |
scoop.readline | 交互式行编辑(移植自 rustyline):历史、Emacs/Vi 模式、多行输入与补全;文件名补全遵循目标平台的路径语法(Windows 接受 / 与 \、盘符和 UNC 路径)。 |
//! dep: scoop:scoop.cli:0.1.0
import scoop.cli.*
struct Options(
@CliArgument(position = 0L, help = "Name to greet") val name: String,
@CliOption(names = ["--count", "-n"], defaultText = "1") val count: Int = 1,
@CliFlag(names = ["--excited", "-e"]) val excited: Boolean = false
) {
@GenerateWith("scoop.cli", ["CliArguments<Options>"])
companion object: CliArguments<Options>
}
fun main(args: Array<String>): Int {
val parser = CliParser(CliConfig("greet", "Print a greeting"), Options.Companion)
try {
when (parser.parseCommandLine(args)) {
case CliResult.HelpRequested -> print(parser.help())
case CliResult.Parsed(val options) -> {
if (options.count < 1) {
println("count must be positive")
return 2
}
val ending =
if (options.excited)
"!"
else
"."
for (index in 1 .. options.count) {
println(f"Hello, ${options.name}${ending}")
}
}
}
} catch (error: CliParseException) {
println(error.message ?: "invalid arguments")
return 2
}
return 0
}$ scoop run --release cli.scoop -- Ada --count 2 --excited
Hello, Ada!
Hello, Ada!
图形与桌面 UI
GUI 库随 lib-gui 组件包发布,支持 macOS、Linux GNU(Wayland 与 X11)和 Windows 桌面;Linux musl 目标不提供 GUI 后端。界面由 Scoop 通过 Skia 自绘(macOS 用 Metal,Windows 用 D3D12,Linux 用 EGL/GLES),窗口、菜单、文件对话框和托盘使用系统原生实现。入门见 UI 教程。
| Cone | 内容 |
|---|---|
scoop.ui | 声明式自绘框架,提供组件、状态、布局、焦点、弹层与滚动。输入区域可识别长按、轻扫、双指缩放与旋转。自绘元素通过 SemanticsHandle 发布角色、状态、动作和几何范围。见触摸、手势与无障碍。 |
scoop.ui.component | Label、Button、Input、Checkbox、布局容器、滚动与虚拟列表、Popover、Dialog、菜单、Toast、Tabs、表格、树、日历与图表,以及原生菜单、窗框、文件对话框与多窗口控制器。标准控件公开默认无障碍语义,可用 ComponentSemantics 补充名称和说明。 |
scoop.ui.style | 主题与样式协议:颜色、边框、圆角、阴影等 Style,主题 tokens、部件绘制与可复用效果。 |
scoop.ui.style.macos / .material / .fluent / .shadcn | 四套主题预设,提供 macosTheme、materialTheme、fluentTheme、shadcnTheme,支持浅色与深色。 |
scoop.ui.component.desktop / scoop.ui.component.tray | 把 Dock/任务栏状态与系统托盘接入组件 scope;单独成库,不需要的应用不必引入。 |
scoop.graphics | 与窗口无关的 Skia 2D 绘图:路径、渐变、裁剪与变换、图像和图层滤镜、SkSL 自定义着色器与背景采样,左上原点的逻辑坐标;CPU 离屏绘制不需要启动应用。 |
scoop.graphics.text / scoop.graphics.svg | 字体与段落排版(SkParagraph、HarfBuzz、ICU,支持富文本与行内对象);静态 SVG 渲染。 |
scoop.window / scoop.window.asyncio | 原生窗口、输入事件、重绘、显示器、全屏切换、菜单、剪贴板、拖放、窗口生命周期与事件循环。scoop.window.accessibility 将窗口语义树接入 macOS 的 NSAccessibility、Windows 的 UI Automation 和 Linux GNU 的 AT-SPI。 |
scoop.surface | 窗口呈现、帧调度、动画与区域输入,是 UI 宿主与图形设备之间的一层。 |
scoop.desktop / scoop.tray | 应用与窗口图标、Dock 角标与菜单、任务栏进度与 overlay、Windows Jump List;原生系统托盘(Linux 使用 StatusNotifierItem)。 |
scoop.icons.lucide | 精选的 Lucide SVG 图标,以不可变 SvgAsset 提供。 |
UI 程序同样可以单文件运行,在文件头声明所需的库:
//! dep: scoop:scoop.ui:0.1.0
//! dep: scoop:scoop.ui.component:0.1.0
//! dep: scoop:scoop.ui.style:0.1.0
//! dep: scoop:scoop.ui.style.macos:0.1.0
import scoop.ui.*
import scoop.ui.component.button
import scoop.ui.style.ThemeMode
import scoop.ui.style.ThemeSource
import scoop.ui.style.macos.macosTheme
class Counter(scope: ComponentScope): Component(scope) {
private var count: Int by state(0)
public override fun render(): View =
button(f"Count: ${count}", { count += 1 })
}
fun main() {
val source = ThemeSource(macosTheme(ThemeMode.Light))
context(source) {
runUiApplication("Counter", { scope -> Counter(scope) })
}
}$ scoop run --release ui-counter.scoop
打开的窗口是一个按钮,每次点击计数加一。布局、状态、表单、主题、自绘与桌面集成按篇讲解,见 UI 教程;需要分发时用 scoop bundle 生成各平台的安装包。
更多示例
可以先用离线示例索引查找完整程序和运行说明:
$ scoop example --list
$ scoop example --search "异步"
$ scoop example async/tasks
库源码目录中的示例也可以直接运行:
$ scoop-install show # 输出中的 Root 是工具链根目录
$ cd <Root>/src/scoop.asyncio/examples
$ scoop run --release tcp_echo.scoop
网络示例只使用本机回环地址;TLS 示例会现场生成短期证书。