encoding

package module
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 14, 2025 License: MIT Imports: 26 Imported by: 2

README

EncodingProcessor

一个专注于编码检测和转换的 Go 语言库,提供简单易用且功能强大的编码处理能力。

特性

  • 🔍 智能编码检测: 支持多种编码格式的自动检测,包括 UTF-8、GBK、BIG5、Shift_JIS 等
  • 🔄 高效编码转换: 在不同编码格式之间进行快速转换
  • 📁 文件处理: 支持单个文件的编码检测和转换,包含安全的备份机制
  • 🌊 流式处理: 支持大文件的流式处理,内存友好
  • 📊 性能监控: 内置性能指标收集和统计功能
  • ⚙️ 高度可配置: 丰富的配置选项满足不同场景需求
  • 🛡️ 错误恢复: 完善的错误处理和恢复机制

安装

go get github.com/mirbf/encoding-processor

快速开始

基础使用
package main

import (
    "fmt"
    "log"
    
    "github.com/mirbf/encoding-processor"
)

func main() {
    // 创建处理器
    processor := encoding.NewDefault()
    
    // 检测编码
    data := []byte("这是一段中文文本")
    result, err := processor.DetectEncoding(data)
    if err != nil {
        log.Fatal(err)
    }
    
    fmt.Printf("检测到编码: %s (置信度: %.2f)\n", result.Encoding, result.Confidence)
    
    // 智能转换
    convertResult, err := processor.SmartConvertString("测试文本", encoding.EncodingUTF8)
    if err != nil {
        log.Fatal(err)
    }
    
    fmt.Printf("转换结果: %s\n", convertResult.Text)
}
文件处理
// 创建文件处理器
fileProcessor := encoding.NewFileProcessor(encoding.GetDefaultProcessorConfig())

// 配置处理选项
options := &encoding.FileProcessOptions{
    TargetEncoding:    encoding.EncodingUTF8,
    CreateBackup:      true,
    OverwriteExisting: false,
    PreserveMode:      true,
    PreserveTime:      true,
}

// 处理文件
result, err := fileProcessor.ProcessFile("input.txt", "output.txt", options)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("处理完成: %s -> %s\n", result.InputFile, result.OutputFile)
流式处理
streamProcessor := encoding.NewDefaultStream()

options := &encoding.StreamOptions{
    SourceEncoding: "", // 自动检测
    TargetEncoding: encoding.EncodingUTF8,
    BufferSize:     16384,
    StrictMode:     false,
}

ctx := context.Background()
result, err := streamProcessor.ProcessReaderWriter(ctx, inputReader, outputWriter, options)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("处理完成: 读取 %d 字节, 写入 %d 字节\n", result.BytesRead, result.BytesWritten)

支持的编码

  • Unicode: UTF-8, UTF-16, UTF-16LE, UTF-16BE, UTF-32*, UTF-32LE*, UTF-32BE*
  • 中文: GBK, GB2312, GB18030, BIG5
  • 日文: Shift_JIS, EUC-JP
  • 韩文: EUC-KR
  • 西欧: ISO-8859-1, ISO-8859-2, ISO-8859-5, ISO-8859-15
  • Windows: Windows-1250, Windows-1251, Windows-1252, Windows-1254
  • 其他: KOI8-R, CP866, Macintosh

*注: UTF-32 系列编码目前映射到 UTF-16 实现

工厂函数

库提供了多种预配置的工厂函数:

// 基础工厂函数
processor := encoding.NewDefault()                    // 默认配置
processor := encoding.NewQuick()                      // 快速配置(与默认相同)
processor := encoding.NewForCLI()                     // 命令行工具优化
processor := encoding.NewForWebService()              // Web 服务优化
processor := encoding.NewForBatchProcessing()         // 批量处理优化

// 性能优化
processor := encoding.NewHighPerformance()            // 高性能配置
processor := encoding.NewMemoryEfficient()            // 内存高效配置

// 错误处理模式
processor := encoding.NewStrictMode()                 // 严格模式
processor := encoding.NewTolerantMode()               // 容错模式

// 自定义配置
processor := encoding.NewWithLogger(customLogger)     // 带自定义日志
processor := encoding.NewWithConfig(detCfg, convCfg)  // 完全自定义配置

// 专用处理器
streamProcessor := encoding.NewDefaultStream()        // 流处理器

// 带监控
processor, metrics := encoding.NewDefaultWithMetrics() // 带性能监控

性能监控

processor, metrics := encoding.NewDefaultWithMetrics()

// 执行一些操作...

stats := metrics.GetStats()
fmt.Printf("总操作数: %d\n", stats.TotalOperations)
fmt.Printf("成功率: %.2f%%\n", float64(stats.SuccessOperations)/float64(stats.TotalOperations)*100)
fmt.Printf("平均处理速度: %.2f MB/s\n", stats.AverageProcessingSpeed/1024/1024)

错误处理

库提供了结构化的错误类型:

result, err := processor.DetectEncoding(data)
if err != nil {
    var encodingErr *encoding.EncodingError
    if errors.As(err, &encodingErr) {
        fmt.Printf("编码错误: 操作=%s, 编码=%s, 错误=%v\n", 
            encodingErr.Op, encodingErr.Encoding, encodingErr.Err)
    }
    
    switch {
    case errors.Is(err, encoding.ErrDetectionFailed):
        // 处理检测失败
    case errors.Is(err, encoding.ErrUnsupportedEncoding):
        // 处理不支持的编码
    default:
        // 处理其他错误
    }
}

核心接口

主要接口
  • Detector: 编码检测功能
  • Converter: 编码转换功能
  • Processor: 集成检测和转换功能
  • StreamProcessor: 流式处理功能
  • FileProcessor: 文件处理功能
  • MetricsCollector: 性能监控功能
数据结构
  • DetectionResult: 检测结果,包含编码名称、置信度等
  • ConvertResult: 转换结果,包含转换后数据和元信息
  • FileProcessResult: 文件处理结果
  • StreamResult: 流处理结果
  • ProcessingStats: 性能统计信息

设计原则

  • 单一职责: 专注于编码检测和转换,不涉及文件系统操作
  • 接口设计: 清晰的接口分离,便于测试和扩展
  • 内存安全: 大文件分块处理,避免内存溢出
  • 并发安全: 所有公共接口都是线程安全的
  • 错误恢复: 提供完善的错误处理和恢复机制

职责边界

库的职责

  • 编码检测(字节数组、字符串、单个文件)
  • 编码转换(字节数组、字符串、数据流)
  • 单个文件的编码处理

不是库的职责

  • 目录遍历和批量文件管理
  • 文件系统监控
  • 并发文件处理调度

这些功能应该在应用层实现。

性能特性

  • 智能检测: BOM 检测 → UTF-8 验证 → chardet 库检测
  • 缓存机制: 检测结果缓存,避免重复检测
  • 内存优化: 大文件分块处理,可配置内存限制
  • 流式处理: 支持无限大小文件的流式转换
  • 并发安全: 所有接口支持并发调用

示例

查看 example/main.go 了解完整的使用示例。

文档

测试

# 运行所有测试
go test -v

# 运行示例
cd example
go run main.go

# 检查代码构建
go build ./...

依赖

  • github.com/saintfish/chardet - 编码检测
  • golang.org/x/text/encoding - 编码转换
  • golang.org/x/text/transform - 转换框架

许可证

MIT License

贡献

欢迎提交 Issue 和 Pull Request!

Documentation

Index

Constants

View Source
const (
	EncodingUTF8        = "UTF-8"
	EncodingUTF16       = "UTF-16"
	EncodingUTF16LE     = "UTF-16LE"
	EncodingUTF16BE     = "UTF-16BE"
	EncodingUTF32       = "UTF-32"
	EncodingUTF32LE     = "UTF-32LE"
	EncodingUTF32BE     = "UTF-32BE"
	EncodingGBK         = "GBK"
	EncodingGB2312      = "GB2312"
	EncodingGB18030     = "GB18030"
	EncodingBIG5        = "BIG5"
	EncodingShiftJIS    = "SHIFT_JIS"
	EncodingEUCJP       = "EUC-JP"
	EncodingEUCKR       = "EUC-KR"
	EncodingISO88591    = "ISO-8859-1"
	EncodingISO88592    = "ISO-8859-2"
	EncodingISO88595    = "ISO-8859-5"
	EncodingISO885915   = "ISO-8859-15"
	EncodingWindows1250 = "WINDOWS-1250"
	EncodingWindows1251 = "WINDOWS-1251"
	EncodingWindows1252 = "WINDOWS-1252"
	EncodingWindows1254 = "WINDOWS-1254"
	EncodingKOI8R       = "KOI8-R"
	EncodingCP866       = "CP866"
	EncodingMacintosh   = "MACINTOSH"
)

支持的编码格式

View Source
const (
	OperationDetect   = "detect"
	OperationConvert  = "convert"
	OperationProcess  = "process"
	OperationValidate = "validate"
)

操作类型

View Source
const (
	DefaultSampleSize    = 8192        // 默认检测样本大小
	DefaultMinConfidence = 0.8         // 默认最小置信度
	DefaultBufferSize    = 8192        // 默认缓冲区大小
	DefaultInvalidChar   = "?"         // 默认无效字符替换
	DefaultBackupSuffix  = ".bak"      // 默认备份后缀
	DefaultChunkSize     = 1024 * 1024 // 默认分块大小 (1MB)
	DefaultMaxFileSize   = 100 << 20   // 默认最大文件大小 (100MB)
	DefaultCacheSize     = 1000        // 默认缓存大小
	DefaultCacheTTL      = time.Hour   // 默认缓存过期时间
)

默认配置值

View Source
const (
	LineEndingLF   = "\n"   // Unix/Linux 换行符
	LineEndingCRLF = "\r\n" // Windows 换行符
	LineEndingCR   = "\r"   // Classic Mac 换行符
)

换行符常量

Variables

View Source
var (
	// ErrUnsupportedEncoding 不支持的编码
	ErrUnsupportedEncoding = errors.New("unsupported encoding")

	// ErrDetectionFailed 检测失败
	ErrDetectionFailed = errors.New("encoding detection failed")

	// ErrConversionFailed 转换失败
	ErrConversionFailed = errors.New("encoding conversion failed")

	// ErrInvalidInput 无效输入
	ErrInvalidInput = errors.New("invalid input data")

	// ErrFileTooLarge 文件过大
	ErrFileTooLarge = errors.New("file too large")

	// ErrInsufficientMemory 内存不足
	ErrInsufficientMemory = errors.New("insufficient memory")

	// ErrFileNotFound 文件不存在
	ErrFileNotFound = errors.New("file not found")

	// ErrPermissionDenied 权限不足
	ErrPermissionDenied = errors.New("permission denied")

	// ErrInvalidConfiguration 无效配置
	ErrInvalidConfiguration = errors.New("invalid configuration")
)

预定义错误

Functions

func NewDefaultWithMetrics

func NewDefaultWithMetrics() (Processor, MetricsCollector)

NewDefaultWithMetrics 创建带性能监控的默认处理器

Types

type ConvertResult

type ConvertResult struct {
	// Data 转换后的数据
	Data []byte `json:"-"`

	// SourceEncoding 源编码
	SourceEncoding string `json:"source_encoding"`

	// TargetEncoding 目标编码
	TargetEncoding string `json:"target_encoding"`

	// BytesProcessed 处理的字节数
	BytesProcessed int64 `json:"bytes_processed"`

	// ConversionTime 转换耗时
	ConversionTime time.Duration `json:"conversion_time"`
}

ConvertResult 编码转换结果结构

type Converter

type Converter interface {
	// Convert 在指定编码之间转换
	Convert(data []byte, from, to string) ([]byte, error)

	// ConvertToUTF8 转换为 UTF-8 编码
	ConvertToUTF8(data []byte, from string) ([]byte, error)

	// ConvertString 字符串编码转换
	ConvertString(text, from, to string) (string, error)
}

Converter 编码转换器接口

func NewConverter

func NewConverter(config ...*ConverterConfig) Converter

NewConverter 创建新的转换器

type ConverterConfig

type ConverterConfig struct {
	// StrictMode 严格模式(遇到无法转换字符时报错)
	StrictMode bool `json:"strict_mode"`

	// InvalidCharReplacement 无效字符替换字符
	InvalidCharReplacement string `json:"invalid_char_replacement"`

	// BufferSize 转换缓冲区大小
	BufferSize int `json:"buffer_size"`

	// MaxMemoryUsage 最大内存使用量(字节,0 表示无限制)
	MaxMemoryUsage int64 `json:"max_memory_usage"`

	// ChunkSize 大文件分块大小(字节,默认 1MB)
	ChunkSize int64 `json:"chunk_size"`

	// PreserveBOM 是否保留 BOM
	PreserveBOM bool `json:"preserve_bom"`

	// NormalizeLineEndings 是否规范化换行符
	NormalizeLineEndings bool `json:"normalize_line_endings"`

	// TargetLineEnding 目标换行符(LF, CRLF, CR)
	TargetLineEnding string `json:"target_line_ending"`
}

ConverterConfig 转换器配置

func GetDefaultConverterConfig

func GetDefaultConverterConfig() *ConverterConfig

GetDefaultConverterConfig 获取默认转换器配置

type DetectionCandidate added in v0.2.0

type DetectionCandidate struct {
	Encoding      string
	Confidence    float64
	Method        string
	ConvertedText string
	Score         float64
}

DetectionCandidate 检测候选结果

type DetectionResult

type DetectionResult struct {
	// Encoding 检测到的编码名称
	Encoding string `json:"encoding"`

	// Confidence 检测置信度 (0.0-1.0)
	Confidence float64 `json:"confidence"`

	// Language 检测到的语言(可选)
	Language string `json:"language,omitempty"`

	// Details 详细信息(可选)
	Details map[string]interface{} `json:"details,omitempty"`
}

DetectionResult 编码检测结果结构

type Detector

type Detector interface {
	// DetectEncoding 检测数据的编码格式
	DetectEncoding(data []byte) (*DetectionResult, error)

	// DetectFileEncoding 检测文件的编码格式
	DetectFileEncoding(filename string) (*DetectionResult, error)

	// DetectBestEncoding 检测最可能的编码格式(简化版本)
	DetectBestEncoding(data []byte) (string, error)

	// SmartDetectEncoding 智能编码检测(增强版)
	SmartDetectEncoding(data []byte) (*DetectionResult, error)
}

Detector 编码检测器接口

func NewDetector

func NewDetector(config ...*DetectorConfig) Detector

NewDetector 创建新的检测器

type DetectorConfig

type DetectorConfig struct {
	// SampleSize 检测样本大小(字节,默认 8192)
	SampleSize int `json:"sample_size"`

	// MinConfidence 最小置信度(默认 0.6)
	MinConfidence float64 `json:"min_confidence"`

	// SupportedEncodings 支持的编码列表
	SupportedEncodings []string `json:"supported_encodings"`

	// EnableCache 是否启用检测结果缓存
	EnableCache bool `json:"enable_cache"`

	// CacheSize 缓存大小(默认 1000)
	CacheSize int `json:"cache_size"`

	// CacheTTL 缓存过期时间(默认 1 小时)
	CacheTTL time.Duration `json:"cache_ttl"`

	// EnableLanguageDetection 是否启用语言检测
	EnableLanguageDetection bool `json:"enable_language_detection"`

	// PreferredEncodings 优先编码列表(检测时优先考虑)
	PreferredEncodings []string `json:"preferred_encodings"`
}

DetectorConfig 检测器配置

func GetDefaultDetectorConfig

func GetDefaultDetectorConfig() *DetectorConfig

GetDefaultDetectorConfig 获取默认检测器配置

type EncodingError

type EncodingError struct {
	Op       string // 操作名称
	Encoding string // 相关编码
	File     string // 相关文件(可选)
	Err      error  // 原始错误
}

EncodingError 编码相关错误

func (*EncodingError) Error

func (e *EncodingError) Error() string

func (*EncodingError) Unwrap

func (e *EncodingError) Unwrap() error

type FileOperationError

type FileOperationError struct {
	Op   string // 操作名称
	File string // 文件路径
	Err  error  // 原始错误
}

FileOperationError 文件操作错误

func (*FileOperationError) Error

func (e *FileOperationError) Error() string

func (*FileOperationError) Unwrap

func (e *FileOperationError) Unwrap() error

type FileProcessOptions

type FileProcessOptions struct {
	// TargetEncoding 目标编码(默认 UTF-8)
	TargetEncoding string `json:"target_encoding"`

	// MinConfidence 最小置信度阈值(默认 0.8)
	MinConfidence float64 `json:"min_confidence"`

	// CreateBackup 是否创建备份文件(默认 true)
	CreateBackup bool `json:"create_backup"`

	// BackupSuffix 备份文件后缀(默认 ".bak")
	BackupSuffix string `json:"backup_suffix"`

	// OverwriteExisting 是否覆盖已存在的输出文件(默认 false)
	OverwriteExisting bool `json:"overwrite_existing"`

	// BufferSize 缓冲区大小(字节,默认 8192)
	BufferSize int `json:"buffer_size"`

	// PreserveMode 是否保持文件权限(默认 true)
	PreserveMode bool `json:"preserve_mode"`

	// PreserveTime 是否保持文件时间戳(默认 true)
	PreserveTime bool `json:"preserve_time"`

	// DryRun 试运行模式,不实际修改文件(默认 false)
	DryRun bool `json:"dry_run"`
}

FileProcessOptions 文件处理选项

type FileProcessResult

type FileProcessResult struct {
	// InputFile 输入文件路径
	InputFile string `json:"input_file"`

	// OutputFile 输出文件路径
	OutputFile string `json:"output_file"`

	// BackupFile 备份文件路径(如果创建了备份)
	BackupFile string `json:"backup_file,omitempty"`

	// SourceEncoding 检测到的源编码
	SourceEncoding string `json:"source_encoding"`

	// TargetEncoding 目标编码
	TargetEncoding string `json:"target_encoding"`

	// BytesProcessed 处理的字节数
	BytesProcessed int64 `json:"bytes_processed"`

	// ProcessingTime 处理耗时
	ProcessingTime time.Duration `json:"processing_time"`

	// DetectionConfidence 编码检测置信度
	DetectionConfidence float64 `json:"detection_confidence"`
}

FileProcessResult 文件处理结果

type FileProcessor

type FileProcessor interface {
	// ProcessFile 处理文件(检测并转换编码)
	ProcessFile(inputFile, outputFile string, options *FileProcessOptions) (*FileProcessResult, error)

	// ProcessFileInPlace 就地处理文件(直接修改源文件)
	ProcessFileInPlace(file string, options *FileProcessOptions) (*FileProcessResult, error)

	// ProcessFileToBytes 读取文件并转换编码,返回字节数组
	ProcessFileToBytes(filename, targetEncoding string) ([]byte, error)

	// ProcessFileToString 读取文件并转换编码,返回字符串
	ProcessFileToString(filename, targetEncoding string) (string, error)
}

FileProcessor 文件处理接口

func NewFileProcessor

func NewFileProcessor(config *ProcessorConfig) FileProcessor

NewFileProcessor 创建新的文件处理器

type Logger

type Logger interface {
	Debug(msg string, fields ...interface{})
	Info(msg string, fields ...interface{})
	Warn(msg string, fields ...interface{})
	Error(msg string, fields ...interface{})
}

Logger 日志记录器接口

type MetricsCollector

type MetricsCollector interface {
	// GetStats 获取处理统计信息
	GetStats() *ProcessingStats

	// ResetStats 重置统计信息
	ResetStats()

	// RecordOperation 记录操作
	RecordOperation(operation string, duration time.Duration)

	// RecordError 记录错误
	RecordError(operation string, err error)
}

MetricsCollector 性能监控和统计接口

func NewMetricsCollector

func NewMetricsCollector() MetricsCollector

NewMetricsCollector 创建新的性能监控器

type ProcessingStats

type ProcessingStats struct {
	// TotalOperations 总操作数
	TotalOperations int64 `json:"total_operations"`

	// SuccessOperations 成功操作数
	SuccessOperations int64 `json:"success_operations"`

	// FailedOperations 失败操作数
	FailedOperations int64 `json:"failed_operations"`

	// TotalBytes 总字节数
	TotalBytes int64 `json:"total_bytes"`

	// TotalProcessingTime 总处理时间
	TotalProcessingTime time.Duration `json:"total_processing_time"`

	// AverageProcessingSpeed 平均处理速度(字节/秒)
	AverageProcessingSpeed float64 `json:"average_processing_speed"`

	// EncodingDistribution 编码分布统计
	EncodingDistribution map[string]int64 `json:"encoding_distribution"`

	// StartTime 统计开始时间
	StartTime time.Time `json:"start_time"`

	// LastUpdateTime 最后更新时间
	LastUpdateTime time.Time `json:"last_update_time"`
}

ProcessingStats 处理统计信息

type Processor

type Processor interface {
	Detector
	Converter

	// SmartConvert 智能转换(自动检测源编码)
	SmartConvert(data []byte, target string) (*ConvertResult, error)

	// SmartConvertString 智能字符串转换(自动检测源编码)
	SmartConvertString(text, target string) (*StringConvertResult, error)
}

Processor 编码处理器接口,集成检测和转换功能

func NewDefault

func NewDefault() Processor

NewDefault 创建默认处理器

func NewForBatchProcessing

func NewForBatchProcessing() Processor

NewForBatchProcessing 创建适合批量处理的处理器

func NewForCLI

func NewForCLI() Processor

NewForCLI 创建适合命令行工具的处理器

func NewForWebService

func NewForWebService() Processor

NewForWebService 创建适合 Web 服务的处理器

func NewHighPerformance

func NewHighPerformance() Processor

NewHighPerformance 创建高性能处理器

func NewMemoryEfficient

func NewMemoryEfficient() Processor

NewMemoryEfficient 创建内存高效的处理器

func NewProcessor

func NewProcessor(config *ProcessorConfig) Processor

NewProcessor 创建新的处理器

func NewQuick

func NewQuick() Processor

NewQuick 快速创建处理器(最少配置)

func NewSmartProcessor added in v0.2.0

func NewSmartProcessor(config ...*ProcessorConfig) Processor

NewSmartProcessor 创建使用智能检测的处理器

func NewStrictMode

func NewStrictMode() Processor

NewStrictMode 创建严格模式处理器(遇到错误立即失败)

func NewTolerantMode

func NewTolerantMode() Processor

NewTolerantMode 创建容错模式处理器(尽量处理,忽略错误)

func NewWithConfig

func NewWithConfig(detectorConfig *DetectorConfig, converterConfig *ConverterConfig) Processor

NewWithConfig 使用自定义配置创建处理器

func NewWithLogger

func NewWithLogger(logger Logger) Processor

NewWithLogger 创建带自定义日志的处理器

func NewZipFileProcessor added in v0.2.0

func NewZipFileProcessor() Processor

NewZipFileProcessor 专门用于ZIP文件名检测的处理器

type ProcessorConfig

type ProcessorConfig struct {
	// DetectorConfig 检测器配置
	DetectorConfig *DetectorConfig `json:"detector_config"`

	// ConverterConfig 转换器配置
	ConverterConfig *ConverterConfig `json:"converter_config"`

	// EnableMetrics 是否启用性能监控
	EnableMetrics bool `json:"enable_metrics"`

	// LogLevel 日志级别
	LogLevel string `json:"log_level"`

	// Logger 自定义日志记录器
	Logger Logger `json:"-"`

	// TempDir 临时文件目录
	TempDir string `json:"temp_dir"`

	// MaxFileSize 最大文件大小(字节,0 表示无限制)
	MaxFileSize int64 `json:"max_file_size"`
}

ProcessorConfig 处理器配置(集成配置)

func GetDefaultProcessorConfig

func GetDefaultProcessorConfig() *ProcessorConfig

GetDefaultProcessorConfig 获取默认处理器配置

type StreamOptions

type StreamOptions struct {
	// SourceEncoding 源编码(空值表示自动检测)
	SourceEncoding string `json:"source_encoding"`

	// TargetEncoding 目标编码(默认 UTF-8)
	TargetEncoding string `json:"target_encoding"`

	// BufferSize 缓冲区大小(默认 8192)
	BufferSize int `json:"buffer_size"`

	// DetectionSampleSize 编码检测样本大小(默认 8192)
	DetectionSampleSize int `json:"detection_sample_size"`

	// SkipBOM 是否跳过 BOM(默认 false)
	SkipBOM bool `json:"skip_bom"`

	// StrictMode 严格模式(遇到无法转换字符时报错,默认 false)
	StrictMode bool `json:"strict_mode"`
}

StreamOptions 流处理选项

type StreamProcessor

type StreamProcessor interface {
	// ProcessReader 处理输入流
	ProcessReader(ctx context.Context, r io.Reader, sourceEncoding, targetEncoding string) (io.Reader, error)

	// ProcessWriter 创建转换写入器
	ProcessWriter(ctx context.Context, w io.Writer, sourceEncoding, targetEncoding string) (io.Writer, error)

	// ProcessReaderWriter 处理读写流
	ProcessReaderWriter(ctx context.Context, r io.Reader, w io.Writer, options *StreamOptions) (*StreamResult, error)
}

StreamProcessor 流式处理接口

func NewDefaultStream

func NewDefaultStream() StreamProcessor

NewDefaultStream 创建默认流处理器

func NewStreamProcessor

func NewStreamProcessor(config *ProcessorConfig) StreamProcessor

NewStreamProcessor 创建新的流处理器

type StreamResult

type StreamResult struct {
	// BytesRead 读取的字节数
	BytesRead int64 `json:"bytes_read"`

	// BytesWritten 写入的字节数
	BytesWritten int64 `json:"bytes_written"`

	// SourceEncoding 检测到的源编码
	SourceEncoding string `json:"source_encoding"`

	// TargetEncoding 目标编码
	TargetEncoding string `json:"target_encoding"`

	// ProcessingTime 处理耗时
	ProcessingTime time.Duration `json:"processing_time"`

	// ErrorCount 转换错误次数
	ErrorCount int `json:"error_count"`
}

StreamResult 流处理结果

type StringConvertResult

type StringConvertResult struct {
	// Text 转换后的字符串
	Text string `json:"text"`

	// SourceEncoding 源编码
	SourceEncoding string `json:"source_encoding"`

	// TargetEncoding 目标编码
	TargetEncoding string `json:"target_encoding"`

	// BytesProcessed 处理的字节数
	BytesProcessed int64 `json:"bytes_processed"`

	// ConversionTime 转换耗时
	ConversionTime time.Duration `json:"conversion_time"`
}

StringConvertResult 字符串转换结果

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL