### Start and sample a new application with cjprof Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/tools/source_zh_cn/tools/cjprof_manual_cjnative.md Example of starting a new application and sampling it with the maximum system frequency. The output is saved to the default 'cjprof.data' file. ```text # 执行当前路径下的 `test` 应用程序,参数为 `arg1 arg2` ,并以系统支持的最大采样频率对其进行采样,采样结束后将采样数据生成在当前路径下名为 `cjprof.data` (默认文件名)的文件中。 cjprof record -f max -- ./test arg1 arg2 ``` -------------------------------- ### WebSocket Client and Server Example Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/manual/source_zh_cn/Net/net_websocket.md This comprehensive example demonstrates a full WebSocket interaction, including server setup, client connection, message exchange, and graceful closure. It covers both client-side and server-side logic within a single runnable example. ```cangjie import stdx.net.http.* import stdx.encoding.url.* import std.time.* import std.sync.* import std.collection.* import stdx.log.* let server = ServerBuilder() .addr("127.0.0.1") .port(0) .build() // client: main() { // 1 启动服务器 spawn { startServer() } sleep(Duration.millisecond * 200) let client = ClientBuilder().build() let u = URL.parse("ws://127.0.0.1:${server.port}/webSocket") let subProtocol = ArrayList(["foo1", "bar1"]) let headers = HttpHeaders() headers.add("test", "echo") // 2 完成 WebSocket 握手,获取 WebSocket 实例 let websocket: WebSocket let respHeaders: HttpHeaders (websocket, respHeaders) = WebSocket.upgradeFromClient(client, u, subProtocols: subProtocol, headers: headers) client.close() println("subProtocol: ${websocket.subProtocol}") // fool1 println(respHeaders.getFirst("rsp") ?? "") // echo // 3 消息收发 // 发送 hello websocket.write(TextWebFrame, "hello".toArray()) // 收 let data = ArrayList() var frame = websocket.read() while(true) { match(frame.frameType) { case ContinuationWebFrame => data.add(all: frame.payload) if (frame.fin) { break } case TextWebFrame | BinaryWebFrame => if (!data.isEmpty()) { throw Exception("invalid frame") } data.add(all: frame.payload) if (frame.fin) { break } case CloseWebFrame => websocket.write(CloseWebFrame, frame.payload) break case PingWebFrame => websocket.writePongFrame(frame.payload) case _ => () } frame = websocket.read() } println("data size: ${data.size}") // 4097 println("last item: ${String.fromUtf8(data.toArray()[4096])}") // a // 4 关闭 websocket, // 收发 CloseFrame websocket.writeCloseFrame(status: 1000) let websocketFrame = websocket.read() println("close frame type: ${websocketFrame.frameType}") // CloseWebFrame println("close frame payload: ${websocketFrame.payload}") // 3, 232 // 关闭底层连接 websocket.closeConn() server.close() } func startServer() { // 1 注册 handler server.distributor.register("/webSocket", handler1) server.logger.level = LogLevel.OFF server.serve() } // server: func handler1(ctx: HttpContext): Unit { // 2 完成 websocket 握手,获取 websocket 实例 let websocketServer = WebSocket.upgradeFromServer(ctx, subProtocols: ArrayList(["foo", "bar", "foo1"]), userFunc: {request: HttpRequest => let value = request.headers.getFirst("test") ?? "" let headers = HttpHeaders() headers.add("rsp", value) headers }) // 3 消息收发 // 收 hello let data = ArrayList() var frame = websocketServer.read() while(true) { match(frame.frameType) { case ContinuationWebFrame => data.add(all: frame.payload) if (frame.fin) { break } case TextWebFrame | BinaryWebFrame => if (!data.isEmpty()) { throw Exception("invalid frame") } data.add(all: frame.payload) if (frame.fin) { break } case CloseWebFrame => websocketServer.write(CloseWebFrame, frame.payload) break case PingWebFrame => websocketServer.writePongFrame(frame.payload) case _ => () } frame = websocketServer.read() } println("data: ${String.fromUtf8(data.toArray())}") // hello // 发 4097 个 a websocketServer.write(TextWebFrame, Array(4097, repeat: 97)) // 4 关闭 websocket, // 收发 CloseFrame let websocketFrame = websocketServer.read() println("close frame type: ${websocketFrame.frameType}") // CloseWebFrame println("close frame payload: ${websocketFrame.payload}") // 3, 232 websocketServer.write(CloseWebFrame, websocketFrame.payload) // 关闭底层连接 websocketServer.closeConn() } ``` -------------------------------- ### Get Value or Default Example Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/core/core_package_api/core_package_enums.md Demonstrates retrieving a value from an Option or using a default value if the Option is None. ```cangjie main() { var value1: Option = Some(2) println(value1.getOrDefault({=> 0})) var value2: Option = None println(value2.getOrDefault({=> 0})) } ``` -------------------------------- ### Cangjie HTTP Client-Server Example Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/manual/source_zh_cn/Net/net_http.md This example shows a complete client-server interaction. The server listens for GET requests on /hello and responds with 'Hello Cangjie!'. The client connects to the server, sends the request, and prints the response body. Ensure stdx packages are installed and configured. ```cangjie import stdx.net.http.* import std.time.* import std.sync.* import stdx.log.* // 1. 构建 Server 实例 let server = ServerBuilder() .addr("127.0.0.1") .port(0) .build() func startServer(): Unit { // 2. 注册请求处理逻辑 server.distributor.register("/hello", {httpContext => httpContext.responseBuilder.body("Hello Cangjie!") }) server.logger.level = LogLevel.OFF // 3. 启动服务 server.serve() } func startClient(): Unit { // 1. 构建 client 实例 let client = ClientBuilder().build() // 2. 发送 request let response = client.get("http://127.0.0.1:${server.port}/hello") // 3. 读取response body let buffer = Array(32, repeat: 0) let length = response.body.read(buffer) println(String.fromUtf8(buffer[..length])) // 4. 关闭连接 client.close() } main () { spawn { startServer() } sleep(Duration.second) startClient() } ``` -------------------------------- ### startCPUProfiling Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/runtime/runtime_package_overview.md Starts CPU profiler tracking. ```APIDOC ## startCPUProfiling() ### Description Starts CPU profiler tracking. ``` -------------------------------- ### Launch Program: Start CJDB and Load Executable Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/tools/source_zh_cn/tools/cjdb_manual_cjnative.md Use this method to start the debugger and load the target program simultaneously. Ensure the executable path is correct. ```text ~/0901/cangjie_test$ cjdb test (cjdb) target create "test" Current executable set to '/0901/cangjie-linux-x86_64-release/bin/test' (x86_64). (cjdb) ``` -------------------------------- ### CJPM Build Script Example Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/tools/source_zh_cn/tools/cjpm_manual_cjnative_community.md This example defines pre-build and post-build actions for the 'cjpm build' command. It prints messages to the console, which will be logged to the script-log file. ```cangjie import std.process.* func stagePreBuild(): Int64 { println("PRE-BUILD") 0 } func stagePostBuild(): Int64 { println("POST-BUILD") 0 } main(): Int64 { match (Process.current.arguments[0]) { case "pre-build" => stagePreBuild() case "post-build" => stagePostBuild() case _ => 0 } } ``` -------------------------------- ### Example: Using BufferedOutputStream with Try-with-Resource Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/io/io_package_api/io_package_classes.md This example demonstrates the usage of BufferedOutputStream within a try-with-resource block, showcasing automatic resource management and stream operations. ```cangjie import std.io.BufferedOutputStream import std.io.OutputStream import std.io.ByteBuffer import std.io.readToEnd /** * 自定义实现 OutputStream 和 Resource 接口的类A */ public class A <: OutputStream & Resource { private var closed: Bool = false public var outputStream = ByteBuffer() public func write(buffer: Array): Unit { this.outputStream = ByteBuffer(buffer) } public func isClosed(): Bool { return closed } public func close(): Unit { println("Resource is closed") closed = true } } main(): Unit { let resourceStream = A() let bufferedStream = BufferedOutputStream(resourceStream) /* 使用try-with-resource语法获取资源 */ try (r = bufferedStream) { println("Get the resource") let data = "Hello World".toArray() r.write(data) r.flush() println(r.isClosed()) println(String.fromUtf8(readToEnd(resourceStream.outputStream))) } /* 自动调用 close() 函数释放资源 */ println(bufferedStream.isClosed()) } ``` -------------------------------- ### Launch Program: Start CJDB then Load Executable Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/tools/source_zh_cn/tools/cjdb_manual_cjnative.md Start the CJDB debugger first, then use the 'file' command to load the target executable. This is an alternative to launching them together. ```text ~/0901/cangjie_test$ cjdb (cjdb) file test Current executable set to '/0901/cangjie/test' (x86_64). (cjdb) ``` -------------------------------- ### Install Local Project with CJPM Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/tools/source_zh_cn/tools/cjpm_manual_cjnative_community.md Use this command to install a local CJPM project. Ensure the project is compiled before installation. The output will be named after the project, with a `.exe` suffix on Windows. ```bash cjpm install --path path/to/project ``` -------------------------------- ### Install Dependencies on Ubuntu 20.04 Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/manual/source_zh_cn/Appendix/linux_toolchain_install.md Use apt-get to install essential development tools for the Cangjie toolchain on Ubuntu 20.04. Manual installation of OpenSSL 3 is required. ```shell $ apt-get install \ binutils \ libc-dev \ libc++-dev \ libgcc-9-dev ``` -------------------------------- ### Example: Calculating Next UInt64 Value Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/core/core_package_api/core_package_intrinsics.md Shows how to use the next function to find a UInt64 value at a specified offset. The example demonstrates a simple addition operation. ```cangjie main() { var num: UInt64 = 3 println(num.next(10)) } ``` -------------------------------- ### Install Git Project with CJPM Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/tools/source_zh_cn/tools/cjpm_manual_cjnative_community.md Use this command to install a CJPM project directly from a Git repository. The project will be compiled and installed based on the provided URL. ```bash cjpm install --git url ``` -------------------------------- ### Install OpenSSL 3 Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/manual/source_zh_cn/Appendix/linux_toolchain_install.md Install the compiled OpenSSL library to the system or a specified custom path. Root privileges may be required for system-wide installation. ```shell $ make install ``` ```shell $ sudo make install ``` -------------------------------- ### Directory Structure for Macro Example Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/manual/source_zh_cn/Macro/macro_introduction.md Illustrates the required directory layout for the `dprint` macro example, with the macro definition in `define/dprint.cj` and the test code in `main.cj`. ```text // Directory layout. src |-- define | `-- dprint.cj `-- main.cj ``` -------------------------------- ### CJLint Scan Example (Positive) Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/tools/source_zh_cn/tools/cjlint_manual.md Example of correctly specifying the source directory for CJLint using the '-f' option. ```bash cjlint -f xxx/xxx/src ``` -------------------------------- ### POSIX Process Operations Example Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/posix/posix_samples/posix_process_samples.md Demonstrates `nice`, `kill`, `killpg`, and `isatty` functions for process management and terminal checks. Note that this example is not compatible with Windows. ```cangjie import std.posix.* main(): Int64 { var result = nice(200) print("${result}") var result1 = kill(0, SIGCHLD) println(result1) var result2 = killpg(0, SIGURG) println("result ==> ${result2}") if (isatty(0) && isatty(1) && isatty(2)) { print("true01 ") } else { print("false01 ") } if (isatty(-23) || isatty(4) || isatty(455) || isatty(43332)) { print("true02 ") } else { println("false02") } return 0 } ``` -------------------------------- ### Example: Getting and Setting Static Variable Value Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/reflect/reflect_package_api/reflect_package_classes.md Demonstrates how to retrieve a ClassTypeInfo, get a static variable by name, retrieve its value, and then set a new value. This example requires the 'std.reflect' package. ```cangjie package test import std.reflect.* public class Rectangular { public static var area: Int64 = 10 } main(): Unit { // 此处是通过 Rectangular 的类型的限定名称获取 ClassTypeInfo,也可以通过实例获取 ClassTypeInfo let ty = ClassTypeInfo.get("test.Rectangular") // 获取静态变量 let sv = ty.getStaticVariable("area") // 获取值 println(sv.getValue() as Int64) return } ``` ```text Some(10) ``` -------------------------------- ### 编写第一个仓颉程序 Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/manual/source_zh_cn/first_understanding/hello_world.md 这是仓颉语言的 'Hello, World!' 程序。它展示了基本的 `main` 函数和 `println` 调用。注释语法与 C/C++ 类似。 ```cangjie // hello.cj main() { println("你好,仓颉") } ``` -------------------------------- ### Get Process Start Time Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/process/process_package_api/process_package_classes.md Retrieves the time when the process started. If retrieval fails, it returns DateTime.UnixEpoch. ```cangjie public prop startTime: DateTime ``` -------------------------------- ### Array DataStrategy Usage Example Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/unittest_common/unittest_common_package_api/unittest_common_package_interfaces.md Example demonstrating how to use the Array extension of DataStrategy for test data configuration. ```cangjie @Test[x in [1,2,3]] func test(x: Int64) {} ``` -------------------------------- ### Run Project Binary with CJPM Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/tools/source_zh_cn/tools/cjpm_manual_cjnative_community.md Use the `run` command to execute the built binary of your current project. It defaults to running the `main` binary and can be configured with various options. ```text cjpm run ``` ```text cjpm run -g // 此时会默认执行 cjpm build -i -g 命令 ``` ```text cjpm run --build-args="-s -j16" --run-args="a b c" ``` -------------------------------- ### Example: Getting Instance Variable Value Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/reflect/reflect_package_api/reflect_package_classes.md Demonstrates how to get the ClassTypeInfo for a class, retrieve an InstanceVariableInfo for a specific variable, and then get the value of that variable from an instance of the class. ```cangjie import std.reflect.* public class Rectangular { public var length = 4 public var width = 5 } main(): Unit { // 此处是通过 Rectangular 的类型的限定名称获取 ClassTypeInfo,也可以通过实例获取 ClassTypeInfo let ty = ClassTypeInfo.get("default.Rectangular") // 获取 InstanceVariableInfo var gip = ty.getInstanceVariable("width") // 获取实例值 var r = Rectangular() let v = gip.getValue(r) as Int64 println(v) return } ``` -------------------------------- ### Unordered Verification Examples Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/unittest_mock/unittest_mock_package_api/unittest_mock_package_enums.md Demonstrates the usage of `Verify.unordered` with and without the 'Partial' mode. The first example throws an exception due to mismatched call counts, while the second succeeds by ignoring unverified calls when 'Partial' mode is specified. ```cangjie for (i in 0..6) { foo.bar(i % 3) } // 此处验证动作将抛出异常,因为 foo.bar()在验证范围内一共执行了 6 次,而此处的验证动作仅指定了 4 次执行行为。 Verify.unordered( @Called(foo.bar(1)).times(2), @Called(foo.bar(2)).times(2) ) // 此处验证动作可以成功,指定了 Partial 模式后,2 次未在验证动作中定义的执行行为将被忽略。 Verify.unordered(Partial, @Called(foo.bar(1)).times(2), @Called(foo.bar(2)).times(2) ) ``` -------------------------------- ### Example: Getting IntNative Position Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/core/core_package_api/core_package_intrinsics.md Demonstrates how to get the position of an IntNative value, which is returned as an Int64. This is useful for understanding the numerical representation. ```cangjie main() { var num: IntNative = 8 println(num.position()) } ``` -------------------------------- ### Example Target-Dir Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/tools/source_zh_cn/tools/cjpm_manual_cjnative_community.md Specifies a custom directory for storing build artifacts. Be cautious as `cjpm clean` will remove this directory. ```toml target-dir = "temp" ``` -------------------------------- ### Example: Using BufferedOutputStream with Seekable Interface Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/io/io_package_api/io_package_classes.md Demonstrates the usage of BufferedOutputStream extended with Seekable capabilities. This example shows writing data, flushing, checking stream properties, seeking to different positions, and handling exceptions during seek operations. ```cangjie import std.io.BufferedOutputStream import std.io.OutputStream import std.io.ByteBuffer import std.io.Seekable import std.io.SeekPosition import std.io.IOException import std.io.readToEnd /** * 自定义实现 OutputStream 和 Seekable 接口的类A */ public class A <: OutputStream & Seekable { public var outputStream: ByteBuffer = ByteBuffer() public func write(buffer: Array): Unit { this.outputStream = ByteBuffer(buffer) } public func seek(sp: SeekPosition): Int64 { return outputStream.seek(sp) } } main(): Unit { let seekableStream = A() let bufferedStream = BufferedOutputStream(seekableStream) let data = "Hello World".toArray() bufferedStream.write(data) bufferedStream.flush() /* 输出当前流中总数据量,当前光标位置,当前流中未读的数据量 */ println("Length : " + bufferedStream.length.toString()) println("Position : " + bufferedStream.position.toString()) println("Remain Length : " + bufferedStream.remainLength.toString()) /* 移动光标到指定位置,虽然超过了流中数据末尾但是合法的 */ println("Position after seek() : " + bufferedStream.seek(SeekPosition.Current(11)).toString()) /* 尝试移动到数据头部之前,抛出异常 */ try { bufferedStream.seek(SeekPosition.Begin(-1)) } catch (e: IOException) { println("Error: " + e.message) } /* 将光标移动到第一个单词之后,读取后续的数据 */ bufferedStream.seek(SeekPosition.Begin(6)) println(String.fromUtf8(readToEnd(seekableStream.outputStream))) } ``` -------------------------------- ### Example: Default Root and Source Paths Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/tools/source_zh_cn/tools/cjcov_manual_cjnative.md Shows the command execution when neither --root nor --source is specified. In this case, the current directory is used as the reference for relative paths. ```shell cjcov --html-details --output=html_output ``` -------------------------------- ### matchPosition() Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/regex/regex_package_api/regex_package_structs.md Gets the start and end indices of the last matched substring within the input string. ```APIDOC ## func matchPosition() ```cangjie public func matchPosition(): Position ``` 功能:获取上一次匹配到的子字符串在输入字符串中起始位置和末尾位置的索引。 返回值: - [Position](#struct-position) - 匹配结果位置信息。 示例: ```cangjie import std.regex.* main(): Unit { let r = Regex(#"(?\d{4})-(?\d{2})-(?\d{2})"#) let iter = r.lazyFindAll("2024-10-24&2025-01-01", group: true) while (true) { match (iter.next()) { case Some(md) => println("# found: ${md.matchString()} and groupCount: ${md.groupCount()}") let pos = md.matchPosition(0) println("pos: [${pos.start}, ${pos.end}]") case None => break } } } ``` 运行结果: ```text # found: 2024-10-24 and groupCount: 3 pos: [0, 10] # found: 2025-01-01 and groupCount: 3 pos: [11, 21] ``` ``` -------------------------------- ### Get UTF-8 Size from Bytes Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/core/core_package_api/core_package_intrinsics.md Determines the number of bytes a UTF-8 character occupies in a byte array starting at a given index. Throws IllegalArgumentException if the byte at the index is not the start of a valid UTF-8 sequence. ```cangjie public static func utf8Size(arr: Array, index: Int64): Int64 ``` ```cangjie main() { var arr: Array = [ 1u8, 2u8, 231u8, 136u8, 177u8, 145u8] var len: Int64 = Rune.utf8Size(arr, 2) println(len) // 索引为2-4的数组元素为中文字符爱的utf-8编码,占用三字节 } ``` -------------------------------- ### CJPM Bench Command Usage Examples Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/tools/source_zh_cn/tools/cjpm_manual_cjnative_community.md Demonstrates various ways to invoke the 'cjpm bench' command, including specifying a source directory and filtering test cases. Benchmarks do not fully support 'mock' to avoid overhead; using 'mock' with benchmarks may lead to runtime exceptions. ```text 输入: cjpm bench 输出: cjpm bench success ``` ```text 输入: cjpm bench src 输出: cjpm bench success ``` ```text 输入: cjpm bench src --filter=* 输出: cjpm bench success ``` ```text 输入: cjpm bench src --report-format=csv 输出: cjpm bench success ``` -------------------------------- ### Example of using replace(K, V) and iterating Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/collection_concurrent/collection_concurrent_package_api/collection_concurrent_class.md Demonstrates replacing a value for a key and then iterating through the map to show the updated content. This example initializes a ConcurrentHashMap and then modifies an entry. ```cangjie import std.collection.concurrent.* main() { let map: ConcurrentHashMap = ConcurrentHashMap(3, {value => (value, value)}) let num = map.replace(0, 2) println(num) let iter = map.iterator() while (true) { match (iter.next()) { case Some(i) => println("(${i[0]},${i[1]})") case None => break } } } ``` -------------------------------- ### PropDecl Class Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/ast/ast_package_api/ast_package_classes.md Represents a property declaration node. Example: `prop X: Int64 { get() { 0 } }`. ```APIDOC ## Class PropDecl ### Description Represents a property declaration node. ### Example `prop X: Int64 { get() { 0 } }` ### Constructors #### `init()` Constructs a default `PropDecl` object. #### `init(inputs: Tokens)` Constructs a `PropDecl` object. - **inputs** (Tokens) - The token collection to construct the `PropDecl` type. ``` -------------------------------- ### Creating Directories and Files using Path Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/fs/fs_samples/path_samples.md This snippet illustrates how to create a directory and a file within that directory using Path instances. It checks for the existence of the directory and file after creation and cleans up by removing the created directory and its contents. ```cangjie import std.fs.* main() { let curPath: Path = Path("./") let dirPath: Path = curPath.join("tempDir") let filePath: Path = dirPath.join("tempFile.txt") if (exists(dirPath)) { remove(dirPath, recursive: true) } Directory.create(dirPath) if (exists(dirPath)) { println("Directory 'tempDir' is created successfully.") } File.create(filePath).close() if (exists(filePath)) { println("File 'tempFile.txt' is created successfully in directory 'tempDir'.") } remove(dirPath, recursive: true) return 0 } ``` -------------------------------- ### BenchInputProvider reset Method Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/unittest/unittest_package_api/unittest_package_interfaces.md Called before a benchmark starts. Ensures that subsequent calls to get(i) for i in [0, max) will succeed. ```cangjie mut func reset(max: Int64) ``` -------------------------------- ### Get Process Command Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/process/process_package_api/process_package_classes.md Retrieves the command used to start the process. An exception is thrown if the process does not exist or is a zombie process. ```cangjie public prop command: String ``` -------------------------------- ### Test Execution with Report Path and Format Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/tools/source_zh_cn/tools/cjpm_manual_cjnative_community.md This example demonstrates running tests and specifying a report path and format (XML). ```text 输入: cjpm test --report-path=reports --report-format=xml 输出: cjpm test success ``` -------------------------------- ### Get Masked IPPrefix Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/net/net_package_api/net_package_classes.md Returns the IPPrefix address masked according to its prefix length. For example, '192.168.12.34/16' returns '192.168.0.0/16'. ```cangjie public open func masked(): IPPrefix ``` -------------------------------- ### Get Rune from UTF-8 Bytes (Previous) Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/core/core_package_api/core_package_intrinsics.md Retrieves a Rune from a byte array starting at a given index, searching backwards for the start of the UTF-8 sequence. Returns the Rune and the index of its first byte. Throws IllegalArgumentException if the byte sequence is invalid. ```cangjie public static func getPreviousFromUtf8(arr: Array, index: Int64): (Rune, Int64) ``` -------------------------------- ### Constructing Tokens Collections Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/manual/source_zh_cn/Macro/Tokens_types_and_quote_expressions.md Shows how to create Tokens instances, which are collections of Tokens, using different constructor methods and demonstrates basic operations like printing and dumping for debugging. ```cangjie import std.ast.* let tks = Tokens([ Token(TokenKind.INTEGER_LITERAL, "1"), Token(TokenKind.ADD), Token(TokenKind.INTEGER_LITERAL, "2") ]) main() { println(tks) tks.dump() } ``` -------------------------------- ### Get Process Command Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/env/env_package_api/env_package_funcs.md Retrieves the command used to start the current process. Throws EnvException if the process is non-existent or a zombie process. ```cangjie public func getCommand(): String ``` -------------------------------- ### Example: Malloc, Write, Read, and Free CPointer Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/core/core_package_api/core_package_structs.md Shows how to allocate memory for an Int64 using malloc, write a value to it, read the value back, and then free the allocated memory. ```cangjie main() { var p = unsafe { LibC.malloc(count: 1) } unsafe { p.write(8) } let value: Int64 = unsafe { p.read() } println(value) unsafe { LibC.free(p) } } ``` -------------------------------- ### Example: Try Parsing IPv4 and IPv6 Prefixes Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/net/net_package_api/net_package_classes.md Demonstrates using tryParse to safely parse IPv4 and IPv6 addresses into IPPrefix objects, asserting the 'Some' wrapped results. ```cangjie import std.net.* import std.unittest.* import std.unittest.testmacro.* main () { let v4: ?IPPrefix = IPPrefix.tryParse("192.168.1.2/24") let v6: ?IPPrefix = IPPrefix.tryParse("2001:0250:1006:dff0:4913:2aa5:8075:7c10/32") @Assert(v4.toString(), "Some(192.168.1.2/24)") @Assert(v6.toString(), "Some(2001:250:1006:dff0:4913:2aa5:8075:7c10/32)") } ``` -------------------------------- ### Example of Timer.once Usage Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/sync/sync_package_api/sync_package_classes.md Demonstrates scheduling a one-time task using Timer.once and printing the execution time relative to the start time. ```cangjie import std.time.MonoTime main() { let start = MonoTime.now() Timer.once(Duration.second, {=> println("Tick at: ${MonoTime.now() - start}") }) sleep(Duration.second * 2) 0 } ``` -------------------------------- ### Example: Parsing IPv4 and IPv6 Prefixes Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/net/net_package_api/net_package_classes.md Demonstrates parsing both IPv4 and IPv6 addresses into IPPrefix objects and asserting their string representations. ```cangjie import std.net.* import std.unittest.* import std.unittest.testmacro.* main () { let v4: IPPrefix = IPPrefix.parse("192.168.1.2/24") let v6: IPPrefix = IPPrefix.parse("2001:0250:1006:dff0:4913:2aa5:8075:7c10/32") @Assert(v4.toString(), "192.168.1.2/24") @Assert(v6.toString(), "2001:250:1006:dff0:4913:2aa5:8075:7c10/32") } ``` -------------------------------- ### Get ArrayList Size Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/manual/source_zh_cn/Collections/collection_arraylist.md Obtain the number of elements in an ArrayList using the `size` property. This example checks if the list is empty and prints its size. ```cangjie import std.collection.* main() { let list = ArrayList([0, 1, 2]) if (list.size == 0) { println("This is an empty arraylist") } else { println("The size of arraylist is ${list.size}") } } ``` -------------------------------- ### Example: Comparing UInt64 Values Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/core/core_package_api/core_package_intrinsics.md Demonstrates how to use the compare function to determine the ordering between two UInt64 numbers. The output shows the result of the comparison. ```cangjie main() { var num1: UInt64 = 2 var num2: UInt64 = 3 println(num1.compare(num2)) } ``` -------------------------------- ### Example: Getting UInt64 Position Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/core/core_package_api/core_package_intrinsics.md Demonstrates retrieving the position of a UInt64 value, which is its direct integer representation. The output is the Int64 equivalent of the UInt64. ```cangjie main() { var num: UInt64 = 8 println(num.position()) } ``` -------------------------------- ### Constructing Tokens Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/manual/source_zh_cn/Macro/Tokens_types_and_quote_expressions.md Demonstrates how to construct individual Token instances using various TokenKind values and optional string values for literals. ```cangjie import std.ast.* let tk1 = Token(TokenKind.ADD) // '+' 运算符 let tk2 = Token(TokenKind.FUNC) // func 关键字 let tk3 = Token(TokenKind.IDENTIFIER, "x") // x 标识符 let tk4 = Token(TokenKind.INTEGER_LITERAL, "3") // 整数字面量 let tk5 = Token(TokenKind.STRING_LITERAL, "xyz") // 字符串字面量 ``` -------------------------------- ### Convert IPv6Address to IPv4Mapped IPv4Address Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/net/net_package_api/net_package_classes.md Converts an IPv6Address to an IPv4-mapped IPv4Address. For example, ::ffff:a.b.c.d converts to a.b.c.d. Addresses not starting with ::ffff will return None. ```cangjie public func toIPv4Mapped(): ?IPv4Address ``` -------------------------------- ### UnixSocketAddress toString() Example Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/net/net_package_api/net_package_classes.md Demonstrates the usage of the toString() method to get the string representation of a UnixSocketAddress. Includes assertions for various valid and invalid socket path formats. ```cangjie public func toString(): String ``` ```cangjie import std.net.* import std.unittest.* import std.unittest.testmacro.* main () { let expect1 = "/tmp/server1.sock" let expect2 = "\u{0}/tmp/server1.sock" let udsa1_1: UnixSocketAddress = UnixSocketAddress("/tmp/server1.sock") let udsa2_1: UnixSocketAddress = UnixSocketAddress("/tmp/server1.sock".toArray()) let udsa2_2: UnixSocketAddress = UnixSocketAddress("/tmp/server1.sock\u{0}\u{0}".toArray()) let udsa3_1: UnixSocketAddress = UnixSocketAddress("\u{0}/tmp/server1.sock") let udsa4_1: UnixSocketAddress = UnixSocketAddress("\u{0}/tmp/server1.sock".toArray()) let udsa4_2: UnixSocketAddress = UnixSocketAddress("\u{0}/tmp/server1.sock\u{0}\u{0}".toArray()) @Assert(udsa1_1.toString(), expect1) @Assert(udsa2_1.toString(), expect1) @Assert(udsa2_2.toString(), expect1) @Assert(udsa3_1.toString(), expect2) @Assert(udsa1_1, udsa2_1) @Assert(udsa1_1, udsa2_2) @Assert(udsa3_1, udsa4_1) @Assert(udsa3_1, udsa4_2) @Assert(udsa4_1.toString(), expect2) @Assert(udsa4_2.toString(), expect2) try { UnixSocketAddress("/tmp/server1\u{0}.sock") } catch (e: IllegalArgumentException) { @Assert(true) } try { UnixSocketAddress("/tmp/server1.sock\u{0}\u{0}") } catch (e: IllegalArgumentException) { @Assert(true) } try { UnixSocketAddress("\u{0}/tmp/server1.sock\u{0}\u{0}") } catch (e: IllegalArgumentException) { @Assert(true) } try { UnixSocketAddress("/tmp/server1\u{0}.sock".toArray()) } catch (e: IllegalArgumentException) { @Assert(true) } return } ``` -------------------------------- ### CJPM Bench Command Output Example Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/tools/source_zh_cn/tools/cjpm_manual_cjnative_community.md This shows the typical output when running the 'cjpm bench' command, including performance metrics and test results. Ensure the project builds successfully before running benchmarks. ```text 输入: cjpm bench 输出: TP: bench, time elapsed: 8107939844 ns, RESULT: TCS: Test_UT, time elapsed: 8107939844 ns, RESULT: | Case | Median | Err | Err% | Mean | |:-----------|---------:|------------:|-------:|---------:| | Benchmark1 | 5.438 ns | ±0.00439 ns | ±0.1% | 5.420 ns | Summary: TOTAL: 1 PASSED: 1, SKIPPED: 0, ERROR: 0 FAILED: 0 -------------------------------------------------------------------------------------------------- Project tests finished, time elapsed: 8107939844 ns, RESULT: TP: bench.*, time elapsed: 8107939844 ns, RESULT: PASSED: TP: bench, time elapsed: 8107939844 ns, RESULT: Summary: TOTAL: 1 PASSED: 1, SKIPPED: 0, ERROR: 0 FAILED: 0 ``` -------------------------------- ### Get Max Heap Size Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/runtime/runtime_package_api/runtime_package_structs.md Example demonstrating how to retrieve the maximum heap size using the deprecated MemoryInfo struct. Note that this functionality is being replaced by global functions. ```cangjie import std.runtime.* main() { println(MemoryInfo.maxHeapSize) } ``` -------------------------------- ### CJPM Command Extension Example Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/tools/source_zh_cn/tools/cjpm_manual_cjnative_community.md Demonstrates how to extend CJPM commands using an executable file named 'cjpm-demo'. Ensure the directory containing the executable is in the system's PATH. ```cangjie import std.process.* import std.collection.* main(): Int64 { var args = ArrayList(Process.current.arguments) if (args.size < 1) { eprintln("Error: failed to get parameters") return 1 } println("Output: ${args[0]}") return 0 } ``` -------------------------------- ### IPPrefix toString() Example Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/net/net_package_api/net_package_classes.md Demonstrates the usage of the toString() method for both IPv4 and IPv6 IPPrefix objects. ```cangjie import std.net.* import std.unittest.* import std.unittest.testmacro.* main () { let v4: IPPrefix = IPAddress.parse("192.168.1.2").getPrefix(24) let v6: IPPrefix = IPAddress.parse("2001:0250:1006:dff0:4913:2aa5:8075:7c10").getPrefix(32) @Assert(v4.toString(), "192.168.1.2/24") @Assert(v6.toString(), "2001:250:1006:dff0:4913:2aa5:8075:7c10/32") } ``` -------------------------------- ### Get UTF-8 Size of Rune Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/core/core_package_api/core_package_intrinsics.md Returns the number of bytes a Rune character occupies in UTF-8 encoding. For example, Chinese characters typically occupy 3 bytes. ```cangjie public static func utf8Size(c: Rune): Int64 ``` ```cangjie main() { var char: Rune = r'爱' var len: Int64 = Rune.utf8Size(char) println(len) // 中文字符爱的utf-8编码,占用三字节 } ``` -------------------------------- ### Get Match Position - Regex MatchData Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/regex/regex_package_api/regex_package_structs.md Retrieves the start and end indices of the entire matched substring in the input string. This is useful for locating the matched text within the original string. ```cangjie public func matchPosition(): Position ``` -------------------------------- ### Initialize File with Path Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/fs/fs_package_api/fs_package_classes.md Creates a File object using a Path instance and a specified OpenMode. Ensure the path is valid and the mode is appropriate to avoid exceptions. ```cangjie public init(path: Path, mode: OpenMode) ``` -------------------------------- ### Invalid Normal Identifiers in Cangjie Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/manual/source_zh_cn/basic_programming_concepts/identifier.md These examples illustrate invalid normal identifiers. They violate the naming rules, such as using characters not allowed in XID_Continue, starting with a digit, or using a keyword as an identifier. ```text ab&c // & 不是 XID_Continue 字符 3abc // 阿拉伯数字不是 XID_Start 字符,因此,数字不能作为起始字符 _ // _ 后至少需要有一个 XID_Continue 字符 while // while 是仓颉关键字,普通标识符不能使用仓颉关键字 ``` -------------------------------- ### Example: Get Static Property Value Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/reflect/reflect_package_api/reflect_package_classes.md Demonstrates how to retrieve the value of a static property ('sides') from a class ('Rectangular') using reflection. It obtains the ClassTypeInfo, then the StaticPropertyInfo, and finally calls getValue(). ```cangjie package test import std.reflect.* public class Rectangular { public static prop sides: Int64 { get() { 4 } } public static prop angles: Int64 { get() { 4 } } } main(): Unit { // 此处是通过 Rectangular 的类型的限定名称获取 ClassTypeInfo,也可以通过实例获取 ClassTypeInfo let ty = ClassTypeInfo.get("test.Rectangular") // 获取静态属性 let sp = ty.getStaticProperty("sides") let result = sp.getValue() as Int64 println(result) return } ``` -------------------------------- ### Example Cangjie Source File Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/manual/source_zh_cn/compile_and_build/cjc_usage.md A simple 'Hello, World!' program written in the Cangjie programming language. ```cangjie main() { println("Hello, World!") } ``` -------------------------------- ### Convert IPv6Address to IPv4Address Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/net/net_package_api/net_package_classes.md Converts an IPv6Address to an IPv4-compatible IPv4Address. For example, ::a.b.c.d and ::ffff:a.b.c.d convert to a.b.c.d, and ::1 converts to 0.0.0.1. Addresses not starting with all zeros or ::ffff will return None. ```cangjie public func toIPv4(): ?IPv4Address ``` -------------------------------- ### CJPM Package Structure Example Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/tools/source_zh_cn/tools/cjpm_manual_cjnative_community.md Illustrates a valid CJPM project structure where 'demo.pkg0' is recognized as a source package by including 'pkg0.cj'. ```text demo ├── src │ ├── main.cj │ └── pkg0 │ ├── pkg0.cj │ ├── aoo │ │ └── aoo.cj │ └── boo │ └── boo.cj └── cjpm.toml ``` -------------------------------- ### Valid Normal Identifiers in Cangjie Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/manual/source_zh_cn/basic_programming_concepts/identifier.md These examples demonstrate valid normal identifiers that follow the rules: starting with an XID_Start character or an underscore, followed by XID_Continue characters. They include alphanumeric characters, underscores, and Chinese characters. ```text abc _abc abc_ a1b2c3 a_b_c a1_b2_c3 仓颉 __こんにちは ``` -------------------------------- ### Timer with Delay CatchupStyle Example Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/sync/sync_package_api/sync_package_enums.md Demonstrates creating a timer that executes a task 3 times, starting 1 second after creation with a 1-second interval, using the Delay catchup strategy. This ensures a fixed delay between task completions. ```cangjie import std.sync.{Timer, CatchupStyle} import std.time.{MonoTime} main() { let start = MonoTime.now() Timer.repeatTimes(3, Duration.second, Duration.second, {=> println("Tick at: ${MonoTime.now() - start}") }, style: Delay) sleep(Duration.second * 4) 0 } ``` -------------------------------- ### Workspace Configuration Example Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/tools/source_zh_cn/tools/cjpm_manual_cjnative_community.md Defines a workspace with multiple local modules, specifying which modules to build and test, common compile/override options, and a custom target directory. ```toml [workspace] members = ["aoo", "boo", "coo"] build-members = ["aoo", "boo"] test-members = ["aoo"] compile-option = "-Woff all" override-compile-option = "-O2" [dependencies] xoo = { path = "path_xoo" } [ffi.c] abc = { path = "libs" } ``` -------------------------------- ### Example Link-Option Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/tools/source_zh_cn/tools/cjpm_manual_cjnative_community.md Passes compilation options to the linker, useful for security-related compile commands. ```toml link-option = "-z noexecstack -z relro -z now --strip-all" ``` -------------------------------- ### InstancePropertyInfo.getValue Method Example Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/reflect/reflect_package_api/reflect_package_classes.md Demonstrates how to get the value of an instance member property from a given instance. Note that struct instances are not currently supported for the 'instance' parameter. Throws IllegalTypeException if the runtime type of the instance does not strictly match the type of the property. ```cangjie import std.reflect.* public class Rectangular { public var length = 4 public prop width: Int64 { get() { 5 } } } main(): Unit { // 此处是通过 Rectangular 的类型的限定名称获取 ClassTypeInfo,也可以通过实例获取 ClassTypeInfo let ty = ClassTypeInfo.get("default.Rectangular") // 获取 InstancePropertyInfo var gip = ty.getInstanceProperty("width") // 获取实例值 var r = Rectangular() var result = gip.getValue(r) as Int64 println(result) return } ``` -------------------------------- ### Get Match Position by Group Index - Regex MatchData Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/regex/regex_package_api/regex_package_structs.md Retrieves the start and end indices for a specific capture group within the last match. Requires the group index as an argument. An IllegalArgumentException is thrown if the group is invalid or capture groups are not enabled. ```cangjie public func matchPosition(group: Int64): Position ``` -------------------------------- ### Configure Environment Variables for Shell Startup Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/manual/source_zh_cn/first_understanding/install_Community.md Add the source command to your shell's initialization file (e.g., .bashrc or .zshrc) to automatically configure the Cangjie toolchain environment variables when a new shell session starts. Replace '/home/user/cangjie' with the actual installation path. ```shell # 假设仓颉安装包解压在 /home/user/cangjie 中 source /home/user/cangjie/envsetup.sh # 即 envsetup.sh 的绝对路径 ``` -------------------------------- ### Run Cangjie envsetup.bat (CMD) Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/manual/source_zh_cn/first_understanding/install_Community.md Execute this script in the Windows Command Prompt (CMD) to set up the Cangjie environment for the current session. ```bash path\to\cangjie\envsetup.bat ``` -------------------------------- ### UNIX Socket Server and Client Example Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/net/net_samples/unix.md This example shows a complete UNIX domain socket communication flow. It includes setting up a server to listen for connections, accepting a client, sending a message, and a client connecting to the server, receiving the message, and printing it. Ensure the socket path is accessible and unique. ```cangjie import std.net.* import std.sync.* import std.fs.* let SOCKET_PATH = "/tmp/tmpsock" let barrier = Barrier(2) func runUnixServer() { remove(SOCKET_PATH) try (serverSocket = UnixServerSocket(bindAt: SOCKET_PATH)) { serverSocket.bind() barrier.wait() try (client = serverSocket.accept()) { client.write("hello".toArray()) } } } main(): Int64 { let fut = spawn { runUnixServer() } barrier.wait() try (socket = UnixSocket(SOCKET_PATH)) { socket.connect() let buf = Array(10, repeat: 0) socket.read(buf) println(String.fromUtf8(buf)) // hello } fut.get() return 0 } ``` ```text hello ``` -------------------------------- ### Get Match Position by Named Group - Regex MatchData Source: https://github.com/yolomao/cangjiecorpus-mirror/blob/main/libs/std/regex/regex_package_api/regex_package_structs.md Retrieves the start and end indices for a specific named capture group within the last match. Requires the group name as a String argument. An IllegalArgumentException is thrown if the group name does not exist or capture groups are not enabled. ```cangjie public func matchPosition(group: String): Position ```