Rust 中的字符串

字符串编码

rust 中的字符串都是使用的 UTF-8 编码,rust 代码文件也是 UTF-8 编码,如果不是,rust 会报错。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
use std::str;

fn main() {
    let tao = str::from_utf8(&[0xE9u8, 0x81u8, 0x93u8]).unwrap(); // UTF8 到 str
    assert_eq!("道", tao);
    assert_eq!("道", String::from("\u{9053}"));
    let unicode_x = 0x9053; //  unicode 码点
    let utf_x_hex = 0xe98193;
    let utf_x_bin = 0b111010011000000110010011;
    println!("unicode_x: {:b}", unicode_x);
    println!("utf_x_hex: {:b}", utf_x_hex);
    println!("utf_x_bin: 0x{:b}", utf_x_bin);
}
1
2
3
unicode_x: 1001000001010011
utf_x_hex: 111010011000000110010011
utf_x_bin: 0x111010011000000110010011

字符

Rust 使用 char 表示单个字符,char 类型使用的整数值和 Unicode 标量值一一对应。为了存储任意的 Unicode 标量值,Rust 规定每个字符都占 4 个字节

C# 中 json 的使用

序列化对象

自定义对象

使用 JsonConvert.SerializeObject 方法,实例代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using System;
using Newtonsoft.Json;


namespace ConsoleApp3
{
    class Person
    {
        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("age")]
        public int? Age { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person();
            p.Name = "张三";
            p.Age = 20;
            Console.WriteLine(JsonConvert.SerializeObject(p, Formatting.None, new JsonSerializerSettings));
        }
    }
}

输出结果如下:

C# 的语法

数据类型

在 C# 中,变量分为以下类型:

  • 值类型
  • 引用类型
  • 指针类型

值类型

值类型复制时直接拷贝。如果值类型的数据成员中包括引用类型时,引用类型只会浅拷贝。

T? 是一个可以为 T 或者=null= 的值类型,类似 optional

SSL/TLS 编程实践

普通的 socket 通信

我们用 Python 来实现一个简单的 TCP 服务器,它实现 echo 功能。

服务端代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import socketserver

class MyTcpHandler(socketserver.BaseRequestHandler):

    def handle(self) -> None:
        self.data = self.request.recv(1024).strip()
        self.request.sendall(self.data)


HOST, PORT = "localhost", 9999

with socketserver.TCPServer((HOST, PORT), MyTcpHandler) as server:
    server.serve_forever()

客户端代码:

SSL/TLS 通信的基本流程

基本概念

SSL1(Secure Sockets Layer ,安全套接字层)和 TLS(Transport Layer Security, 传输层安全) 是一种加密协议,目的是为计算机网络提供通信安全。TLS 是已经废弃的 SSL 的继承者,发展过程:

SSL1.0 -> SSL2.0 -> SSL3.0 -> TLS1.0 -> TLS1.1 -> TLS1.2 -> TLS1.3