### HTTP Client and Server Implementation in Cangjie Source: https://context7.com/cangjie-pub/cangjie_docs/llms.txt Provides examples for building HTTP client and server applications using Cangjie's networking libraries. It includes setting up a basic HTTP server with a request handler for '/hello' and a client that sends a GET request to the server and prints the response. The code utilizes `ServerBuilder`, `ClientBuilder`, and asynchronous `spawn` for concurrent operation. ```cangjie import stdx.net.http.* import std.time.* import std.sync.* import stdx.log.* // Build HTTP server let server = ServerBuilder() .addr("127.0.0.1") .port(0) .build() func startServer(): Unit { // Register request handler server.distributor.register("/hello", {httpContext => httpContext.responseBuilder.body("Hello Cangjie!") }) server.logger.level = LogLevel.OFF // Start server server.serve() } func startClient(): Unit { // Build HTTP client let client = ClientBuilder().build() // Send GET request let response = client.get("http://127.0.0.1:${server.port}/hello") // Read response body let buffer = Array(32, repeat: 0) let length = response.body.read(buffer) println(String.fromUtf8(buffer[..length])) // Close connection client.close() } main() { // Start server in background thread spawn { startServer() } // Wait for server to initialize sleep(Duration.second) // Make client request startClient() // Output: Hello Cangjie! } ``` -------------------------------- ### Cangjie Basic Program Structure and Entry Point Source: https://context7.com/cangjie-pub/cangjie_docs/llms.txt Demonstrates the basic structure of a Cangjie program, including global variables, function definitions, struct, class, enum, and the main entry point function. The `main` function serves as the program's execution start. ```cangjie let globalYear = 2023 func calculateArea(width: Int64, height: Int64): Int64 { return width * height } struct Config { let name: String } class Application { var running: Bool = true } enum Status { Active | Inactive } main() { println("Welcome to Cangjie!") println("Year: ${globalYear}") let area = calculateArea(10, 20) println("Area: ${area}") } ``` -------------------------------- ### Handle WebSocket Server Closure Source: https://github.com/cangjie-pub/cangjie_docs/blob/main/docs/dev-guide/source_zh_cn/Net/net_websocket.md This Kotlin code snippet demonstrates how to handle the closure of a WebSocket connection within a Cangjie server. It logs the frame type and payload before initiating the server-side closure. ```kotlin println("close frame type: ${websocketFrame.frameType}") // CloseWebFrame println("close frame payload: ${websocketFrame.payload}") // 3, 232 websocketServer.write(CloseWebFrame, websocketFrame.payload) // 关闭底层连接 websocketServer.closeConn() } ``` -------------------------------- ### Exception Handling with Try-Catch-Finally in Cangjie Source: https://context7.com/cangjie-pub/cangjie_docs/llms.txt Illustrates exception handling mechanisms in Cangjie using `try`, `catch`, and `finally` blocks. The examples show basic `try-catch` for specific exceptions and a more complex structure with multiple `catch` blocks and a `finally` block for cleanup operations. It covers throwing and catching predefined exceptions. ```cangjie main() { // Basic try-catch try { throw NegativeArraySizeException("Invalid array size!") } catch (e: NegativeArraySizeException) { println("Caught exception: ${e}") println("Handling negative array size error") } // Try-catch-finally with multiple catch blocks try { let value = 10 if (value < 0) { throw ArithmeticException("Negative value") } println("Value is valid: ${value}") } catch (e: ArithmeticException) { println("Arithmetic error: ${e}") } catch (e: Exception) { println("General exception: ${e}") } finally { println("Cleanup completed") } println("Program continues after exception handling") } ``` -------------------------------- ### Thread Creation and Management with spawn in Cangjie Source: https://context7.com/cangjie-pub/cangjie_docs/llms.txt Demonstrates concurrent programming in Cangjie using the `spawn` keyword to create and manage threads. The code shows how to launch multiple threads that perform independent tasks concurrently and how the main thread can wait for their completion using `sleep`. It includes necessary imports for time-related operations. ```cangjie import std.time.* main(): Int64 { // Create new thread with spawn spawn { => println("Thread 1: Starting work") sleep(100 * Duration.millisecond) println("Thread 1: Work completed") } spawn { => println("Thread 2: Starting work") sleep(50 * Duration.millisecond) println("Thread 2: Work completed") } println("Main thread: Launched worker threads") // Wait for threads to complete sleep(200 * Duration.millisecond) println("Main thread: All work finished") return 0 } ``` -------------------------------- ### Using inout Parameters for Pass-by-Reference Source: https://context7.com/cangjie-pub/cangjie_docs/llms.txt Explains the usage of the `inout` keyword in Cangjie to pass variables by reference to C functions. Demonstrates how to read and write to memory pointers within `unsafe` blocks and how to define C-callable functions that modify data via pointers. ```cangjie foreign func modifyValue(ptr: CPointer): Unit @C func doubleValue(ptr: CPointer): Unit { let current = unsafe { ptr.read() } unsafe { ptr.write(current * 2) } } main() { var number: Int32 = 10 println("Before: ${number}") // Pass by reference with inout unsafe { modifyValue(inout number) doubleValue(inout number) } println("After: ${number}") } ``` -------------------------------- ### Cangjie String Operations: Literals, Interpolation, and Manipulation Source: https://context7.com/cangjie-pub/cangjie_docs/llms.txt Demonstrates various string operations in Cangjie, including creating string literals (single and double quotes), multi-line strings, raw strings, string interpolation, concatenation, comparison, and common manipulation methods like `split`. ```cangjie main() { // String literals let s1 = "Hello" let s2 = 'World' // Multi-line string let multiline = """ Line 1 Line 2 """ // Raw string (no escape sequences) let raw = #"Path: C:\\Users\\file.txt"# // String interpolation with expressions let count = 10 let fruit = "apples" let message = "There are ${count * count} ${fruit}" println(message) // Output: There are 100 apples // String operations let combined = s1 + " " + s2 let isEqual = s1 == s2 let contains = combined.contains("World") let parts = "a,b,c".split(",") println("Combined: ${combined}") println("Contains 'World': ${contains}") } ``` -------------------------------- ### Defining Cangjie Functions Callable from C Source: https://context7.com/cangjie-pub/cangjie_docs/llms.txt Shows how to expose Cangjie functions to C code using the `@C` attribute. Also illustrates the use of `CFunc` for defining function pointers and interacting with C callbacks. ```cangjie // Cangjie function callable from C @C func callableFromC(value: Int32): Int32 { println("Called from C with value: ${value}") return value * 2 } // CFunc type for function pointers let callback: CFunc<(Int32) -> Int32> = { value => println("Callback invoked with: ${value}") value + 10 } foreign func processWithCallback(cb: CFunc<(Int32) -> Int32>, value: Int32): Int32 main() { unsafe { let result = callableFromC(5) println("Result: ${result}") let callbackResult = processWithCallback(callback, 20) println("Callback result: ${callbackResult}") } } ``` -------------------------------- ### Cangjie Keywords for Control Flow and Structure Source: https://github.com/cangjie-pub/cangjie_docs/blob/main/docs/dev-guide/source_zh_cn/Appendix/tokenkind_type.md This snippet lists keywords used for controlling program flow and defining code structure in Cangjie. These include conditional statements, loops, exception handling, and return statements. No external dependencies are required to use these keywords. ```Cangjie THIS SUPER IF ELSE CASE TRY CATCH FINALLY FOR DO WHILE THROW RETURN CONTINUE BREAK IN NOT_IN MATCH WHERE EXTEND WITH OPERATOR SPAWN SYNCHRONIZED MAIN ``` -------------------------------- ### ArrayList Operations in Cangjie Source: https://context7.com/cangjie-pub/cangjie_docs/llms.txt Covers the usage of `ArrayList` for dynamic array operations in Cangjie. This snippet demonstrates creating an `ArrayList`, adding elements individually and in bulk, inserting at a specific index, accessing elements, iterating, modifying, and removing elements. It also shows how to pre-allocate capacity for performance. ```cangjie import std.collection.ArrayList main() { // Create empty ArrayList let list = ArrayList() // Add elements list.add(10) list.add(20) list.add(30) // Add multiple elements let moreNumbers = [40, 50] list.add(all: moreNumbers) // Insert at specific position list.add(15, at: 1) // Access elements println("First element: ${list[0]}") println("List size: ${list.size}") // Iterate with for-in loop for (element in list) { println("Element: ${element}") } // Modify element list[0] = 100 // Remove element list.remove(at: 1) // Pre-allocate capacity for performance let largeList = ArrayList(1000) for (i in 0..1000) { largeList.add(i) } } ``` -------------------------------- ### Calling C Functions from Cangjie Source: https://context7.com/cangjie-pub/cangjie_docs/llms.txt Demonstrates how to declare and call C functions from Cangjie using the `foreign` keyword. Requires an `unsafe` block for direct C calls. Uses `LibC.mallocCString` for C string manipulation and `LibC.free` for memory deallocation. ```cangjie // Declare C functions with foreign keyword foreign func rand(): Int32 foreign func printf(fmt: CString, ...): Int32 main() { // Call C function within unsafe block let randomNumber = unsafe { rand() } println("Random number: ${randomNumber}") // Call C printf with CString unsafe { var formatStr = LibC.mallocCString("Hello from C, value: %d\n") printf(formatStr, 42) LibC.free(formatStr) } } ``` -------------------------------- ### Class Definition with Inheritance in Cangjie Source: https://context7.com/cangjie-pub/cangjie_docs/llms.txt Demonstrates class definition, inheritance, abstract methods, and polymorphism using Cangjie. It shows how to define an abstract base class `Shape` and concrete subclasses `Circle` and `Square` that override the `area` method. The `main` function illustrates creating a collection of `Shape` objects and invoking their `area` methods. ```cangjie abstract class Shape { public func area(): Int64 } class Circle <: Shape { let radius: Int64 public init(radius: Int64) { this.radius = radius } public func area(): Int64 { 3 * radius * radius // Simplified pi approximation } } class Square <: Shape { let side: Int64 public init(side: Int64) { this.side = side } public func area(): Int64 { side * side } } main() { let shapes: Array = [Circle(5), Square(4)] for (shape in shapes) { println("Shape area: ${shape.area()}") } // Output: Shape area: 75 // Output: Shape area: 16 } ``` -------------------------------- ### Cangjie Identifiers and Special Tokens Source: https://github.com/cangjie-pub/cangjie_docs/blob/main/docs/dev-guide/source_zh_cn/Appendix/tokenkind_type.md This snippet covers Cangjie tokens for identifiers, including standard, package-qualified, and dollar-prefixed variants, as well as special structural and annotation tokens. It includes comments, newlines, end-of-file markers, and punctuation like semicolons. These are essential for parsing and interpreting Cangjie code. ```Cangjie IDENTIFIER PACKAGE_IDENTIFIER DOLLAR_IDENTIFIER COMMENT NL END SENTINEL ANNOTATION AT_EXCL ILLEGAL ``` -------------------------------- ### Cangjie Variable Declaration with Mutability and Type Inference Source: https://context7.com/cangjie-pub/cangjie_docs/llms.txt Illustrates variable declaration in Cangjie using `let` for immutable variables and `var` for mutable variables. It also shows constant declaration with `const` and string interpolation for dynamic string creation. ```cangjie main() { // Immutable variable with explicit type let pi: Float64 = 3.14159 // Mutable variable with type inference var counter = 0 counter = counter + 1 // Constant variable (compile-time evaluation) const G = 6.674e-11 // String interpolation let message = "Counter value: ${counter}" println(message) } ``` -------------------------------- ### Cangjie Function Definition and Scopes Source: https://context7.com/cangjie-pub/cangjie_docs/llms.txt Shows how to define functions in Cangjie, including specifying parameters, return types, and explicit type inference for return values. Functions can be defined at the top level or within other scopes. ```cangjie // Top-level function with explicit return type func add(a: Int64, b: Int64): Int64 { return a + b } // Function with inferred return type func multiply(x: Int64, y: Int64) { x * y } main() { let sum = add(5, 10) let product = multiply(4, 7) println("Sum: ${sum}, Product: ${product}") } ``` -------------------------------- ### Cangjie Struct Definition: Members, Constructors, and Methods Source: https://context7.com/cangjie-pub/cangjie_docs/llms.txt Shows how to define a `struct` in Cangjie, including member variables, a public constructor for initialization, and member functions (methods) to perform operations on the struct's data. Structs are value types. ```cangjie struct Rectangle { let width: Int64 let height: Int64 // Constructor public init(width: Int64, height: Int64) { this.width = width this.height = height } // Member function public func area() { width * height } public func perimeter() { 2 * (width + height) } } main() { let rect = Rectangle(10, 20) println("Area: ${rect.area()}") println("Perimeter: ${rect.perimeter()}") // Output: Area: 200 // Output: Perimeter: 60 } ``` -------------------------------- ### Cangjie Literal Tokens for Data Types Source: https://github.com/cangjie-pub/cangjie_docs/blob/main/docs/dev-guide/source_zh_cn/Appendix/tokenkind_type.md This snippet illustrates the various literal tokens supported in Cangjie for representing different data types. It covers integers, floats, booleans, runes, strings (including multi-line and raw variants), and the unit type. These literals are fundamental for initializing variables and constants. ```Cangjie INTEGER_LITERAL RUNE_BYTE_LITERAL FLOAT_LITERAL RUNE_LITERAL STRING_LITERAL SINGLE_QUOTED_STRING_LITERAL JSTRING_LITERAL MULTILINE_STRING MULTILINE_RAW_STRING BOOL_LITERAL UNIT_LITERAL ``` -------------------------------- ### Cangjie Keywords for Access Modifiers and Types Source: https://github.com/cangjie-pub/cangjie_docs/blob/main/docs/dev-guide/source_zh_cn/Appendix/tokenkind_type.md This snippet details Cangjie keywords related to access control and type definition. It includes keywords for visibility (public, private, etc.), inheritance modifiers (override, redef), and abstract or sealed types. Understanding these is crucial for defining class and member visibility and behavior. ```Cangjie PROP STATIC PUBLIC PRIVATE INTERNAL PROTECTED OVERRIDE REDEF ABSTRACT SEALED OPEN FOREIGN INOUT MUT UNSAFE UPPERBOUND ``` -------------------------------- ### Cangjie Value Types (Struct) vs. Reference Types (Class) Source: https://context7.com/cangjie-pub/cangjie_docs/llms.txt Explains the difference between value types (structs) and reference types (classes) in Cangjie. Structs are passed by copy, while classes are passed by reference, affecting how changes are propagated. ```cangjie struct ValueType { var data = 100 } class ReferenceType { var data = 100 } main() { // Value type - creates independent copy let v1 = ValueType() var v2 = v1 v2.data = 200 println("v1.data = ${v1.data}, v2.data = ${v2.data}") // Output: v1.data = 100, v2.data = 200 // Reference type - shares same instance let r1 = ReferenceType() let r2 = r1 r2.data = 200 println("r1.data = ${r1.data}, r2.data = ${r2.data}") // Output: r1.data = 200, r2.data = 200 } ``` -------------------------------- ### Cangjie TokenKind Enum Definition Source: https://github.com/cangjie-pub/cangjie_docs/blob/main/docs/dev-guide/source_zh_cn/Appendix/tokenkind_type.md Defines the enumeration for TokenKind in Cangjie, representing various lexical tokens such as operators, punctuation, keywords, and literal types. This enum is crucial for the lexer and parser to identify and categorize elements of the source code. ```cangjie public enum TokenKind <: ToString { DOT| /* "." */ COMMA| /* "," */ LPAREN| /* "(" */ RPAREN| /* ")" */ LSQUARE| /* "[" */ RSQUARE| /* "]" */ LCURL| /* "{" */ RCURL| /* "}" */ EXP| /* "**" */ MUL| /* "*" */ MOD| /* "%" */ DIV| /* "/" */ ADD| /* "+" */ SUB| /* "-" */ INCR| /* "++" */ DECR| /* "--" */ AND| /* "&&" */ OR| /* "||" */ COALESCING| /* "??" */ PIPELINE| /* "||" */ COMPOSITION| /* "~>" */ NOT| /* "!" */ BITAND| /* "&" */ BITOR| /* "|" */ BITXOR| /* "^" */ BITNOT| /* "~" */ LSHIFT| /* "<<" */ RSHIFT| /* ">>" */ COLON| /* ":" */ SEMI| /* ";" */ ASSIGN| /* "=" */ ADD_ASSIGN| /* "+=" */ SUB_ASSIGN| /* "-=" */ MUL_ASSIGN| /* "*=" */ EXP_ASSIGN| /* "**=" */ DIV_ASSIGN| /* "/=" */ MOD_ASSIGN| /* "%=" */ AND_ASSIGN| /* "&&=" */ OR_ASSIGN| /* "||" */ BITAND_ASSIGN| /* "&=" */ BITOR_ASSIGN| /* "|=" */ BITXOR_ASSIGN| /* "^=" */ LSHIFT_ASSIGN| /* "<<=" */ RSHIFT_ASSIGN| /* ">>=" */ ARROW| /* "->" */ BACKARROW| /* "<-" */ DOUBLE_ARROW| /* "=>" */ RANGEOP| /* ".." */ CLOSEDRANGEOP| /* "..=" */ ELLIPSIS| /* "..." */ HASH| /* "#" */ AT| /* "@" */ QUEST| /* "?" */ LT| /* "<" */ GT| /* ">" */ LE| /* "<=" */ GE| /* ">=" */ IS| /* "is" */ AS| /* "as" */ NOTEQ| /* "!=" */ EQUAL| /* "==" */ WILDCARD| /* "_" */ INT8| /* "Int8" */ INT16| /* "Int16" */ INT32| /* "Int32" */ INT64| /* "Int64" */ INTNATIVE| /* "IntNative" */ UINT8| /* "UInt8" */ UINT16| /* "UInt16" */ UINT32| /* "UInt32" */ UINT64| /* "UInt64" */ UINTNATIVE| /* "UIntNative" */ FLOAT16| /* "Float16" */ FLOAT32| /* "Float32" */ FLOAT64| /* "Float64" */ RUNE| /* "Rune" */ BOOLEAN| /* "Bool" */ NOTHING| /* "Nothing" */ UNIT| /* "Unit" */ STRUCT| /* "struct" */ ENUM| /* "enum" */ VARRAY| /* "VArray" */ THISTYPE| /* "This" */ PACKAGE| /* "package" */ IMPORT| /* "import" */ CLASS| /* "class" */ INTERFACE| /* "interface" */ FUNC| /* "func" */ MACRO| /* "macro" */ QUOTE| /* "quote" */ DOLLAR| /* "$" */ LET| /* "let" */ VAR| /* "var" */ CONST| /* "const" */ TYPE| /* "type" */ INIT| /* "init" */ } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.