### Cangjie HTTP Client and Server Example Source: https://docs.cangjie-lang.cn/docs/1.0.0/user_manual/source_zh_cn/Net/net_http.html This example demonstrates setting up an HTTP server that responds to a GET /hello request with 'Hello Cangjie!', and a client that sends this request and prints the response. Ensure the `net` and `log` packages are downloaded and configured in `cjpm.toml`. ```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() } ``` -------------------------------- ### Start a Process and Get Instance Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/process/process_package_api/process_package_classes.html Creates and starts a child process, returning a `SubProcess` instance. Requires subsequent calls to `wait` or `waitOutput` to prevent zombie processes. Deprecated; use `launch` instead. ```Cangjie public static func start(command: String, arguments: Array, workingDirectory!: ?Path = None, environment!: ?Map = None, stdIn!: ProcessRedirect = Inherit, stdOut!: ProcessRedirect = Inherit, stdErr!: ProcessRedirect = Inherit): SubProcess ``` -------------------------------- ### Install Local Project Source: https://docs.cangjie-lang.cn/docs/1.0.0/tools/source_zh_cn/tools/cjpm_manual_cjnative_community.html Installs a project from a local path. Ensure the project is compiled before installation. ```bash cjpm install --path path/to/project # 从本地路径 path/to/project 中安装 ``` -------------------------------- ### Example: Invoking Instance Function via Reflection Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/reflect/reflect_package_api/reflect_package_classes.html Demonstrates how to get ClassTypeInfo, find an InstanceFunctionInfo for 'area', and then apply it to an instance of Rectangular. Requires importing std.reflect. ```Go import std.reflect.* public class Rectangular { public var length = 4 public var width = 5 public func area(): Int64 { return length * width } } main(): Unit { // 此处是通过 Rectangular 的类型的限定名称获取 ClassTypeInfo,也可以通过实例获取 ClassTypeInfo let ty = ClassTypeInfo.get("default.Rectangular") // 获取 InstanceFunctionInfo var gif = ty.getInstanceFunction("area") // 调用反射函数 var r = Rectangular() var result = gif.apply(r) as Int64 println(result) return } ``` -------------------------------- ### Install Git Project Source: https://docs.cangjie-lang.cn/docs/1.0.0/tools/source_zh_cn/tools/cjpm_manual_cjnative_community.html Installs a project directly from a Git repository URL. The project will be compiled and installed. ```bash cjpm install --git url # 从 git 对应地址安装 ``` -------------------------------- ### Output of Instance and Static Properties Example Source: https://docs.cangjie-lang.cn/docs/1.0.0/user_manual/source_zh_cn/class_and_interface/prop.html Shows the output when accessing instance and static properties defined in the preceding example. ```text 123 321 ``` -------------------------------- ### Bench Command Usage Examples Source: https://docs.cangjie-lang.cn/docs/1.0.0/tools/source_zh_cn/tools/cjpm_manual_cjnative_community.html Examples demonstrating the usage of the `cjpm bench` command with different arguments and package paths. ```bash cjpm bench ``` ```bash cjpm bench src ``` ```bash cjpm bench src --filter=* ``` ```bash cjpm bench src --report-format=csv ``` -------------------------------- ### Timer.once Example Output Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/sync/sync_package_api/sync_package_classes.html Example output for the Timer.once demonstration. ```text Tick at: 1s2ms74us551ns ``` -------------------------------- ### Importing all public items from a package (example) Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/std_module_overview.html An example demonstrating how to import all public items from the 'std.collection' package. ```cangjie import std.collection.* ``` -------------------------------- ### Linux Target Configuration Example Source: https://docs.cangjie-lang.cn/docs/1.0.0/tools/source_zh_cn/tools/cjpm_manual_cjnative_community.html Example of configuring compile, link, and dependency options for a specific target, such as x86_64-unknown-linux-gnu on Linux. ```toml [target.x86_64-unknown-linux-gnu] # Linux 系统的配置项 compile-option = "value1" # 额外编译命令选项 override-compile-option = "value2" # 额外全局编译命令选项 link-option = "value3" # 链接器透传选项 [target.x86_64-unknown-linux-gnu.dependencies] # 源码依赖配置项 [target.x86_64-unknown-linux-gnu.test-dependencies] # 测试阶段依赖配置项 [target.x86_64-unknown-linux-gnu.bin-dependencies] # 仓颉二进制库依赖 path-option = ["./test/pro0", "./test/pro1"] [target.x86_64-unknown-linux-gnu.bin-dependencies.package-option] "pro0.xoo" = "./test/pro0/pro0.xoo.cjo" "pro0.yoo" = "./test/pro0/pro0.yoo.cjo" "pro1.zoo" = "./test/pro1/pro1.zoo.cjo" [target.x86_64-unknown-linux-gnu.debug] # Linux 系统的 debug 配置项 [target.x86_64-unknown-linux-gnu.debug.test-dependencies] [target.x86_64-unknown-linux-gnu.release] # Linux 系统的 release 配置项 [target.x86_64-unknown-linux-gnu.release.bin-dependencies] ``` -------------------------------- ### Using Unittest Options with Configuration Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/unittest_testmacro/unittest_testmacro_package_api/unittest_testmacro_package_macros.html Demonstrates how to set and get a registered unittest option using the `Configuration` class. This example shows basic usage with a string option. ```unittest @UnittestOption[String](opt) @Test func test_that_derived_type_overwrite_parent_type_value_in_configuration() { let conf = Configuration() conf.set(KeyOpt.opt, "a") let value = conf.get(KeyOpt.opt).getOrThrow() @PowerAssert(value == "a") } ``` -------------------------------- ### Install Dependencies on Ubuntu 18.04/20.04 (Older GCC) Source: https://docs.cangjie-lang.cn/docs/1.0.0/user_manual/source_zh_cn/Appendix/linux_toolchain_install.html Installs binutils, libc-dev, libstdc++-dev, and libgcc-7-dev using apt-get. OpenSSL 3 must be installed separately. ```bash $ apt-get install \ binutils \ libc-dev \ libc++-dev \ libgcc-7-dev ``` -------------------------------- ### Install Dependencies on Ubuntu 18.04/20.04 (Newer GCC) Source: https://docs.cangjie-lang.cn/docs/1.0.0/user_manual/source_zh_cn/Appendix/linux_toolchain_install.html Installs binutils, libc-dev, libstdc++-dev, and libgcc-9-dev using apt-get. OpenSSL 3 must be installed separately. ```bash $ apt-get install \ binutils \ libc-dev \ libc++-dev \ libgcc-9-dev ``` -------------------------------- ### Token Construction Examples Source: https://docs.cangjie-lang.cn/docs/1.0.0/user_manual/source_zh_cn/Macro/Tokens_types_and_quote_expressions.html Provides examples of creating `Token` objects for operators, keywords, identifiers, and 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") // 字符串字面量 ``` -------------------------------- ### startCPUProfiling Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/runtime/runtime_package_api/runtime_package_funcs.html Starts CPU profiler tracing. ```APIDOC ## startCPUProfiling ### Description Starts CPU profiler tracing. ### Exceptions - **ProfilingInfoException** - `startCPUProfiling` and `stopCPUProfiling(Path)` must be called in pairs. If `startCPUProfiling` is called again without a corresponding `stopCPUProfiling(Path)` call, this exception is thrown. ``` -------------------------------- ### Timer.repeat Example Output Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/sync/sync_package_api/sync_package_classes.html Example output for the Timer.repeat demonstration. ```text Tick at: 1s2ms72us188ns Tick at: 2s4ms185us160ns Tick at: 3s6ms275us464ns Tick at: 4s8ms18us399ns Tick at: 5s9ms621us394ns ``` -------------------------------- ### CJPM Target Configuration Example Source: https://docs.cangjie-lang.cn/docs/1.0.0/tools/source_zh_cn/tools/cjpm_manual_cjnative_community.html Demonstrates a complex CJPM TOML configuration with package, dependencies, and target-specific settings for different platforms and build modes. This example illustrates how compile-option, link-option, and dependencies are merged based on priority. ```toml [package] compile-option = "compile-0" override-compile-option = "override-compile-0" link-option = "link-0" [dependencies] dep0 = { path = "./dep0" } [test-dependencies] devDep0 = { path = "./devDep0" } [target.x86_64-unknown-linux-gnu] compile-option = "compile-1" override-compile-option = "override-compile-1" link-option = "link-1" [target.x86_64-unknown-linux-gnu.dependencies] dep1 = { path = "./dep1" } [target.x86_64-unknown-linux-gnu.test-dependencies] devDep1 = { path = "./devDep1" } [target.x86_64-unknown-linux-gnu.bin-dependencies] path-option = ["./test/pro1"] [target.x86_64-unknown-linux-gnu.bin-dependencies.package-option] "pro1.xoo" = "./test/pro1/pro1.xoo.cjo" [target.x86_64-unknown-linux-gnu.debug] compile-option = "compile-2" override-compile-option = "override-compile-2" link-option = "link-2" [target.x86_64-unknown-linux-gnu.debug.dependencies] dep2 = { path = "./dep2" } [target.x86_64-unknown-linux-gnu.debug.test-dependencies] devDep2 = { path = "./devDep2" } [target.x86_64-unknown-linux-gnu.debug.bin-dependencies] path-option = ["./test/pro2"] [target.x86_64-unknown-linux-gnu.debug.bin-dependencies.package-option] "pro2.xoo" = "./test/pro2/pro2.xoo.cjo" ``` -------------------------------- ### DataStrategyProcessor start Static Method (DataStrategy) Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/unittest/unittest_package_api/unittest_package_classes.html The starting point for combining and mapping DataStrategy. ```APIDOC ## start Static Method (DataStrategy) ### Description The starting point for combining and mapping DataStrategy. ### Parameters * `s`: DataStrategy - The data strategy. * `name`: String - The name of the test case. ### Returns * `SimpleProcessor` - The test case processor. ``` -------------------------------- ### Scan Dependency Output Example Source: https://docs.cangjie-lang.cn/docs/1.0.0/user_manual/source_zh_cn/Appendix/compile_options.html Example JSON output from the `--scan-dependency` command, detailing package information and its dependencies. ```json { "package": "pkgA", "isMacro": true, "dependencies": [ { "package": "pkgB", "isStd": false, "imports": [ { "file": "pkgA/pkgA.cj", "begin": { "line": 2, "column": 1 }, "end": { "line": 2, "column": 14 } } ] }, { "package": "pkgB.subB", "isStd": false, "imports": [ { "file": "pkgA/pkgA.cj", "begin": { "line": 4, "column": 1 }, "end": { "line": 4, "column": 19 } } ] }, { "package": "std.io", "isStd": true, "imports": [ { "file": "pkgA/pkgA.cj", "begin": { "line": 3, "column": 1 }, "end": { "line": 3, "column": 16 } } ] } ] } ``` -------------------------------- ### Install Dependencies on SUSE Linux Enterprise Server Source: https://docs.cangjie-lang.cn/docs/1.0.0/user_manual/source_zh_cn/Appendix/linux_toolchain_install.html Installs binutils, glibc-devel, and gcc-c++ using the zypper package manager. OpenSSL 3 must be installed separately. ```bash $ zypper install \ binutils \ glibc-devel \ gcc-c++ ``` -------------------------------- ### Output of Variadic Parameter Examples Source: https://docs.cangjie-lang.cn/docs/1.0.0/user_manual/source_zh_cn/function/function_call_desugar.html This snippet shows the expected output for the variadic parameter examples. ```text 0 6 ``` ```text 2 5 ``` ```text array: [] item: 1 array: [1, 2] ``` -------------------------------- ### Install OpenSSL 3 to System Directory Source: https://docs.cangjie-lang.cn/docs/1.0.0/user_manual/source_zh_cn/Appendix/linux_toolchain_install.html Installs the compiled OpenSSL to the system directory. Root privileges may be required. Alternatively, use 'make install' if a custom --prefix was specified during configuration. ```bash $ make install ``` ```bash $ sudo make install ``` -------------------------------- ### DataStrategyProcessor start Static Method (Closure returning DataStrategyProcessor with Int64) Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/unittest/unittest_package_api/unittest_package_classes.html The starting point for combining and mapping DataStrategy. ```APIDOC ## start Static Method (Closure returning DataStrategyProcessor with Int64) ### Description The starting point for combining and mapping DataStrategy. ### Parameters * `s`: () -> DataStrategyProcessor - A closure that generates a data strategy processor. * `name`: String - The name of the test case. * `x!`: Int64 = 0 - Parameter added for refactoring to achieve different return values. ### Returns * `DataStrategyProcessor` where U <: BenchInputProvider - The data strategy processor. ``` -------------------------------- ### DataStrategyProcessor start Static Method (Closure returning DataStrategy with Int64) Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/unittest/unittest_package_api/unittest_package_classes.html The starting point for combining and mapping DataStrategy. ```APIDOC ## start Static Method (Closure returning DataStrategy with Int64) ### Description The starting point for combining and mapping DataStrategy. ### Parameters * `s`: () -> DataStrategy - A closure that generates a data strategy. * `name`: String - The name of the test case. * `x!`: Int64 = 0 - Parameter added for refactoring to achieve different return values. ### Returns * `SimpleProcessor` - The test case processor. ``` -------------------------------- ### Importing specific collection items (example) Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/std_module_overview.html An example showing how to import multiple specific items like ArrayList and HashMap from the std.collection package. ```cangjie import std.collection.{ArrayList, HashMap} ``` -------------------------------- ### Example: Thread Synchronization with Condition Source: https://docs.cangjie-lang.cn/docs/1.0.0/user_manual/source_zh_cn/concurrency/sync.html A complete example demonstrating thread synchronization using a Mutex and Condition. It shows a main thread signaling a spawned thread to proceed after a condition is met. ```Cangjie import std.sync.* import std.time.* let mtx = Mutex() let condition = synchronized(mtx) { mtx.condition() } var flag: Bool = true main(): Int64 { let fut = spawn { mtx.lock() while (flag) { println("New thread: before wait") condition.wait() println("New thread: after wait") } mtx.unlock() } // Sleep for 10ms, to make sure the new thread can be executed. sleep(10 * Duration.millisecond) mtx.lock() println("Main thread: set flag") flag = false mtx.unlock() mtx.lock() println("Main thread: notify") condition.notifyAll() mtx.unlock() // wait for the new thread finished. fut.get() return 0 } ``` -------------------------------- ### DataStrategyProcessor start Static Method (Closure returning DataStrategyProcessor) Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/unittest/unittest_package_api/unittest_package_classes.html The starting point for combining and mapping DataStrategy. ```APIDOC ## start Static Method (Closure returning DataStrategyProcessor) ### Description The starting point for combining and mapping DataStrategy. ### Parameters * `s`: () -> DataStrategyProcessor - A closure that generates a data strategy processor. * `name`: String - The name of the test case. ### Returns * `DataStrategyProcessor` - The data strategy processor. ``` -------------------------------- ### Install Dependencies on CentOS/RHEL/Fedora (Older GCC) Source: https://docs.cangjie-lang.cn/docs/1.0.0/user_manual/source_zh_cn/Appendix/linux_toolchain_install.html Installs binutils, glibc-devel, libstdc++-devel, and gcc using yum. OpenSSL 3 must be installed separately. ```bash $ yum install \ binutils \ glibc-devel \ libstdc++-devel \ gcc \ ``` -------------------------------- ### Performance Test Output Example Source: https://docs.cangjie-lang.cn/docs/1.0.0/tools/source_zh_cn/tools/cjpm_manual_cjnative_community.html Example output from the `cjpm bench` command, showing test case results, timing, and summary statistics. ```text 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 -------------------------------------------------------------------------------------------------- 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 ``` -------------------------------- ### Perf Setup Method Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/unittest/unittest_package_api/unittest_package_structs.html Initialization routine for this CPU counter. Called before each benchmark step. ```swift func setup() ``` -------------------------------- ### Get InterfaceTypeInfo Example Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/reflect/reflect_package_api/reflect_package_classes.html Demonstrates how to get and print the InterfaceTypeInfo for a given qualified name. ```swift __ import std.reflect.* public interface Rectangular {} main(): Unit { let ty = InterfaceTypeInfo.get("default.Rectangular") println(ty) return } ``` ```text __ default.Rectangular ``` -------------------------------- ### Example: Get Address Bytes Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/net/net_package_api/net_package_classes.html Demonstrates how to get the raw byte representation of a UnixSocketAddress and assert its correctness. ```C++ __ import std.net.* import std.unittest.* import std.unittest.testmacro.* main () { let udsa1_1: UnixSocketAddress = UnixSocketAddress("/tmp/server1.sock") @Assert(udsa1_1.getAddressBytes(), "\u{1}\u{0}/tmp/server1.sock".toArray()) } ``` -------------------------------- ### Directory and File Operations with Path Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/fs/fs_samples/path_samples.html This example demonstrates creating directories and files using Path instances. It also shows how to join path components and canonicalize paths to their absolute and normalized forms. ```Cangjie import std.fs.* main() { let dirPath: Path = Path("./a/b/c") if (!exists(dirPath)) { Directory.create(dirPath, recursive: true) } let filePath: Path = dirPath.join("d.cj") // ./a/b/c/d.cj if (filePath == Path("./a/b/c/d.cj")) { println("filePath.join: success") } if (!exists(filePath)) { File.create(filePath).close() } let curCanonicalizedPath: Path = canonicalize(Path(".")) let fileCanonicalizedPath: Path = canonicalize(Path("././././a/./../a/b/../../a/b/c/.././../../a/b/c/d.cj")) if (fileCanonicalizedPath == canonicalize(filePath) && fileCanonicalizedPath.toString() == curCanonicalizedPath.toString() + "/a/b/c/d.cj") { println("canonicalize filePath: success") } remove(dirPath, recursive: true) return 0 } ``` -------------------------------- ### Macro Call Example Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/ast/ast_samples/report.html Demonstrates how to call the 'testDef' macro with different inputs. This example shows the usage of macros defined in another file. ```Cangjie // macro_call.cj package macro_calling import std.ast.* import macro_definition.* main(): Int64 { let a = @testDef(1) let b = @testDef(a) let c = @testDef(1 + a) return 0 } ``` -------------------------------- ### Get OS Environment Info with POSIX Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/posix/posix_samples/posix_get_os_envinfo_samples.html This snippet shows how to get system name, hostname, login name, change directory, get current directory, and retrieve group IDs. It requires importing the 'std.posix' module. Note that these functions are not supported on Windows. ```D import std.posix.* main(): Int64 { /* 系统名称相关 */ var os_info = getos() println("os info ==> ${os_info}") var hostname = gethostname() println("hostname ==> ${hostname}") var logname: String = getlogin() println("logname ==> ${logname}") /* 程序运行路径相关函数 */ var changePath = "/" var chdir_result = chdir(changePath) println("chdir_result ==> ${chdir_result}") var cwd_path: String = getcwd() println("cwd_path ==> ${cwd_path}") /* 系统 id 相关函数 getpgid */ var arr: CString = unsafe { LibC.mallocCString(" ") } var a: CPointer = arr.getChars() var cp: CPointer = CPointer(a) var getg = unsafe{ getgroups(0, cp)} var s: String = " " for (_ in 0..getg) { s = s + "\0" } println(getg) var local: UInt32 = 0 for (temp in 0..getg) { unsafe { local = cp.read(Int64(temp)) } println("getgroups ==> ${local.toString()}") } unsafe { LibC.free(arr)} return 0 } ``` -------------------------------- ### CpuCycles Setup Method Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/unittest/unittest_package_api/unittest_package_structs.html Configuration action performed before measurement. ```swift public func setup() ``` -------------------------------- ### Example: Get and Print Static Property Value Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/reflect/reflect_package_api/reflect_package_classes.html Demonstrates how to obtain `ClassTypeInfo` for a class, retrieve a static property by name, and then get and print its value. This example assumes the static property is of type `Int64` and prints the result wrapped in `Some`. ```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 } ``` -------------------------------- ### Get ArrayList Size Source: https://docs.cangjie-lang.cn/docs/1.0.0/user_manual/source_zh_cn/collections/collection_arraylist.html Use the 'size' property to get the number of elements in an ArrayList. This example checks if the list is empty. ```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}") } } ``` -------------------------------- ### DataStrategyProcessor start Static Method (Closure returning DataStrategy) Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/unittest/unittest_package_api/unittest_package_classes.html The starting point for combining and mapping DataStrategy. ```APIDOC ## start Static Method (Closure returning DataStrategy) ### Description The starting point for combining and mapping DataStrategy. ### Parameters * `f`: () -> DataStrategy - A closure that generates a data strategy. * `name`: String - The name of the test case. ### Returns * `DataStrategyProcessor` where U <: BenchInputProvider - The data strategy processor. ``` -------------------------------- ### Start CPU Profiling Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/runtime/runtime_package_api/runtime_package_funcs.html Starts the CPU profiler trace. Must be paired with a call to stopCPUProfiling(Path). Throws ProfilingInfoException if called again without stopping. ```cangjie public func startCPUProfiling(): Unit ``` -------------------------------- ### Get Process Start Time Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/process/process_package_api/process_package_classes.html Retrieves the start time of a process as a DateTime object. Returns DateTime.UnixEpoch if retrieval fails. ```cangjie public prop startTime: DateTime ``` -------------------------------- ### POSIX Process Operations Example Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/posix/posix_samples/posix_process_samples.html Demonstrates `nice`, `kill`, `killpg`, and `isatty` functions for process management. This code is not compatible with Windows. ```d 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 } ``` -------------------------------- ### Getting HashMap Size Source: https://docs.cangjie-lang.cn/docs/1.0.0/user_manual/source_zh_cn/collections/collection_hashmap.html Use the 'size' property to get the number of elements in a HashMap. This example checks if the map is empty or prints its size. ```Cangjie import std.collection.* main() { let map = HashMap([("a", 0), ("b", 1), ("c", 2)]) if (map.size == 0) { println("This is an empty hashmap") } else { println("The size of hashmap is ${map.size}") } } ``` -------------------------------- ### Output of the Simple Property Example Source: https://docs.cangjie-lang.cn/docs/1.0.0/user_manual/source_zh_cn/class_and_interface/prop.html This shows the expected console output when the property getter and setter are invoked in the preceding example. ```text get set ``` -------------------------------- ### slice(start: Int64, len: Int64) Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/core/core_package_api/core_package_structs.html Gets a slice of the array. The slice is a reference to the original data, not a copy. Parameters `start` and `len` must be positive, and `start + len` must not exceed the array's length. ```APIDOC ## slice(start: Int64, len: Int64) ### Description Gets a slice of the array. The slice is a reference to the original data, not a copy. Parameters `start` and `len` must be positive, and `start + len` must not exceed the array's length. ### Parameters #### Path Parameters - **start** (Int64) - Required - The starting position of the slice. Must be greater than 0, and start + len must be less than or equal to the current Array instance's length. - **len** (Int64) - Required - The length of the slice. Must be greater than 0. ### Returns - **Array** - The sliced array. ### Throws - **IndexOutOfBoundsException** - If parameters do not meet the specified range requirements. ``` -------------------------------- ### 无参数的 main 函数 Source: https://docs.cangjie-lang.cn/docs/1.0.0/user_manual/source_zh_cn/package/entry.html 定义一个没有参数的 `main` 函数,返回类型为 `Int64`。这是程序执行的入口点。 ```仓颉 // main.cj main(): Int64 { // Ok. return 0 } ``` -------------------------------- ### Get Element Example Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/core/core_package_api/core_package_structs.html Shows how to safely retrieve an element from an array using its index. ```cangjie main() { let arr = [0, 1, 2] let num = arr.get(0) println(num) } ``` -------------------------------- ### Timer with Delay CatchupStyle Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/sync/sync_package_api/sync_package_enums.html Example of creating a timer that executes a task 3 times, starting after 1 second and repeating every second, using the Delay catchup style. This ensures a fixed interval between the start of consecutive tasks. ```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 } ``` -------------------------------- ### Creating and Verifying Directory and File Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/fs/fs_samples/path_samples.html This snippet demonstrates the creation of a directory and a file within that directory using Path objects. It also includes checks to verify their existence 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 } ``` -------------------------------- ### Get Region Settings Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/regex/regex_package_api/regex_package_classes.html Returns the current region settings (start and end indices) for the matcher's search area. ```swift public func region(): Position ``` -------------------------------- ### Example of Combined Build Output Structure Source: https://docs.cangjie-lang.cn/docs/1.0.0/tools/source_zh_cn/tools/cjpm_manual_cjnative_community.html Illustrates the file structure after applying the 'combined' build profile, showing the main dynamic library and static libraries for sub-packages, along with their corresponding CJO files. ```text |-- libdemo.so |-- libdemo.aoo.a |-- libdemo.boo.a |-- demo.cjo |-- demo.aoo.cjo |-- demo.boo.cjo ``` -------------------------------- ### Getting HashSet Size Source: https://docs.cangjie-lang.cn/docs/1.0.0/user_manual/source_zh_cn/collections/collection_hashset.html The 'size' property returns the number of elements in the HashSet. This example checks if the set is empty or prints its size. ```Cangjie import std.collection.* main() { let mySet = HashSet([0, 1, 2]) if (mySet.size == 0) { println("This is an empty hashset") } else { println("The size of hashset is ${mySet.size}") } } ``` -------------------------------- ### Generate Random Boolean Value Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/random/random_package_api/random_package_classes.html Retrieves a pseudo-random boolean value. This example shows how to create a Random object and get a boolean. ```cangjie import std.random.* main() { let m: Random = Random() let n: Bool = m.nextBool() println("n=${n is Bool}") return 0 } ``` -------------------------------- ### Wildcard Example 1: Function Name Matching Source: https://docs.cangjie-lang.cn/docs/1.0.0/user_manual/source_zh_cn/Appendix/compile_options.html Demonstrates using wildcards in obfuscation rules to match function names. This example shows how '?' can match a single character in the function name. ```plaintext __ obf-cf-flatten pro?.myfunc() ``` -------------------------------- ### Multi-line Ignore Correct Example 3 Source: https://docs.cangjie-lang.cn/docs/1.0.0/tools/source_zh_cn/tools/cjlint_manual.html Demonstrates multi-line ignore using a block comment for the start directive, suppressing G.CHK.04. ```c /** * cjlint-ignore -start !G.CHK.04 description */ void fetctl_process(const void *para) { if (para == NULL) { return; } } // cjlint-ignore -end description ``` -------------------------------- ### Get Process Command Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/env/env_package_api/env_package_funcs.html Retrieves the command used to start the current process. Throws EnvException if the process does not exist or is a zombie process. ```cangjie public func getCommand(): String ``` -------------------------------- ### Console Input/Output Example Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/env/env_samples/env_sample.html Shows how to read user input from stdin and write it back to stdout. This is useful for creating interactive command-line applications. ```Cangjie import std.env.* main() { getStdOut().write("请输入信息1:") var c = getStdIn().readln() // 输入:你好,请问今天星期几? var r = c.getOrThrow() getStdOut().writeln("输入的信息1为:" + r) getStdOut().write("请输入信息2:") c = getStdIn().readln() // 输入:你好,请问今天几号? r = c.getOrThrow() getStdOut().writeln("输入的信息2为:" + r) return } ``` -------------------------------- ### Get Forward Iterator Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/collection/collection_package_api/collection_package_class.html Obtains an iterator starting from the first element greater than or equal to a specified mark. The inclusivity of the mark element can be controlled. ```swift public func forward(mark: T, inclusive!: Bool = true): Iterator ``` -------------------------------- ### Main Project Configuration File Source: https://docs.cangjie-lang.cn/docs/1.0.0/tools/source_zh_cn/tools/cjpm_manual_cjnative_community.html Example 'cjpm.toml' for the main project ('test'), specifying package details, Cangjie compiler version, and external dependencies like 'pro0'. ```toml // cj_project/cjpm.toml [package] cjc-version = "0.40.2" description = "nothing here" version = "1.0.0" name = "test" output-type = "executable" [dependencies] pro0 = { path = "pro0" } ``` -------------------------------- ### Valid Normal Identifiers Source: https://docs.cangjie-lang.cn/docs/1.0.0/user_manual/source_zh_cn/basic_programming_concepts/identifier.html Examples of valid normal identifiers in Cangjie. These follow rules based on Unicode XID_Start and XID_Continue characters, or start with an underscore. ```cangjie abc _abc abc_ a1b2c3 a_b_c a1_b2_c3 仓颉 こんにちは ``` -------------------------------- ### 在 Windows 环境下运行仓颉原生应用 Source: https://docs.cangjie-lang.cn/docs/1.0.0/user_manual/source_zh_cn/deploy_and_run/run_cjnative.html 在 Windows 环境下,将编译好的可执行文件 `main.exe` 拷贝到运行环境中并执行。 ```batch .\main.exe ``` -------------------------------- ### Invalid Normal Identifiers Source: https://docs.cangjie-lang.cn/docs/1.0.0/user_manual/source_zh_cn/basic_programming_concepts/identifier.html Examples of invalid normal identifiers in Cangjie. These are invalid because they use characters not allowed by XID_Continue, start with a digit, are just an underscore, or are reserved keywords. ```cangjie ab&c // & 不是 XID_Continue 字符 3abc // 阿拉伯数字不是 XID_Start 字符,因此,数字不能作为起始字符 _ // _ 后至少需要有一个 XID_Continue 字符 while // while 是仓颉关键字,普通标识符不能使用仓颉关键字 ``` -------------------------------- ### Get ClassTypeInfo for a Class Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/reflect/reflect_package_api/reflect_package_classes.html Retrieves the ClassTypeInfo for a given class using its fully qualified name. This is the primary way to start inspecting a class's metadata. ```Go package test import std.reflect.* public class Rectangular { public var myName = "" public init() {} public init(name: String) { myName = name } } main(): Unit { // 此处是通过 Rectangular 的类型的限定名称获取 ClassTypeInfo,也可以通过实例获取 ClassTypeInfo let ty = ClassTypeInfo.get("test.Rectangular") // 获取 constructors for (i in ty.constructors) { println(i) } return } ``` -------------------------------- ### Trim Start with String Set Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/core/core_package_api/core_package_structs.html Trims the current string by removing Runes from the start that are present in the provided string set, until the first Rune not in the set is encountered. For example, "12241".trimStart("12") results in "41". Returns the trimmed string. ```cangjie public func trimStart(set: String): String ``` -------------------------------- ### TCP Server and Client Example Source: https://docs.cangjie-lang.cn/docs/1.0.0/user_manual/source_zh_cn/Net/net_socket.html Demonstrates a basic TCP server that accepts a connection, reads data, and a client that connects and sends data. Ensure the server port is correctly set and accessible. ```Cangjie import std.time.* import std.sync.* import std.net.* var SERVER_PORT: UInt16 = 0 func runTcpServer() { try (serverSocket = TcpServerSocket(bindAt: SERVER_PORT)) { serverSocket.bind() SERVER_PORT = (serverSocket.localAddress as IPSocketAddress)?.port ?? 0 try (client = serverSocket.accept()) { let buf = Array(10, repeat: 0) let count = client.read(buf) // 服务端读取到的数据为: [1, 2, 3, 0, 0, 0, 0, 0, 0, 0] println("Server read ${count} bytes: ${buf}") } } } main(): Int64 { let future = spawn { runTcpServer() } sleep(Duration.millisecond * 500) try (socket = TcpSocket("127.0.0.1", SERVER_PORT)) { socket.connect() socket.write([1, 2, 3]) } future.get() return 0 } ``` -------------------------------- ### Trim Start with Rune Set Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/core/core_package_api/core_package_structs.html Trims the current string by removing Runes from the start that are present in the provided set, until the first Rune not in the set is encountered. For example, "12241".trimStart([r'1', r'2']) results in "41". Returns the trimmed string. ```cangjie public func trimStart(set: Array): String ``` -------------------------------- ### Conditional Compilation based on OS (Linux/Windows) Source: https://docs.cangjie-lang.cn/docs/1.0.0/user_manual/source_zh_cn/compile_and_build/conditional_compilation.html This example shows how to use `os == "Linux"` and `os == "Windows"` to define platform-specific functions. It also demonstrates using `os != "Windows"` and `os != "Linux"` for inverse conditions. ```Cangjie @When[os == "Linux"] func foo() { print("Linux, ") } @When[os == "Windows"] func foo() { print("Windows, ") } @When[os != "Windows"] func fee() { println("NOT Windows") } @When[os != "Linux"] func fee() { println("NOT Linux") } main() { foo() fee() } ``` -------------------------------- ### Get Element by Index Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/collection/collection_package_api/collection_package_class.html Retrieves the element at a specified index in the ArrayList. Returns None if the index is out of bounds. See ArrayList's get/set functions for usage examples. ```cangjie __ public func get(index: Int64): ?T ``` -------------------------------- ### BufferedInputStream Construction and Reading Source: https://docs.cangjie-lang.cn/docs/1.0.0/user_manual/source_zh_cn/Basic_IO/basic_IO_process_stream.html Demonstrates how to construct a BufferedInputStream with a ByteBuffer and read data from it. Ensure the io package is imported. ```Cangjie import std.io.{ByteBuffer, BufferedInputStream} main(): Unit { let arr1 = "0123456789".toArray() let byteBuffer = ByteBuffer() byteBuffer.write(arr1) let bufferedInputStream = BufferedInputStream(byteBuffer) let arr2 = Array(20, repeat: 0) /* 读取流中数据,返回读取到的数据的长度 */ let readLen = bufferedInputStream.read(arr2) println(String.fromUtf8(arr2[..readLen])) // 0123456789 } ``` -------------------------------- ### Handling Inheritance with Unittest Options Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/unittest_testmacro/unittest_testmacro_package_api/unittest_testmacro_package_macros.html Illustrates how the `Configuration` class correctly handles inheritance when setting and getting options. This example shows overriding parent types with derived types. ```unittest open class Base { public open func str() { "Base" } } class Derived <: Base { public func str() { "Derived" } } @UnittestOption[Base](opt) @Test func test_that_derived_type_overwrite_parent_type_value_in_configuration() { let conf = Configuration() conf.set(KeyOpt.opt, Base()) let first = conf.get(KeyOpt.opt).getOrThrow() @PowerAssert(first.str() == "Base") conf.set(KeyOpt.opt, Derived()) let second = conf.get(KeyOpt.opt).getOrThrow() @PowerAssert(second.str() == "Derived") } ``` -------------------------------- ### Initialize VArray with Constructors Source: https://docs.cangjie-lang.cn/docs/1.0.0/user_manual/source_zh_cn/basic_data_type/array.html Demonstrates initializing VArrays using two constructor functions: one that takes an initialization function for each element, and another that repeats a single initial element. ```Cangjie // VArray(initElement: (Int64) -> T) let b = VArray({ i => i }) // [0, 1, 2, 3, 4] // VArray(repeat!: T) let c = VArray(repeat: 0) // [0, 0, 0, 0, 0] ``` -------------------------------- ### Convert IPv6Address to IPv4 Mapped IPv4Address Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/net/net_package_api/net_package_classes.html Converts this 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. ```swift __ public func toIPv4Mapped(): ?IPv4Address ``` -------------------------------- ### CJPM Command Line Interface Help Source: https://docs.cangjie-lang.cn/docs/1.0.0/user_manual/source_zh_cn/compile_and_build/cjpm_usage_OHOS.html Displays the main interface of CJPM, including command descriptions, usage examples, available subcommands, and options. Use this to get an overview of CJPM's capabilities. ```bash Cangjie Package Manager Usage: cjpm [subcommand] [option] Available subcommands: init Init a new cangjie module check Check the dependencies update Update cjpm.lock tree Display the package dependencies in the source code build Compile the current module run Compile and run an executable product test Unittest a local package or module bench Run benchmarks in a local package or module clean Clean up the target directory install Install a cangjie binary uninstall Uninstall a cangjie binary Available options: -h, --help help for cjpm -v, --version version for cjpm Use "cjpm [subcommand] --help" for more information about a command. ``` -------------------------------- ### Convert IPv6Address to IPv4 Compatible IPv4Address Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/net/net_package_api/net_package_classes.html Converts this IPv6Address to an IPv4 compatible IPv4Address. For example, ::a.b.c.d and ::ffff:a.b.c.d convert to a.b.c.d; ::1 converts to 0.0.0.1. Addresses not starting with all zeros or ::ffff will return None. ```swift __ public func toIPv4(): ?IPv4Address ``` -------------------------------- ### Example of SOURCE parameter usage Source: https://docs.cangjie-lang.cn/docs/1.0.0/tools/source_zh_cn/tools/cjcov_manual_cjnative.html Demonstrates how to use the -s or --source parameter to specify reference paths for relative source file paths in the HTML report. This example shows the command executed in the /work directory with specific source paths. ```bash cjcov --root=./ -s "/work/cangjie /work/cangjie-tools/tests" --html-details --output=html_output ``` -------------------------------- ### Defining a Simple Property with Getter and Setter Source: https://docs.cangjie-lang.cn/docs/1.0.0/user_manual/source_zh_cn/class_and_interface/prop.html This example demonstrates a basic property 'b' within a class 'Foo'. It encapsulates access to a private variable 'a' using explicit 'get' and 'set' functions. Use this when you need to control access to a member variable. ```Cangjie class Foo { private var a = 0 public mut prop b: Int64 { get() { println("get") a } set(value) { println("set") a = value } } } main() { var x = Foo() let y = x.b + 1 // get x.b = y // set } ``` -------------------------------- ### Get Path File Name Without Extension Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/fs/fs_package_api/fs_package_structs.html Obtains the filename part of a Path, excluding the extension. The part before the last '.' is returned. Returns an empty string if the filename starts with '.' or has no extension. Throws IllegalArgumentException for empty paths or paths containing a string terminator. ```swift public prop fileNameWithoutExtension: String ``` -------------------------------- ### Create and Write to a New File Source: https://docs.cangjie-lang.cn/docs/1.0.0/user_manual/source_zh_cn/Basic_IO/basic_IO_source_stream.html Creates a new file named './tempFile.txt' using `File.create` and writes 'hello, world!' to it. Files created with `create` are write-only. ```Cangjie // 创建 internal import std.fs.* internal import std.io.* main() { let file = File.create("./tempFile.txt") file.write("hello, world!".toArray()) // 打开 let file2 = File("./tempFile.txt", Read) let bytes = readToEnd(file2) // 读取所有数据 println(bytes) } ``` -------------------------------- ### trimStart(set: String) Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/core/core_package_api/core_package_structs.html Trims the current string by removing Rune characters from the start that are present in the provided string, until the first Rune character not in the string is encountered. For example, "12241".trimStart("12") results in "41". ```APIDOC ## trimStart(set: String) ### Description Trims the current string by removing Rune characters from the start that are present in the set, until the first Rune character not in the set is encountered. For example, "12241".trimStart("12") = "41". ### Parameters * set: String - The set of characters to remove. ### Returns * String - The new string obtained after trimming. ``` -------------------------------- ### Constructing Tokens Source: https://docs.cangjie-lang.cn/docs/1.0.0/user_manual/source_zh_cn/Macro/Tokens_types_and_quote_expressions.html Demonstrates how to construct individual `Token` instances using `TokenKind` and optional values. ```Cangjie Token(k: TokenKind) Token(k: TokenKind, v: String) ``` -------------------------------- ### trimStart(set: Array) Source: https://docs.cangjie-lang.cn/docs/1.0.0/libs/std/core/core_package_api/core_package_structs.html Trims the current string by removing Rune characters from the start that are present in the provided set, until the first Rune character not in the set is encountered. For example, "12241".trimStart([r'1', r'2']) results in "41". ```APIDOC ## trimStart(set: Array) ### Description Trims the current string by removing Rune characters from the start that are present in the set, until the first Rune character not in the set is encountered. For example, "12241".trimStart([r'1', r'2']) = "41". ### Parameters * set: Array - The set of characters to remove. ### Returns * String - The new string obtained after trimming. ```