code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
import math def euclidean_distance(x1, x2): if len(x1) != len(x2): raise ValueError("两个样本必须具有相同的维度") # 欧氏距离公式:sqrt(sum((x1_i - x2_i)^2)) return math.sqrt(sum((a - b) ** 2 for a, b in zip(x1, x2))) def knn_classify(train_features, train_labels, test_sample, k): # 输入合法性检查 if not train_features: raise ValueError("训练样本不能为空") if len(train_features) != len(train_labels): raise ValueError("训练特征与标签数量必须一致") if k <= 0: raise ValueError("k必须为正整数") # 若k大于训练样本数,强制使用所有样本 if k > len(train_features): k = len(train_features) print(f"警告:k值大于训练样本数,已自动调整为{k}") # 检查特征维度是否一致 feature_dim = len(train_features[0]) if len(test_sample) != feature_dim: raise ValueError(f"测试样本维度({len(test_sample)})与训练样本维度({feature_dim})不一致") # 1. 计算测试样本与所有训练样本的距离 distances = [] for i in range(len(train_features)): dist = euclidean_distance(test_sample, train_features[i]) distances.append((dist, train_labels[i])) # 存储(距离,标签)元组 # 2. 按距离升序排序(距离越小越近) distances.sort(key=lambda x: x[0]) # 按元组第一个元素(距离)排序 # 3. 取前k个最近邻的标签 k_nearest_labels = [item[1] for item in distances[:k]] # 4. 投票:选择出现次数最多的标签作为预测结果 label_count = {} for label in k_nearest_labels: if label in label_count: label_count[label] += 1 else: label_count[label] = 1 # 处理票数相同的情况(取第一个出现的最大票数标签) max_count = -1 predicted_label = None for label, count in label_count.items(): if count > max_count: max_count = count predicted_label = label return predicted_label def knn_predict_batch(train_features, train_labels, test_samples, k): return [knn_classify(train_features, train_labels, sample, k) for sample in test_samples] # 训练数据(二维特征,标签为0或1) train_features = [ [1.2, 2.3], [1.8, 1.9], [2.1, 2.8], [2.5, 2.2], # 标签0 [5.3, 6.1], [6.0, 5.8], [6.2, 6.5], [7.0, 6.3] # 标签1 ] train_labels = [0, 0, 0, 0, 1, 1, 1, 1] # 测试样本 test_samples = [ [1.5, 2.5], # 预计属于0 [6.5, 6.0], # 预计属于1 [3.0, 3.5] # 靠近0的样本,预计属于0 ] # 预测(k=3) predictions = knn_predict_batch(train_features, train_labels, test_samples, k=3) print("测试样本:", test_samples) print("预测标签:", predictions)
2301_80822435/machine-learning-course
assignment4/2班46.py
Python
mit
2,916
import math import operator from collections import Counter def euclidean_distance(point1, point2): """ 计算两个点之间的欧几里得距离 """ if len(point1) != len(point2): raise ValueError("Points must have the same dimensions") squared_distance = 0 for i in range(len(point1)): squared_distance += (point1[i] - point2[i]) ** 2 return math.sqrt(squared_distance) def manhattan_distance(point1, point2): """ 计算两个点之间的曼哈顿距离 """ if len(point1) != len(point2): raise ValueError("Points must have the same dimensions") distance = 0 for i in range(len(point1)): distance += abs(point1[i] - point2[i]) return distance def get_neighbors(training_set, test_instance, k, distance_metric='euclidean'): """ 获取测试实例的k个最近邻 """ distances = [] # 选择距离度量函数 if distance_metric == 'euclidean': distance_func = euclidean_distance elif distance_metric == 'manhattan': distance_func = manhattan_distance else: raise ValueError("Unsupported distance metric") # 计算测试实例与所有训练实例的距离 for i, training_point in enumerate(training_set): # training_point格式: (features, label) features = training_point[0] label = training_point[1] dist = distance_func(test_instance, features) distances.append((training_point, dist, label)) # 按距离排序并返回前k个 distances.sort(key=operator.itemgetter(1)) neighbors = distances[:k] return neighbors def predict_classification(neighbors): """ 基于邻居进行分类预测(多数投票) """ class_votes = {} for neighbor in neighbors: label = neighbor[2] # 邻居的标签 if label in class_votes: class_votes[label] += 1 else: class_votes[label] = 1 # 按票数排序,返回票数最多的类别 sorted_votes = sorted(class_votes.items(), key=operator.itemgetter(1), reverse=True) return sorted_votes[0][0] def predict_regression(neighbors): """ 基于邻居进行回归预测(平均值) """ if not neighbors: return 0 # 假设标签是数值型 values = [neighbor[2] for neighbor in neighbors] return sum(values) / len(values) class KNN: """ K近邻算法类 """ def __init__(self, k=3, distance_metric='euclidean'): """ 初始化KNN模型 参数: k: 邻居数量 distance_metric: 距离度量方法 ('euclidean' 或 'manhattan') """ self.k = k self.distance_metric = distance_metric self.training_set = None def fit(self, X_train, y_train): """ 训练模型(实际上只是存储训练数据) """ if len(X_train) != len(y_train): raise ValueError("X_train and y_train must have the same length") self.training_set = [] for i in range(len(X_train)): self.training_set.append((X_train[i], y_train[i])) def predict(self, X_test, problem_type='classification'): """ 预测测试数据的标签 参数: X_test: 测试数据 problem_type: 问题类型 ('classification' 或 'regression') """ if self.training_set is None: raise ValueError("Model must be fitted before prediction") predictions = [] for test_instance in X_test: neighbors = get_neighbors(self.training_set, test_instance, self.k, self.distance_metric) if problem_type == 'classification': prediction = predict_classification(neighbors) elif problem_type == 'regression': prediction = predict_regression(neighbors) else: raise ValueError("problem_type must be 'classification' or 'regression'") predictions.append(prediction) return predictions def score(self, X_test, y_test, problem_type='classification'): """ 计算模型在测试集上的准确率(分类)或R²分数(回归) """ predictions = self.predict(X_test, problem_type) if problem_type == 'classification': # 计算准确率 correct = 0 for i in range(len(predictions)): if predictions[i] == y_test[i]: correct += 1 return correct / len(predictions) else: # regression # 计算R²分数 y_mean = sum(y_test) / len(y_test) ss_total = sum((y - y_mean) ** 2 for y in y_test) ss_residual = sum((y_test[i] - predictions[i]) ** 2 for i in range(len(y_test))) if ss_total == 0: return 1.0 # 完美预测 return 1 - (ss_residual / ss_total) # 测试代码 if __name__ == "__main__": print("=== K近邻算法测试 ===\n") # 测试1:分类问题 print("1. 分类问题测试:") # 简单的二维分类数据 X_train_class = [ [1, 2], [1, 4], [2, 1], [2, 3], # 类别0 [5, 6], [6, 5], [7, 7], [6, 8] # 类别1 ] y_train_class = [0, 0, 0, 0, 1, 1, 1, 1] X_test_class = [[1, 3], [6, 6]] y_test_class = [0, 1] # 创建并训练KNN分类器 knn_classifier = KNN(k=3, distance_metric='euclidean') knn_classifier.fit(X_train_class, y_train_class) # 预测 predictions_class = knn_classifier.predict(X_test_class, 'classification') accuracy = knn_classifier.score(X_test_class, y_test_class, 'classification') print(f"训练数据: {X_train_class}") print(f"训练标签: {y_train_class}") print(f"测试数据: {X_test_class}") print(f"真实标签: {y_test_class}") print(f"预测结果: {predictions_class}") print(f"准确率: {accuracy:.2f}") # 测试2:回归问题 print("\n2. 回归问题测试:") # 简单的一维回归数据 X_train_reg = [[1], [2], [3], [4], [5], [6]] y_train_reg = [2, 4, 6, 8, 10, 12] # y = 2x X_test_reg = [[2.5], [4.5]] y_test_reg = [5, 9] # 创建并训练KNN回归器 knn_regressor = KNN(k=2, distance_metric='euclidean') knn_regressor.fit(X_train_reg, y_train_reg) # 预测 predictions_reg = knn_regressor.predict(X_test_reg, 'regression') r2_score = knn_regressor.score(X_test_reg, y_test_reg, 'regression') print(f"训练数据: {X_train_reg}") print(f"训练标签: {y_train_reg}") print(f"测试数据: {X_test_reg}") print(f"真实值: {y_test_reg}") print(f"预测值: {[f'{x:.2f}' for x in predictions_reg]}") print(f"R²分数: {r2_score:.2f}") # 测试3:手动使用函数 print("\n3. 手动函数使用示例:") # 准备训练数据(格式:[(features, label), ...]) training_data = [] for i in range(len(X_train_class)): training_data.append((X_train_class[i], y_train_class[i])) test_point = [1, 3] neighbors = get_neighbors(training_data, test_point, k=3) print(f"测试点: {test_point}") print("最近的3个邻居:") for i, (point, distance, label) in enumerate(neighbors): print(f" 邻居{i+1}: 点{point[0]}, 距离{distance:.2f}, 标签{label}") prediction = predict_classification(neighbors) print(f"预测标签: {prediction}")
2301_80822435/machine-learning-course
assignment4/2班47.py
Python
mit
7,708
import math # 导入数学模块 def euclidean_distance(point1, point2): # 计算欧几里得距离 return math.sqrt(sum((a - b) ** 2 for a, b in zip(point1, point2))) # 计算两点间距离 def knn_predict(train_data, train_labels, test_point, k=3): # K近邻预测函数 distances = [] # 存储距离的列表 for i, train_point in enumerate(train_data): # 遍历训练数据 dist = euclidean_distance(test_point, train_point) # 计算测试点到训练点的距离 distances.append((dist, train_labels[i])) # 存储距离和对应标签 distances.sort(key=lambda x: x[0]) # 按距离从小到大排序 k_nearest = distances[:k] # 取前k个最近邻 k_labels = [label for _, label in k_nearest] # 提取k个最近邻的标签 # 返回出现次数最多的标签 return max(set(k_labels), key=k_labels.count) # 统计并返回最多出现的标签 # 测试代码 if __name__ == "__main__": # 训练数据:特征 train_data = [ [1, 2], [1, 4], [2, 1], [2, 3], # 类别0 [5, 6], [6, 5], [7, 7], [6, 8] # 类别1 ] # 训练数据:标签 train_labels = [0, 0, 0, 0, 1, 1, 1, 1] # 对应标签 # 测试点 test_point = [3, 3] # 待分类的点 # 使用KNN预测 prediction = knn_predict(train_data, train_labels, test_point, k=3) # K=3进行预测 print(f"测试点 {test_point} 的预测类别是: {prediction}") # 输出预测结果
2301_80822435/machine-learning-course
assignment4/2班49.py
Python
mit
1,502
import math def euclidean_distance(x1, x2): """ 计算两个数据点之间的欧氏距离 参数: x1, x2: 数据点(列表或元组) 返回: 欧氏距离 """ return math.sqrt(sum((x1[i] - x2[i]) ** 2 for i in range(len(x1)))) def find_k_nearest_neighbors(x, X_train, k): """ 找到数据点x的k个最近邻 参数: x: 待查询的数据点 X_train: 训练数据点列表 k: 近邻数量 返回: k个最近邻的索引列表 """ distances = [(i, euclidean_distance(x, X_train[i])) for i in range(len(X_train))] distances.sort(key=lambda item: item[1]) return [idx for idx, _ in distances[:k]] def KNN_predict(x, X_train, y_train, k): """ K近邻分类预测 参数: x: 待预测的数据点 X_train: 训练数据点列表 y_train: 训练标签列表 k: 近邻数量 返回: 预测的类别 """ neighbors_idx = find_k_nearest_neighbors(x, X_train, k) neighbor_labels = [y_train[i] for i in neighbors_idx] # 投票决定类别 label_counts = {} for label in neighbor_labels: label_counts[label] = label_counts.get(label, 0) + 1 # 返回出现次数最多的类别 return max(label_counts, key=label_counts.get) def KNN_predict_regression(x, X_train, y_train, k): """ K近邻回归预测 参数: x: 待预测的数据点 X_train: 训练数据点列表 y_train: 训练值列表 k: 近邻数量 返回: 预测值(k个近邻的平均值) """ neighbors_idx = find_k_nearest_neighbors(x, X_train, k) neighbor_values = [y_train[i] for i in neighbors_idx] return sum(neighbor_values) / len(neighbor_values) # 测试示例 if __name__ == "__main__": # 分类示例 print("=== KNN分类示例 ===") X_train = [ [1, 1], [1, 2], [2, 1], [2, 2], [5, 5], [5, 6], [6, 5], [6, 6], [9, 9], [9, 10], [10, 9], [10, 10] ] y_train = [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2] test_point = [3, 3] k = 3 prediction = KNN_predict(test_point, X_train, y_train, k) print(f"测试点 {test_point} 的预测类别: {prediction}") # 回归示例 print("\n=== KNN回归示例 ===") X_train_reg = [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]] y_train_reg = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] test_point_reg = [5.5] k_reg = 3 prediction_reg = KNN_predict_regression(test_point_reg, X_train_reg, y_train_reg, k_reg) print(f"测试点 {test_point_reg} 的预测值: {prediction_reg}")
2301_80822435/machine-learning-course
assignment4/2班50.py
Python
mit
2,698
""" 手动实现K近邻算法(K-Nearest Neighbors, KNN) 只使用Python标准库 """ import math def knn_predict(X_train, y_train, x_test, k=3, weighted=True): """ K近邻预测(分类)- 简洁版本 参数: X_train: 训练特征 [[x1, x2, ...], ...] y_train: 训练标签 [label1, label2, ...] x_test: 测试点 [x1, x2, ...] 或测试点列表 [[x1, x2, ...], ...] k: 最近邻数量 weighted: 是否使用距离加权投票(True=加权,False=简单投票) 返回: 预测结果(单个值或列表) """ # 处理单个测试点 if isinstance(x_test[0], (int, float)): return _knn_single(X_train, y_train, x_test, k, weighted) # 批量预测 return [_knn_single(X_train, y_train, x, k, weighted) for x in x_test] def _knn_single(X_train, y_train, x, k, weighted): """单个测试点的KNN预测""" # 计算距离并排序,取前k个 neighbors = sorted( [(math.sqrt(sum((a - b) ** 2 for a, b in zip(x, xi))), yi) for xi, yi in zip(X_train, y_train)], key=lambda d: d[0] )[:k] if weighted: # 距离加权投票:权重 = 1/(距离+1e-10) 避免除零 votes = {} for dist, label in neighbors: weight = 1.0 / (dist + 1e-10) votes[label] = votes.get(label, 0) + weight return max(votes.items(), key=lambda x: x[1])[0] else: # 简单投票:选择k个最近邻中最常见的标签 labels = [label for _, label in neighbors] return max(set(labels), key=labels.count) def knn_regress(X_train, y_train, x_test, k=3, weighted=True): """ 返回: 预测值(单个值或列表) """ # 处理单个测试点 if isinstance(x_test[0], (int, float)): return _knn_regress_single(X_train, y_train, x_test, k, weighted) # 批量预测 return [_knn_regress_single(X_train, y_train, x, k, weighted) for x in x_test] def _knn_regress_single(X_train, y_train, x, k, weighted): """单个测试点的KNN回归""" # 计算距离并排序,取前k个 neighbors = sorted( [(math.sqrt(sum((a - b) ** 2 for a, b in zip(x, xi))), yi) for xi, yi in zip(X_train, y_train)], key=lambda d: d[0] )[:k] if weighted: # 距离加权平均:权重 = 1/(距离+1e-10) weights = [1.0 / (dist + 1e-10) for dist, _ in neighbors] values = [val for _, val in neighbors] return sum(w * v for w, v in zip(weights, values)) / sum(weights) else: # 简单平均 return sum(val for _, val in neighbors) / k # 测试代码 if __name__ == "__main__": print("=" * 60) print("K近邻算法(简洁版)") print("=" * 60) # 分类示例 print("\n【分类示例】") X_train = [[1, 1], [1.5, 1.5], [2, 2], [5, 5], [5.5, 5.5], [6, 6]] y_train = [0, 0, 0, 1, 1, 1] X_test = [[1.2, 1.2], [5.3, 5.3], [3.5, 3.5]] print("训练数据:", list(zip(X_train, y_train))) print("测试数据:", X_test) # 加权投票 preds_weighted = knn_predict(X_train, y_train, X_test, k=3, weighted=True) print("加权投票预测:", preds_weighted) # 简单投票 preds_simple = knn_predict(X_train, y_train, X_test, k=3, weighted=False) print("简单投票预测:", preds_simple) # 单个点预测 single_pred = knn_predict(X_train, y_train, [2, 2], k=3) print("单点预测 [2,2]:", single_pred) # 回归示例 print("\n【回归示例】") X_train_reg = [[1, 1], [2, 2], [3, 3], [4, 4], [5, 5]] y_train_reg = [2.1, 4.0, 5.9, 8.2, 10.1] X_test_reg = [[1.5, 1.5], [3.5, 3.5]] print("训练数据:", list(zip(X_train_reg, y_train_reg))) print("测试数据:", X_test_reg) # 加权平均 reg_weighted = knn_regress(X_train_reg, y_train_reg, X_test_reg, k=3, weighted=True) print("加权平均预测:", [f"{x:.2f}" for x in reg_weighted]) # 简单平均 reg_simple = knn_regress(X_train_reg, y_train_reg, X_test_reg, k=3, weighted=False) print("简单平均预测:", [f"{x:.2f}" for x in reg_simple]) print("\n" + "=" * 60)
2301_80822435/machine-learning-course
assignment4/2班51.py
Python
mit
4,267
import math from collections import Counter # Counter 用来统计邻居标签出现次数 from typing import List # 为函数/变量添加类型提示,提高可读性和 IDE 支持 def euclidean_distance(a: List[float], b: List[float]) -> float: """ 计算两条等长向量的欧氏距离。 """ if len(a) != len(b): raise ValueError("向量维度不一致")# 防止维度不匹配导致 zip 失真 return math.sqrt(sum((x - y) ** 2 for x, y in zip(a, b))) class KNN: """ 手动实现的 K 近邻分类器。 """ def __init__(self, k: int, label_num: int): """ :param k: 近邻数目 :param label_num: 类别总数(用于统计) """ if k <= 0: raise ValueError("k 必须为正整数") self.k = k self.label_num = label_num self.x_train: List[List[float]] = [] # 训练特征矩阵(列表的列表) self.y_train: List[int] = [] # 训练标签向量 def fit(self, x_train: List[List[float]], y_train: List[int]) -> None: """ 保存训练数据。 """ if len(x_train) != len(y_train): raise ValueError("特征和标签数量不匹配") self.x_train = x_train self.y_train = y_train def _get_knn_indices(self, x: List[float]) -> List[int]: """ 返回距离样本 x 最近的 k 个训练样本的索引。 """ # 计算所有训练样本到 x 的距离 distances = [euclidean_distance(sample, x) for sample in self.x_train] # 按距离升序排列,取前 k 个索引 sorted_indices = sorted(range(len(distances)), key=lambda i: distances[i]) return sorted_indices[:self.k] def _vote_label(self, knn_indices: List[int]) -> int: """ 根据 k 个最近邻的标签进行投票,返回出现次数最多的标签。 """ # 统计邻居标签出现次数 label_counter = Counter(self.y_train[i] for i in knn_indices) # 选取出现次数最多的标签(若出现次数相同,取最小标签号) most_common_label, _ = max(label_counter.items(), key=lambda item: (item[1], -item[0])) return most_common_label def predict(self, x_test: List[List[float]]) -> List[int]: """ 对测试集进行预测,返回预测标签列表。 """ predictions = [] for x in x_test: knn_idx = self._get_knn_indices(x) # 找最近的 k 个邻居 pred_label = self._vote_label(knn_idx) # 投票决定标签 predictions.append(pred_label) return predictions # ------------------- 示例 ------------------- if __name__ == "__main__": # 简单的二维数据集 X_train = [ [1.0, 2.0], [1.5, 1.8], [5.0, 8.0], [6.0, 9.0], [1.0, 0.6], [9.0, 11.0], ] y_train = [0, 0, 1, 1, 0, 1] # 两类标签 0 / 1 X_test = [ [2.0, 3.0], [8.0, 9.0], [0.5, 0.5], ] knn = KNN(k=3, label_num=2) # k=3 表示看最近的 3 个邻居,label_num=2 表示共有 2 类 knn.fit(X_train, y_train) # 训练(其实只是保存数据) y_pred = knn.predict(X_test) # 预测 print("预测结果:", y_pred) # 示例输出: [0, 1, 0]
2301_80822435/machine-learning-course
assignment4/2班54.py
Python
mit
3,365
import numpy as np from collections import Counter import matplotlib.pyplot as plt plt.rcParams['font.family'] = 'SimHei' plt.rcParams['axes.unicode_minus'] = False class KNearestNeighbors: def __init__(self, k=3): self.k = k self.X_train = None self.y_train = None def fit(self, X, y): self.X_train = np.array(X) self.y_train = np.array(y) def _distance(self, x1, x2): return np.sqrt(np.sum((x1 - x2) ** 2)) def predict(self, X): X = np.array(X) predictions = [] for test_point in X: distances = [(self._distance(test_point, train_point), label) for train_point, label in zip(self.X_train, self.y_train)] distances.sort(key=lambda x: x[0]) k_neighbors = [label for _, label in distances[:self.k]] most_common = Counter(k_neighbors).most_common(1)[0][0] predictions.append(most_common) return np.array(predictions) def score(self, X, y): y_pred = self.predict(X) return np.mean(y_pred == y) if __name__ == "__main__": np.random.seed(42) class0 = np.random.normal([2, 2], 1, (50, 2)) class1 = np.random.normal([6, 6], 1, (50, 2)) X = np.vstack([class0, class1]) y = np.hstack([np.zeros(50), np.ones(50)]) split_idx = int(0.8 * len(X)) X_train, X_test = X[:split_idx], X[split_idx:] y_train, y_test = y[:split_idx], y[split_idx:] print(f"训练集: {len(X_train)}, 测试集: {len(X_test)}") k_values = [1, 3, 5, 7, 9] accuracies = [] for k in k_values: knn = KNearestNeighbors(k=k) knn.fit(X_train, y_train) accuracy = knn.score(X_test, y_test) accuracies.append(accuracy) print(f"k={k}, 准确率: {accuracy:.4f}") plt.figure(figsize=(12, 5)) plt.subplot(1, 2, 1) plt.plot(k_values, accuracies, 'bo-') plt.xlabel('k值') plt.ylabel('准确率') plt.title('不同k值的准确率') plt.grid(True, alpha=0.3) plt.subplot(1, 2, 2) x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx, yy = np.meshgrid(np.linspace(x_min, x_max, 50), np.linspace(y_min, y_max, 50)) knn = KNearestNeighbors(k=3) knn.fit(X_train, y_train) Z = knn.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape) plt.contourf(xx, yy, Z, alpha=0.3) plt.scatter(X_train[y_train == 0, 0], X_train[y_train == 0, 1], c='blue', label='类别0-训练', alpha=0.7) plt.scatter(X_train[y_train == 1, 0], X_train[y_train == 1, 1], c='red', label='类别1-训练', alpha=0.7) plt.scatter(X_test[y_test == 0, 0], X_test[y_test == 0, 1], c='blue', marker='^', label='类别0-测试') plt.scatter(X_test[y_test == 1, 0], X_test[y_test == 1, 1], c='red', marker='^', label='类别1-测试') plt.xlabel('特征1') plt.ylabel('特征2') plt.title('KNN分类结果 (k=3)') plt.legend() plt.tight_layout() plt.show() new_samples = np.array([[3, 3], [5, 5], [2, 6]]) predictions = knn.predict(new_samples) print("\n新样本预测:") for sample, pred in zip(new_samples, predictions): print(f"样本{sample} -> 类别{int(pred)}")
2301_80822435/machine-learning-course
assignment4/2班55.py
Python
mit
3,357
import math class KNN: def __init__(self, k=3, task='classification'): self.k = k self.task = task self.X_train = None self.y_train = None def fit(self, X, y): self.X_train = X self.y_train = y return self def _euclidean_distance(self, a, b): distance = 0.0 for i in range(len(a)): distance += (a[i] - b[i]) ** 2 return math.sqrt(distance) def _get_k_neighbors(self, x): distances = [] for i in range(len(self.X_train)): dist = self._euclidean_distance(x, self.X_train[i]) distances.append((i, dist)) for i in range(len(distances)): for j in range(i + 1, len(distances)): if distances[i][1] > distances[j][1]: distances[i], distances[j] = distances[j], distances[i] return distances[:self.k] def _most_common(self, labels): count_dict = {} for label in labels: if label in count_dict: count_dict[label] += 1 else: count_dict[label] = 1 max_count = 0 most_common_label = None for label, count in count_dict.items(): if count > max_count: max_count = count most_common_label = label return most_common_label def predict(self, X): predictions = [] for sample in X: neighbors = self._get_k_neighbors(sample) neighbor_labels = [self.y_train[idx] for idx, _ in neighbors] if self.task == 'classification': prediction = self._most_common(neighbor_labels) predictions.append(prediction) elif self.task == 'regression': total = 0.0 for label in neighbor_labels: total += label predictions.append(total / len(neighbor_labels)) return predictions def predict_proba(self, X): if self.task != 'classification': raise ValueError("predict_proba 仅适用于分类任务") probabilities = [] for sample in X: neighbors = self._get_k_neighbors(sample) neighbor_labels = [self.y_train[idx] for idx, _ in neighbors] label_count = {} for label in neighbor_labels: if label in label_count: label_count[label] += 1 else: label_count[label] = 1 total = len(neighbors) all_labels = sorted(set(self.y_train)) prob_list = [] for label in all_labels: count = label_count.get(label, 0) prob_list.append(count / total) probabilities.append(prob_list) return probabilities def score(self, X, y): predictions = self.predict(X) if self.task == 'classification': correct = 0 for i in range(len(predictions)): if predictions[i] == y[i]: correct += 1 return correct / len(y) else: total_y = 0.0 for value in y: total_y += value mean_y = total_y / len(y) ss_tot = 0.0 for value in y: ss_tot += (value - mean_y) ** 2 ss_res = 0.0 for i in range(len(y)): ss_res += (y[i] - predictions[i]) ** 2 if ss_tot == 0: return 0.0 return 1 - (ss_res / ss_tot)
2301_80822435/machine-learning-course
assignment4/2班56.py
Python
mit
3,610
import numpy as np from collections import Counter import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False class KNN: def __init__(self, k=3): self.k = k self.X_train = None self.y_train = None def fit(self, X, y): self.X_train, self.y_train = np.array(X), np.array(y) return self def _distance(self, x1, x2, metric='euclidean'): if metric == 'euclidean': return np.sqrt(np.sum((x1 - x2) ** 2)) elif metric == 'manhattan': return np.sum(np.abs(x1 - x2)) raise ValueError("距离度量支持: 'euclidean' 或 'manhattan'") def predict(self, X, metric='euclidean'): X = np.array(X) return np.array([self._predict_single(x, metric) for x in X]) def _predict_single(self, x, metric): distances = [self._distance(x, x_train, metric) for x_train in self.X_train] k_indices = np.argsort(distances)[:self.k] k_labels = self.y_train[k_indices] return Counter(k_labels).most_common(1)[0][0] def score(self, X, y, metric='euclidean'): return np.mean(self.predict(X, metric) == y) if __name__ == "__main__": np.random.seed(42) # 生成数据 class0 = np.column_stack((np.random.normal(0, 1, 50), np.random.normal(0, 1, 50))) class1 = np.column_stack((np.random.normal(3, 1, 50), np.random.normal(3, 1, 50))) X = np.vstack((class0, class1)) y = np.hstack((np.zeros(50), np.ones(50))) # 打乱并分割 indices = np.random.permutation(len(X)) X, y = X[indices], y[indices] split = int(0.8 * len(X)) X_train, X_test, y_train, y_test = X[:split], X[split:], y[:split], y[split:] print(f"训练集: {X_train.shape}, 测试集: {X_test.shape}") # 测试不同k值 k_values = [1, 3, 5, 7, 9] accuracies = [] for k in k_values: accuracy = KNN(k=k).fit(X_train, y_train).score(X_test, y_test) accuracies.append(accuracy) print(f"k={k}, 准确率: {accuracy:.4f}") # 可视化 fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(15, 5)) # 数据分布 ax1.scatter(X_train[y_train == 0, 0], X_train[y_train == 0, 1], c='red', label='类别 0', alpha=0.6) ax1.scatter(X_train[y_train == 1, 0], X_train[y_train == 1, 1], c='blue', label='类别 1', alpha=0.6) ax1.scatter(X_test[:, 0], X_test[:, 1], c='green', marker='x', label='测试点', s=100) ax1.set_xlabel('特征 1'), ax1.set_ylabel('特征 2'), ax1.set_title('数据分布') ax1.legend(), ax1.grid(True, alpha=0.3) # k值影响 ax2.plot(k_values, accuracies, 'bo-', linewidth=2, markersize=8) ax2.set_xlabel('k值'), ax2.set_ylabel('准确率'), ax2.set_title('k值对准确率的影响') ax2.grid(True, alpha=0.3) # 决策边界 best_k = k_values[np.argmax(accuracies)] knn = KNN(k=best_k).fit(X_train, y_train) x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.1), np.arange(y_min, y_max, 0.1)) Z = knn.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape) ax3.contourf(xx, yy, Z, alpha=0.3, cmap=plt.cm.RdYlBu) ax3.scatter(X_train[y_train == 0, 0], X_train[y_train == 0, 1], c='red', label='类别 0', alpha=0.6) ax3.scatter(X_train[y_train == 1, 0], X_train[y_train == 1, 1], c='blue', label='类别 1', alpha=0.6) ax3.set_xlabel('特征 1'), ax3.set_ylabel('特征 2'), ax3.set_title(f'决策边界 (k={best_k})') ax3.legend(), ax3.grid(True, alpha=0.3) plt.tight_layout() plt.show() # 距离度量比较 print("\n距离度量比较:") knn = KNN(k=3).fit(X_train, y_train) for metric in ['euclidean', 'manhattan']: accuracy = knn.score(X_test, y_test, metric) print(f"{metric}距离准确率: {accuracy:.4f}")
2301_80822435/machine-learning-course
assignment4/2班57.py
Python
mit
3,930
import numpy as np from collections import Counter from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.metrics import accuracy_score, classification_report import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False class KNN: def __init__(self, k=3, distance_metric='euclidean'): self.k = k self.distance_metric = distance_metric self.X_train = None self.y_train = None def fit(self, X, y): """ 训练模型(kNN只是存储数据) """ self.X_train = X self.y_train = y return self def _calculate_distance(self, x1, x2): """ 计算两个样本之间的距离 """ if self.distance_metric == 'euclidean': return np.sqrt(np.sum((x1 - x2) ** 2)) elif self.distance_metric == 'manhattan': return np.sum(np.abs(x1 - x2)) elif self.distance_metric == 'minkowski': # 这里使用p=3作为示例 return np.sum(np.abs(x1 - x2) ** 3) ** (1 / 3) else: raise ValueError("不支持的距離度量方法") def predict(self, X): """ 预测类别 """ predictions = [self._predict_single(x) for x in X] return np.array(predictions) def _predict_single(self, x): """ 预测单个样本的类别 """ # 计算所有训练样本与当前样本的距离 distances = [] for i, x_train in enumerate(self.X_train): dist = self._calculate_distance(x, x_train) distances.append((dist, self.y_train[i])) # 按距离排序并选择前k个邻居 distances.sort(key=lambda x: x[0]) k_nearest = distances[:self.k] # 获取k个邻居的标签 k_labels = [label for _, label in k_nearest] # 返回最常见的标签 most_common = Counter(k_labels).most_common(1) return most_common[0][0] def predict_proba(self, X): """ 预测概率(每个类别的概率) """ probas = [] for x in X: # 计算所有训练样本与当前样本的距离 distances = [] for i, x_train in enumerate(self.X_train): dist = self._calculate_distance(x, x_train) distances.append((dist, self.y_train[i])) # 按距离排序并选择前k个邻居 distances.sort(key=lambda x: x[0]) k_nearest = distances[:self.k] # 获取k个邻居的标签 k_labels = [label for _, label in k_nearest] # 计算每个类别的概率 label_counts = Counter(k_labels) proba = {label: count / self.k for label, count in label_counts.items()} probas.append(proba) return probas # 示例:使用鸢尾花数据集测试kNN算法 def example_usage(): # 加载数据 iris = load_iris() X, y = iris.data, iris.target # 数据分割 X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.3, random_state=42, stratify=y ) # 数据标准化 scaler = StandardScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test) # 创建并训练kNN模型 knn = KNN(k=5, distance_metric='euclidean') knn.fit(X_train, y_train) # 预测 y_pred = knn.predict(X_test) # 评估模型 accuracy = accuracy_score(y_test, y_pred) print(f"准确率: {accuracy:.4f}") print("\n分类报告:") print(classification_report(y_test, y_pred, target_names=iris.target_names)) return knn, X_test, y_test, y_pred # 可视化结果 def plot_results(X_test, y_test, y_pred, feature_names, target_names): """ 可视化预测结果(使用前两个特征) """ plt.figure(figsize=(12, 5)) # 真实标签 plt.subplot(1, 2, 1) scatter = plt.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap='viridis', alpha=0.7) plt.xlabel(feature_names[0]) plt.ylabel(feature_names[1]) plt.title('真实标签') plt.colorbar(scatter, ticks=range(len(target_names))) # 预测标签 plt.subplot(1, 2, 2) scatter = plt.scatter(X_test[:, 0], X_test[:, 1], c=y_pred, cmap='viridis', alpha=0.7) plt.xlabel(feature_names[0]) plt.ylabel(feature_names[1]) plt.title('预测标签') plt.colorbar(scatter, ticks=range(len(target_names))) plt.tight_layout() plt.show() # 测试不同k值的影响 def test_different_k(): iris = load_iris() X, y = iris.data, iris.target X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.3, random_state=42, stratify=y ) scaler = StandardScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test) k_values = range(1, 16) accuracies = [] for k in k_values: knn = KNN(k=k) knn.fit(X_train, y_train) y_pred = knn.predict(X_test) accuracy = accuracy_score(y_test, y_pred) accuracies.append(accuracy) print(f"k={k}: 准确率 = {accuracy:.4f}") # 绘制k值与准确率的关系 plt.figure(figsize=(10, 6)) plt.plot(k_values, accuracies, 'bo-', linewidth=2, markersize=8) plt.xlabel('k值') plt.ylabel('准确率') plt.title('k值对kNN算法性能的影响') plt.grid(True, alpha=0.3) plt.show() # 找到最佳k值 best_k = k_values[np.argmax(accuracies)] best_accuracy = max(accuracies) print(f"\n最佳k值: {best_k}, 最高准确率: {best_accuracy:.4f}") if __name__ == "__main__": print("=== kNN算法实现示例 ===\n") # 基本使用示例 print("1. 基本使用示例:") knn_model, X_test, y_test, y_pred = example_usage() # 可视化结果 iris = load_iris() plot_results(X_test, y_test, y_pred, iris.feature_names, iris.target_names) # 测试不同k值 print("\n2. 测试不同k值的影响:") test_different_k() # 预测概率示例 print("\n3. 预测概率示例:") probas = knn_model.predict_proba(X_test[:3]) for i, proba in enumerate(probas): print(f"样本 {i + 1} 的预测概率: {proba}")
2301_80822435/machine-learning-course
assignment4/2班59.py
Python
mit
6,382
import numpy as np from collections import Counter class KNN: def __init__(self, k=3): """初始化KNN模型,指定近邻数量k""" self.k = k self.X_train = None # 训练特征 self.y_train = None # 训练标签 def fit(self, X, y): """训练模型(KNN是惰性学习,仅存储训练数据)""" self.X_train = X self.y_train = y def _euclidean_distance(self, x1, x2): """计算两个样本之间的欧氏距离""" return np.sqrt(np.sum((x1 - x2) **2)) def predict(self, X): """预测新样本的类别""" predictions = [self._predict_single(x) for x in X] return np.array(predictions) def _predict_single(self, x): """预测单个样本的类别""" # 1. 计算与所有训练样本的距离 distances = [self._euclidean_distance(x, x_train) for x_train in self.X_train] # 2. 按距离排序,取前k个样本的索引 k_indices = np.argsort(distances)[:self.k] # 3. 取前k个样本的标签 k_nearest_labels = [self.y_train[i] for i in k_indices] # 4. 多数投票决定预测结果 most_common = Counter(k_nearest_labels).most_common(1) return most_common[0][0] # 测试代码 if __name__ == "__main__": # 生成示例数据(分类问题:两个类别) X_train = np.array([ [1, 2], [2, 3], [3, 4], [6, 7], [7, 8], [8, 9] # 特征 ]) y_train = np.array([0, 0, 0, 1, 1, 1]) # 标签(0或1) # 初始化并训练模型 knn = KNN(k=3) knn.fit(X_train, y_train) # 预测新样本 X_test = np.array([[4, 5], [5, 6]]) # 待预测样本 predictions = knn.predict(X_test) print("预测结果:", predictions) # 输出:[0 1](根据距离判断)
2301_80822435/machine-learning-course
assignment4/2班61.py
Python
mit
1,851
import math import heapq def euclidean_distance(x1, x2): if len(x1) != len(x2): raise ValueError("两个样本的维度必须一致") dist_sq = 0.0 for a, b in zip(x1, x2): dist_sq += (a - b) ** 2 return math.sqrt(dist_sq) def knn_classify(train_data, train_labels, x, k=3, distance_func=euclidean_distance): if len(train_data) != len(train_labels): raise ValueError("训练数据与标签数量必须一致") if not isinstance(k, int) or k <= 0: raise ValueError("k必须是正整数") if k > len(train_data): raise ValueError("k不能大于训练样本数量") if len(train_data) == 0: raise ValueError("训练数据集不能为空") # 校验待预测样本与训练样本维度一致 dim = len(train_data[0]) if len(x) != dim: raise ValueError(f"待预测样本维度({len(x)})与训练样本维度({dim})不一致") distance_label = [] for idx, train_x in enumerate(train_data): dist = distance_func(x, train_x) distance_label.append( (dist, train_labels[idx]) ) # heapq.nlargest 取最大的k个,这里取负距离实现“最小k个”(比排序后切片更高效) k_nearest = heapq.nsmallest(k, distance_label, key=lambda item: item[0]) label_count = {} for dist, label in k_nearest: if label in label_count: label_count[label] += 1 else: label_count[label] = 1 # 找出投票数最多的标签(若有平局,返回先出现的最多标签) max_count = 0 result_label = None for label, count in label_count.items(): if count > max_count: max_count = count result_label = label return result_label class KNNClassifier: def __init__(self, k=3, distance_func=euclidean_distance): self.k = k self.distance_func = distance_func self.train_data = None self.train_labels = None def fit(self, train_data, train_labels): # 校验输入合法性(复用核心函数的校验逻辑) if len(train_data) != len(train_labels): raise ValueError("训练数据与标签数量必须一致") if len(train_data) == 0: raise ValueError("训练数据集不能为空") self.train_data = train_data self.train_labels = train_labels def predict(self, x): if self.train_data is None or self.train_labels is None: raise RuntimeError("请先调用fit()方法训练模型") return knn_classify( self.train_data, self.train_labels, x, self.k, self.distance_func ) def predict_batch(self, X): return [self.predict(x) for x in X] if __name__ == "__main__": train_data = [ [5.1, 3.5], [4.9, 3.0], [4.7, 3.2], [4.6, 3.1], [5.0, 3.6], # 0类 [5.4, 3.9], [4.6, 3.4], [5.0, 3.4], [4.4, 2.9], [4.9, 3.1], # 0类 [6.0, 2.2], [5.8, 2.6], [5.6, 2.8], [5.9, 3.0], [5.5, 2.4], # 1类 [5.7, 2.8], [5.7, 2.6], [5.8, 2.7], [6.2, 2.9], [5.6, 2.2], # 1类 [6.3, 3.3], [5.8, 2.7], [7.1, 3.0], [6.3, 2.9], [6.5, 3.0], # 2类 [6.2, 3.4], [5.9, 3.0], [6.1, 3.0], [6.4, 2.8], [6.6, 3.0] # 2类 ] train_labels = [0]*10 + [1]*10 + [2]*10 # 对应3类标签 # 待预测样本 test_samples = [ [5.0, 3.5], # 预期标签0 [5.8, 2.7], # 预期标签1 [6.4, 3.1], # 预期标签2 [5.2, 2.8] # 预期标签1 ] # 初始化并训练KNN分类器(k=5) knn = KNNClassifier(k=5) knn.fit(train_data, train_labels) predictions = knn.predict_batch(test_samples) print("KNN分类预测结果:") for idx, sample in enumerate(test_samples): print(f"样本{sample} -> 预测标签:{predictions[idx]}")
2301_80822435/machine-learning-course
assignment4/2班63.py
Python
mit
3,818
import numpy as np from collections import Counter class SimpleKNN: def __init__(self, k=3): self.k = k self.X_train = None self.y_train = None # 计算欧氏距离 def _distance(self, x1, x2): return np.sqrt(np.sum((x1 - x2) ** 2, axis=1)) # 训练 def fit(self, X_train, y_train): self.X_train = X_train self.y_train = y_train # 预测 def predict(self, X_test): predictions = [] for x in X_test: dists = self._distance(x, self.X_train) k_neighbor_labels = self.y_train[np.argsort(dists)[:self.k]] predictions.append(Counter(k_neighbor_labels).most_common(1)[0][0]) return np.array(predictions) if __name__ == "__main__": X_train = np.array([[1,2], [2,3], [3,4], [4,5], [1,3], [4,3]]) y_train = np.array([0, 0, 0, 1, 1, 1]) # 测试样本 X_test = np.array([[2,2], [3,3]]) # 运行KNN knn = SimpleKNN(k=3) knn.fit(X_train, y_train) y_pred = knn.predict(X_test) print("预测结果:", y_pred)
2301_80822435/machine-learning-course
assignment4/2班64.py
Python
mit
1,095
import math from collections import Counter def euclidean_distance(x1, x2): """ 计算两个向量之间的欧几里得距离。 """ distance = 0.0 for a, b in zip(x1, x2): distance += (a - b) ** 2 return math.sqrt(distance) class KNN: def __init__(self, k=3, task_type='classification'): """ 初始化 KNN 分类器/回归器。 参数: k (int): 近邻数量。 task_type (str): 任务类型, 'classification' (分类) 或 'regression' (回归)。 """ if k <= 0: raise ValueError("k 必须是正整数") self.k = k self.task_type = task_type.lower() if self.task_type not in ['classification', 'regression']: raise ValueError("task_type 必须是 'classification' 或 'regression'") # KNN 不训练模型,只存储数据 self.X_train = None self.y_train = None def fit(self, X, y): """ 拟合模型,即存储训练数据。 参数: X (list of lists): 训练特征向量。 y (list): 训练标签。 """ if len(X) != len(y): raise ValueError("特征向量 X 和标签 y 的长度必须相同") self.X_train = X self.y_train = y def predict(self, X): """ 对新样本进行预测。 参数: X (list of lists): 待预测的特征向量。 返回: list: 预测结果。 """ if self.X_train is None or self.y_train is None: raise ValueError("请先调用 fit 方法进行训练") predictions = [] for x in X: # 1. 计算距离 distances = [euclidean_distance(x, x_train) for x_train in self.X_train] # 2. 寻找 k 个最近邻的索引 # argsort 返回的是数组值从小到大的索引值 k_indices = sorted(range(len(distances)), key=lambda i: distances[i])[:self.k] # 3. 获取 k 个最近邻的标签 k_nearest_labels = [self.y_train[i] for i in k_indices] # 4. 根据任务类型进行预测 if self.task_type == 'classification': # 分类:投票表决 most_common = Counter(k_nearest_labels).most_common(1) predictions.append(most_common[0][0]) elif self.task_type == 'regression': # 回归:取平均值 prediction = sum(k_nearest_labels) / len(k_nearest_labels) predictions.append(prediction) return predictions
2301_80822435/machine-learning-course
assignment4/2班65.py
Python
mit
2,674
import numpy as np import matplotlib.pyplot as plt from collections import Counter from matplotlib.colors import ListedColormap import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] class KNN: def __init__(self, k=3, task='classification', label_num=None): self.k = k self.task = task self.label_num = label_num self.x_train = None self.y_train = None def fit(self, x_train, y_train): self.x_train = np.array(x_train) self.y_train = np.array(y_train) # 如果是分类任务且未指定类别数量,自动推断 if self.task == 'classification' and self.label_num is None: self.label_num = len(np.unique(y_train)) return self def euclidean_distance(self, a, b): return np.sqrt(np.sum(np.square(a - b))) def get_knn_indices(self, x): # 计算与所有训练样本的距离 distances = [self.euclidean_distance(train_sample, x) for train_sample in self.x_train] # 按距离排序并获取前k个索引 knn_indices = np.argsort(distances)[:self.k] return knn_indices def get_label(self, x): if self.task != 'classification': raise ValueError("此方法仅适用于分类任务") knn_indices = self.get_knn_indices(x) # 类别计数 label_statistic = np.zeros(shape=[self.label_num]) for index in knn_indices: label = int(self.y_train[index]) label_statistic[label] += 1 # 返回数量最多的类别 return np.argmax(label_statistic) def predict_single(self, x): knn_indices = self.get_knn_indices(x) if self.task == 'classification': # 分类任务:多数投票 neighbor_labels = [self.y_train[idx] for idx in knn_indices] most_common = Counter(neighbor_labels).most_common(1) return most_common[0][0] else: # 回归任务:取平均值 neighbor_values = [self.y_train[idx] for idx in knn_indices] return np.mean(neighbor_values) def predict(self, x_test): x_test = np.array(x_test) predicted_labels = np.zeros(shape=[len(x_test)]) for i, x in enumerate(x_test): predicted_labels[i] = self.predict_single(x) return predicted_labels def score(self, x_test, y_test): y_pred = self.predict(x_test) y_true = np.array(y_test) if self.task == 'classification': return np.mean(y_pred == y_true) else: return np.mean(np.square(y_pred - y_true)) # 测试MNIST数据集 def test_mnist(): print("=== MNIST手写数字分类测试 ===") np.random.seed(42) n_samples = 1000 n_features = 784 # 28x28像素 # 生成模拟的MNIST数据 x_train = np.random.randn(int(n_samples * 0.8), n_features) y_train = np.random.randint(0, 10, int(n_samples * 0.8)) x_test = np.random.randn(int(n_samples * 0.2), n_features) y_test = np.random.randint(0, 10, int(n_samples * 0.2)) print(f"训练集大小: {len(x_train)}") print(f"测试集大小: {len(x_test)}") # 测试不同的k值 accuracies = [] k_values = range(1, 10) for k in k_values: knn = KNN(k=k, task='classification', label_num=10) knn.fit(x_train, y_train) accuracy = knn.score(x_test, y_test) accuracies.append(accuracy) print(f'K的取值为 {k}, 预测准确率为 {accuracy * 100:.1f}%') # 绘制准确率随k值变化图 plt.figure(figsize=(10, 6)) plt.plot(k_values, accuracies, 'bo-', linewidth=2, markersize=8) plt.xlabel('K值') plt.ylabel('准确率') plt.title('MNIST数据集上KNN不同K值的准确率') plt.grid(True, alpha=0.3) plt.show() return accuracies def test_gaussian(): print("\n=== 高斯数据集分类测试 ===") # 生成高斯数据集 np.random.seed(42) n_samples = 200 # 生成两个高斯分布的数据 mean1, cov1 = [2, 2], [[1, 0.5], [0.5, 1]] mean2, cov2 = [-2, -2], [[1, -0.3], [-0.3, 1]] class1 = np.random.multivariate_normal(mean1, cov1, n_samples // 2) class2 = np.random.multivariate_normal(mean2, cov2, n_samples // 2) x_data = np.vstack([class1, class2]) y_data = np.hstack([np.zeros(n_samples // 2), np.ones(n_samples // 2)]) # 可视化原始数据 plt.figure(figsize=(8, 6)) plt.scatter(x_data[y_data == 0, 0], x_data[y_data == 0, 1], c='blue', marker='o', label='Class 0', alpha=0.7) plt.scatter(x_data[y_data == 1, 0], x_data[y_data == 1, 1], c='red', marker='x', label='Class 1', alpha=0.7) plt.xlabel('X axis') plt.ylabel('Y axis') plt.title('高斯数据集分布') plt.legend() plt.grid(True, alpha=0.3) plt.show() return x_data, y_data def visualize_decision_boundary(x_data, y_data, k_values=[1, 3, 10]): # 设置网格 step = 0.1 x_min, x_max = x_data[:, 0].min() - 1, x_data[:, 0].max() + 1 y_min, y_max = x_data[:, 1].min() - 1, x_data[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, step), np.arange(y_min, y_max, step)) grid_data = np.c_[xx.ravel(), yy.ravel()] # 创建子图 fig, axes = plt.subplots(1, len(k_values), figsize=(15, 5)) cmap_light = ListedColormap(['lightblue', 'lightcoral']) for i, k in enumerate(k_values): # 训练KNN模型 knn = KNN(k=k, task='classification', label_num=2) knn.fit(x_data, y_data) # 预测网格点 z = knn.predict(grid_data) z = z.reshape(xx.shape) # 绘制决策边界 ax = axes[i] ax.pcolormesh(xx, yy, z, cmap=cmap_light, alpha=0.8) ax.scatter(x_data[y_data == 0, 0], x_data[y_data == 0, 1], c='blue', marker='o', label='Class 0', alpha=0.7) ax.scatter(x_data[y_data == 1, 0], x_data[y_data == 1, 1], c='red', marker='x', label='Class 1', alpha=0.7) ax.set_xlabel('X axis') ax.set_ylabel('Y axis') ax.set_title(f'K = {k}') ax.legend() ax.grid(True, alpha=0.3) plt.tight_layout() plt.show() def test_regression(): print("\n=== KNN回归任务测试 ===") # 生成回归数据 np.random.seed(42) x = np.linspace(0, 10, 100) y = np.sin(x) + 0.1 * np.random.randn(100) # 划分训练测试集 split = int(0.8 * len(x)) x_train, x_test = x[:split].reshape(-1, 1), x[split:].reshape(-1, 1) y_train, y_test = y[:split], y[split:] # 训练KNN回归模型 knn = KNN(k=5, task='regression') knn.fit(x_train, y_train) y_pred = knn.predict(x_test) mse = knn.score(x_test, y_test) print(f"回归任务均方误差: {mse:.4f}") # 可视化回归结果 plt.figure(figsize=(10, 6)) plt.scatter(x_train, y_train, c='blue', alpha=0.6, label='训练数据') plt.scatter(x_test, y_test, c='green', alpha=0.6, label='测试数据') plt.scatter(x_test, y_pred, c='red', alpha=0.8, label='预测值') plt.xlabel('X') plt.ylabel('y') plt.title('KNN回归任务结果') plt.legend() plt.grid(True, alpha=0.3) plt.show() if __name__ == "__main__": # 运行所有测试 print("K近邻算法完整实现") print("=" * 50) # 1. MNIST分类测试 mnist_accuracies = test_mnist() # 2. 高斯数据集测试 x_gauss, y_gauss = test_gaussian() # 3. 可视化决策边界 print("\n=== 决策边界可视化 ===") visualize_decision_boundary(x_gauss, y_gauss) # 4. 回归任务测试 test_regression() # 总结 print("\n=== 算法总结 ===") print("KNN算法特点:") print("1. 简单直观,易于理解和实现") print("2. 无需训练过程,但预测时计算复杂度高") print("3. 对异常值敏感,需要合适的K值选择") print("4. 适用于小到中等规模的数据集")
2301_80822435/machine-learning-course
assignment4/2班66.py
Python
mit
8,271
import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap def distance(a, b): return np.sqrt(np.sum((a - b) ** 2)) class KNN: def __init__(self, k, label_num): self.k = k self.label_num = label_num def fit(self, x_train, y_train): self.x_train = x_train self.y_train = y_train def get_knn_indices(self, x): dis = list(map(lambda a: distance(a, x), self.x_train)) knn_indices = np.argsort(dis)[:self.k] return knn_indices def get_label(self, x): knn_indices = self.get_knn_indices(x) label_statistic = np.zeros(self.label_num) for idx in knn_indices: label_statistic[int(self.y_train[idx])] += 1 return np.argmax(label_statistic) def predict(self, x_test): preds = np.zeros(len(x_test), dtype=int) for i, x in enumerate(x_test): preds[i] = self.get_label(x) return preds np.random.seed(0) x0 = np.random.randn(50, 2) + np.array([2, 2]) y0 = np.zeros(50) x1 = np.random.randn(50, 2) + np.array([7, 7]) y1 = np.ones(50) x_train = np.vstack([x0, x1]) y_train = np.hstack([y0, y1]) plt.figure() plt.scatter(x_train[y_train==0,0], x_train[y_train==0,1], c='blue', marker='o', label='Class 0') plt.scatter(x_train[y_train==1,0], x_train[y_train==1,1], c='red', marker='x', label='Class 1') plt.xlabel('X') plt.ylabel('Y') plt.title('Simple 2D Dataset') plt.legend() plt.show() np.random.seed(1) k = np.random.choice(np.arange(1, 11)) print(f"随机选择的 K 值为: {k}") cmap_light = ListedColormap(['lightblue', 'lightcoral']) x_min, x_max = x_train[:,0].min()-1, x_train[:,0].max()+1 y_min, y_max = x_train[:,1].min()-1, x_train[:,1].max()+1 xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.1), np.arange(y_min, y_max, 0.1)) grid_data = np.c_[xx.ravel(), yy.ravel()] knn = KNN(k=k, label_num=2) knn.fit(x_train, y_train) z = knn.predict(grid_data) plt.figure(figsize=(7,6)) plt.pcolormesh(xx, yy, z.reshape(xx.shape), cmap=cmap_light, alpha=0.5) plt.scatter(x_train[y_train==0,0], x_train[y_train==0,1], c='blue', marker='o', label='Class 0') plt.scatter(x_train[y_train==1,0], x_train[y_train==1,1], c='red', marker='x', label='Class 1') plt.xlabel('X') plt.ylabel('Y') plt.title(f'KNN Classification (K={k})') plt.legend() plt.show() pred_train = knn.predict(x_train) accuracy = np.mean(pred_train == y_train) print(f"K = {k} 时,训练集准确率 = {accuracy*100:.2f}%")
2301_80822435/machine-learning-course
assignment4/2班68.py
Python
mit
2,512
import numpy as np import matplotlib matplotlib.use('TkAgg') # 兼容 PyCharm 绘图后端 import matplotlib.pyplot as plt from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler # 解决中文乱码 plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False # ======================= # 距离函数:闵可夫斯基距离 # ======================= def minkowski_distance(a, b, p=2): return np.sum(np.abs(a - b) ** p) ** (1 / p) # ======================= # 自定义 KNN 分类器 # ======================= class KNN: def __init__(self, k=3, label_num=None, p=2): self.k = k self.label_num = label_num self.p = p # p=1 曼哈顿距离, p=2 欧氏距离 def fit(self, x_train, y_train): self.x_train = x_train self.y_train = y_train if self.label_num is None: self.label_num = len(np.unique(y_train)) def get_knn_indices(self, x): distances = [minkowski_distance(a, x, self.p) for a in self.x_train] knn_indices = np.argsort(distances)[:self.k] return knn_indices def get_label(self, x): knn_indices = self.get_knn_indices(x) label_count = np.zeros(self.label_num) for idx in knn_indices: label = int(self.y_train[idx]) label_count[label] += 1 return np.argmax(label_count) def predict(self, x_test): predictions = np.zeros(len(x_test), dtype=int) for i, x in enumerate(x_test): predictions[i] = self.get_label(x) return predictions # ======================= # 主程序入口 # ======================= if __name__ == "__main__": # 使用 Iris 数据集 iris = load_iris() X = iris.data[:, :2] # 取前两个特征便于可视化 y = iris.target # 数据标准化 scaler = StandardScaler() X = scaler.fit_transform(X) # 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) # 实例化并训练模型 knn = KNN(k=5, p=2) knn.fit(X_train, y_train) # 预测 y_pred = knn.predict(X_test) # 计算精度 accuracy = np.mean(y_pred == y_test) print(f"预测准确率: {accuracy * 100:.2f}%") # ============ 可视化 ============ x_min, x_max = X[:, 0].min() - 0.5, X[:, 0].max() + 0.5 y_min, y_max = X[:, 1].min() - 0.5, X[:, 1].max() + 0.5 xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02), np.arange(y_min, y_max, 0.02)) # 网格点预测 grid_points = np.c_[xx.ravel(), yy.ravel()] Z = knn.predict(grid_points) Z = Z.reshape(xx.shape) # 绘图 plt.figure(figsize=(8, 6)) plt.contourf(xx, yy, Z, alpha=0.3, cmap=plt.cm.rainbow) plt.scatter(X_test[:, 0], X_test[:, 1], c=y_test, edgecolors='k', cmap=plt.cm.rainbow) plt.title(f"KNN 分类结果 (k={knn.k}, p={knn.p}, 准确率={accuracy:.2f})") plt.xlabel("Feature 1") plt.ylabel("Feature 2") plt.show()
2301_80822435/machine-learning-course
assignment4/2班70.py
Python
mit
3,109
import math import random # ================================ # 1. 计算两点欧氏距离 # ================================ def euclidean_distance(x1, x2): distance = 0 for i in range(len(x1)): distance += (x1[i] - x2[i]) ** 2 return math.sqrt(distance) # ================================ # 2. KNN 分类器 # ================================ class KNN: def __init__(self, k=3): self.k = k self.X_train = None self.y_train = None # “训练”其实就是保存训练数据 def fit(self, X, y): self.X_train = X self.y_train = y # 预测单个样本 def predict_one(self, x): distances = [] # 1)计算所有训练样本到 x 的距离 for i in range(len(self.X_train)): d = euclidean_distance(x, self.X_train[i]) distances.append((d, self.y_train[i])) # (距离, 标签) # 2)按距离升序排序 distances.sort(key=lambda t: t[0]) # 3)取前 k 个 k_neighbors = distances[:self.k] # 4)投票:统计出现次数最多的类别 votes = {} for d, label in k_neighbors: votes[label] = votes.get(label, 0) + 1 # 返回投票最多的类别 return max(votes, key=votes.get) # 批量预测 def predict(self, X): return [self.predict_one(x) for x in X] # ================================ # 3. 测试代码(手动生成数据) # ================================ if __name__ == "__main__": # 随机生成两类二维数据 random.seed(0) X = [] y = [] # 类别0:中心在 (1,1) for _ in range(20): X.append([1 + random.random(), 1 + random.random()]) y.append(0) # 类别1:中心在 (3,3) for _ in range(20): X.append([3 + random.random(), 3 + random.random()]) y.append(1) # 创建模型 knn = KNN(k=3) knn.fit(X, y) # 测试样本 test = [[2, 2], [0.5, 0.5], [3.5, 3.2]] print("预测结果:", knn.predict(test))
2301_80822435/machine-learning-course
assignmnet4/2班58.py
Python
mit
2,143
import os import sys import binascii import struct import zlib import itertools import re from collections import defaultdict from PIL import Image from PySide6.QtWidgets import ( QMainWindow, QWidget, QVBoxLayout, QLabel, QLineEdit, QPushButton, QFileDialog, QTextEdit, QToolBar, QApplication, ) from PySide6.QtGui import QAction, QIcon import ctypes def resource_path(relative_path): """获取资源文件的绝对路径(适用于打包后的程序)""" try: # PyInstaller 创建的临时文件夹 base_path = sys._MEIPASS except Exception: base_path = os.path.dirname(os.path.abspath(__file__)) return os.path.join(base_path, relative_path) # 定义文件签名(Magic Numbers) SIGNATURES = [ (b'\x89\x50\x4E\x47\x0D\x0A\x1A\x0A', 'PNG', 'png'), (b'\x47\x49\x46\x38\x37\x61', 'GIF', 'gif'), (b'\x47\x49\x46\x38\x39\x61', 'GIF', 'gif'), (b'\xFF\xD8\xFF', 'JPEG', 'jpg'), (b'\x25\x50\x44\x46\x2D', 'PDF', 'pdf'), (b'\x50\x4B\x03\x04', 'ZIP', 'zip'), (b'\x1F\x8B\x08', 'GZIP', 'gz'), (b'\x52\x61\x72\x21\x1A\x07\x00', 'RAR', 'rar'), (b'\x52\x61\x72\x21\x1A\x07\x01\x00', 'RAR5', 'rar'), (b'\x4D\x5A\x90\x00', 'PE32', 'exe'), ] class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.setWindowTitle("图像处理工具") self.setGeometry(100, 100, 600, 450) # 文件路径输入框 self.file_path_label = QLabel("图片路径:", self) self.file_path_input = QLineEdit(self) self.file_path_input.setReadOnly(True) # 文件选择按钮 self.select_file_button = QPushButton("选择文件", self) self.select_file_button.clicked.connect(self.select_file) # 一把梭按钮 self.one_click_button = QPushButton("一把梭", self) self.one_click_button.clicked.connect(self.one_click_process) # 输出日志 self.log_text = QTextEdit(self) self.log_text.setReadOnly(True) # 布局 layout = QVBoxLayout() layout.addWidget(self.file_path_label) layout.addWidget(self.file_path_input) layout.addWidget(self.select_file_button) layout.addWidget(self.one_click_button) layout.addWidget(QLabel("执行日志:")) layout.addWidget(self.log_text) container = QWidget() container.setLayout(layout) self.setCentralWidget(container) # 添加工具栏 self.add_toolbars() # 设置背景图片和图标 self.set_background_and_icon() def set_background_and_icon(self): # 设置背景图片 background_path = resource_path("img/OIP-C.jpg(1)") self.setStyleSheet(f"MainWindow {{ background-image: url({background_path}); background-size: cover; }}") # 设置窗口图标 icon_path = resource_path("img/OIP-C.jpg") self.setWindowIcon(QIcon(icon_path)) def add_toolbars(self): # 添加工具栏 toolbar = QToolBar("工具栏") self.addToolBar(toolbar) # 添加动作 action1 = QAction("清屏", self) action1.triggered.connect(self.clear_log) toolbar.addAction(action1) def select_file(self): file_path, _ = QFileDialog.getOpenFileName( self, "选择图片文件", "", "图片文件 (*.png *.jpg *.jpeg *.gif *.bmp)" ) if file_path: self.file_path_input.setText(file_path) self.log(f"已选择文件: {file_path}") self.add_separator() def clear_log(self): self.log_text.clear() with open("result.txt", "w") as f: f.write("") def log(self, message): self.log_text.append(message) with open("result.txt", "a", encoding='utf-8') as f: f.write(message + "\n") def add_separator(self): separator = "-" * 50 self.log(separator) def image_to_hex(self): file_path = self.file_path_input.text() if not file_path: self.log("请先选择图片文件!") return try: with open(file_path, 'rb') as image_file: binary_data = image_file.read() hex_data = binascii.hexlify(binary_data).decode('utf-8') with open("hex.txt", 'w') as hex_file: hex_file.write(hex_data) self.log("图片已成功转换为16进制,保存到 hex.txt") self.add_separator() except Exception as e: self.log(f"转换图片为16进制时出错: {e}") self.add_separator() def process_image(self): file_path = self.file_path_input.text() if not file_path: self.log("请先选择图片文件!") return try: # 检查图片格式是否为 PNG with Image.open(file_path) as img: if img.format != 'PNG': self.log("图片不是 PNG 格式,跳过宽高爆破。") self.add_separator() return with open(file_path, 'rb') as file: bin_data = file.read() crc32key = zlib.crc32(bin_data[12:29]) original_crc32 = int(bin_data[29:33].hex(), 16) if crc32key == original_crc32: self.log("宽高没有问题!") self.add_separator() else: self.log("开始爆破宽高...") for i, j in itertools.product(range(4096), range(4096)): data = bin_data[12:16] + struct.pack('>i', i) + struct.pack('>i', j) + bin_data[24:29] crc32 = zlib.crc32(data) if crc32 == original_crc32: self.log(f"找到正确宽高: 宽度={i}, 高度={j}") self.modify_hex_file(i, j) return self.log("破解失败") self.add_separator() except Exception as e: self.log(f"处理图片时出错: {e}") self.add_separator() def modify_hex_file(self, width, height): try: with open('hex.txt', 'r') as hex_file: hex_data = hex_file.read() bin_data = binascii.unhexlify(hex_data) modified_data = bin_data[:16] + struct.pack('>I', width) + struct.pack('>I', height) + bin_data[24:] modified_hex_data = binascii.hexlify(modified_data).decode('utf-8') with open('hex.txt', 'w') as hex_file: hex_file.write(modified_hex_data) with open('modified_image.png', 'wb') as png_file: png_file.write(modified_data) self.log("修改后的16进制数据已保存到 hex.txt,修改后的图片已保存为 modified_image.png") self.add_separator() except Exception as e: self.log(f"修改 hex.txt 文件时出错: {e}") self.add_separator() def scan_hidden_files(self): input_file = 'hex.txt' if not os.path.exists(input_file): self.log(f"Error: Input file '{input_file}' not found.") self.add_separator() return try: with open(input_file, 'r', encoding='utf-8') as f: hex_content = f.read() hex_data = re.findall(r'[0-9A-Fa-f]{2}', hex_content) hex_str = ''.join(hex_data) data = binascii.unhexlify(hex_str) matches = [] for signature, file_type, ext in SIGNATURES: offset = 0 while True: offset = data.find(signature, offset) if offset == -1: break matches.append((offset, signature, file_type, ext)) offset += 1 if not matches: self.log("No files found in the hex data.") self.add_separator() return self.log(f"Found {len(matches)} potential files:") for offset, _, file_type, _ in matches: self.log(f" {file_type} at offset 0x{offset:X}") # 提取文件 output_dir = 'extracted_files' self.log("文件已经成功提取到extracted_files文件夹中") if not os.path.exists(output_dir): os.makedirs(output_dir) for idx, (offset, signature, file_type, ext) in enumerate(matches): file_data = data[offset:] file_name = f"{file_type}_{idx}.{ext}" file_path = os.path.join(output_dir, file_name) with open(file_path, 'wb') as f: f.write(file_data) self.log(f"Extracted {file_type} file: {file_name} (Offset: 0x{offset:X})") self.add_separator() except Exception as e: self.log(f"Error scanning hidden files: {e}") self.add_separator() def get_image_info(self): file_path = self.file_path_input.text() if not file_path: self.log("请先选择图片文件!") return try: with Image.open(file_path) as img: self.log("图片属性详细信息:") self.log(f"文件路径: {file_path}") self.log(f"文件格式: {img.format}") self.log(f"图片尺寸: {img.size} (宽度 x 高度)") self.log(f"图片模式: {img.mode}") exif_data = img._getexif() if exif_data: self.log("\n图片属性详细信息:") from PIL.ExifTags import TAGS for tag, value in exif_data.items(): tag_name = TAGS.get(tag, tag) self.log(f"{tag_name}: {value}") else: self.log("\n该图片没有属性详细信息。") self.add_separator() except Exception as e: self.log(f"处理图片时出错: {e}") self.add_separator() def string_search(self): input_file = 'hex.txt' if not os.path.exists(input_file): self.log(f"Error: Input file '{input_file}' not found.") self.add_separator() return try: with open(input_file, 'r', encoding='utf-8') as f: hex_content = f.read() # 将16进制字符串转换为字节流 hex_data = re.findall(r'[0-9A-Fa-f]{2}', hex_content) hex_str = ''.join(hex_data) data = binascii.unhexlify(hex_str) # 将字节流解码为字符串(忽略非ASCII字符) text = data.decode('utf-8', errors='replace') # 定义要搜索的关键词 keywords = ["ctf", "CTF", "FLAG", "flag", "{}", "ZmxhZwo", "Y3RmCg", "password", "pd", "=="] # 搜索文件中的关键词 matches = [] for keyword in keywords: index = text.find(keyword) while index != -1: # 获取匹配字符串的上下文 start = max(0, index - 32) end = min(len(text), index + len(keyword) + 32) context = text[start:end] matches.append((keyword, context)) index = text.find(keyword, index + 1) if not matches: self.log("未找到关键词。") else: self.log(f"找到 {len(matches)} 个关键词:") for keyword, context in matches: self.log(f" 关键词: {keyword}") self.log(f" 上下文: {context}\n") self.add_separator() except Exception as e: self.log(f"字符串搜索时出错: {e}") self.add_separator() def lsb_decrypt(self): file_path = self.file_path_input.text() if not file_path: self.log("请先选择图片文件!") return try: # 打开图片 with Image.open(file_path) as img: if img.mode not in ['RGB', 'RGBA']: self.log("图片模式不支持 LSB 隐写解密,请使用 RGB 或 RGBA 模式的图片。") self.add_separator() return # 将图片转换为 RGB 模式 img = img.convert('RGB') pixels = list(img.getdata()) # 提取 LSB binary_data = [] for pixel in pixels: for channel in pixel: # 提取最低有效位 binary_data.append(channel & 1) # 将二进制数据转换为字符串 binary_str = ''.join(map(str, binary_data)) # 将二进制数据转换为16进制 hex_data = [] for i in range(0, len(binary_str), 8): byte = binary_str[i:i + 8] if len(byte) < 8: break hex_byte = hex(int(byte, 2))[2:].zfill(2) hex_data.append(hex_byte) # 将16进制数据转换为字符串 hex_str = ''.join(hex_data) # 将16进制数据保存到 lsb_hex.txt with open("lsb_hex.txt", "w") as f: f.write(hex_str) # 将16进制转化为ASCII码 try: asc_str = bytes.fromhex(hex_str).decode('utf-8', errors='ignore') except ValueError: # 如果转换失败,可能是因为16进制字符串长度不是偶数 # 可以尝试修复 hex_str = hex_str[:len(hex_str) // 2 * 2] # 截取偶数长度 asc_str = bytes.fromhex(hex_str).decode('utf-8', errors='ignore') # 在日志中显示前30位数据 self.log("LSB 隐写解密结果:") self.log(f"前30位ascII数据: {asc_str[:40]}") self.log(f"16进制数据已保存到 lsb_hex.txt") self.add_separator() except Exception as e: self.log(f"LSB 隐写解密时出错: {e}") self.add_separator() def scan_lsb_hex_files(self): input_file = 'lsb_hex.txt' if not os.path.exists(input_file): self.log(f"Error: Input file '{input_file}' not found.") self.add_separator() return try: with open(input_file, 'r', encoding='utf-8') as f: hex_content = f.read() # 将16进制字符串转换为字节流 hex_data = re.findall(r'[0-9A-Fa-f]{2}', hex_content) hex_str = ''.join(hex_data) data = binascii.unhexlify(hex_str) matches = [] for signature, file_type, ext in SIGNATURES: offset = 0 while True: offset = data.find(signature, offset) if offset == -1: break matches.append((offset, signature, file_type, ext)) offset += 1 if not matches: self.log("No files found in the LSB hex data.") self.add_separator() return self.log(f"Found {len(matches)} potential files in LSB hex data:") for offset, _, file_type, _ in matches: self.log(f" {file_type} at offset 0x{offset:X}") # 提取文件 output_dir = 'lsb_extracted_files' if not os.path.exists(output_dir): os.makedirs(output_dir) for idx, (offset, signature, file_type, ext) in enumerate(matches): file_data = data[offset:] file_name = f"LSB_{file_type}_{idx}.{ext}" file_path = os.path.join(output_dir, file_name) with open(file_path, 'wb') as f: f.write(file_data) self.log(f"Extracted {file_type} file from LSB hex data: {file_name} (Offset: 0x{offset:X})") self.add_separator() except Exception as e: self.log(f"Error scanning LSB hex data for hidden files: {e}") self.add_separator() def extract_channels(self): file_path = self.file_path_input.text() if not file_path: self.log("请先选择图片文件!") return try: with Image.open(file_path) as img: if img.mode not in ['RGB', 'RGBA']: self.log("图片模式不支持通道提取,请使用 RGB 或 RGBA 模式的图片。") self.add_separator() return # 分离通道 if img.mode == 'RGB': r, g, b = img.split() channels = {'R': r, 'G': g, 'B': b} else: # RGBA r, g, b, a = img.split() channels = {'R': r, 'G': g, 'B': b, 'A': a} # 保存原始通道 output_dir = 'extracted_channels' if not os.path.exists(output_dir): os.makedirs(output_dir) for channel_name, channel_img in channels.items(): channel_path = os.path.join(output_dir, f"{channel_name}_channel.png") channel_img.save(channel_path) self.log(f"通道 {channel_name} 已保存为 {channel_path}") # 提取位平面 for channel_name, channel_img in channels.items(): # 创建位平面文件夹 bit_plane_dir = os.path.join(output_dir, f"{channel_name}_bit_planes") if not os.path.exists(bit_plane_dir): os.makedirs(bit_plane_dir) # 提取每个位平面(0到7) for bit in range(8): # 创建一个新的图像来存储当前位平面 bit_plane_img = Image.new('L', channel_img.size) pixels = bit_plane_img.load() # 提取当前位平面 for y in range(channel_img.size[1]): for x in range(channel_img.size[0]): pixel = channel_img.getpixel((x, y)) # 提取第 bit 位,并将其放大为 0 或 255 以提高可见性 pixels[x, y] = (pixel >> bit) & 1 # 将位平面转换为黑白图像(0 或 255) pixels[x, y] = pixels[x, y] * 255 # 保存位平面 bit_plane_path = os.path.join(bit_plane_dir, f"{channel_name}_bit_plane_{bit}.png") bit_plane_img.save(bit_plane_path) self.log(f"成功保存在extracted_channels") self.add_separator() except Exception as e: self.log(f"提取通道或位平面时出错: {e}") self.add_separator() def one_click_process(self): self.log("开始执行'一把梭'流程...") self.add_separator() self.image_to_hex() self.process_image() self.scan_hidden_files() self.get_image_info() self.string_search() self.lsb_decrypt() self.scan_lsb_hex_files() self.extract_channels() self.log("流程执行完成!") self.add_separator() if __name__ == "__main__": app = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec())
2301_80905479/123
run_GUL.py
Python
unknown
20,600
<script> export default { onLaunch: function() { console.log('App Launch') }, onShow: function() { console.log('App Show') }, onHide: function() { console.log('App Hide') }, onError() { console.log(); } } </script> <style> /*每个页面公共css */ @import 'lib/smart.css'; </style>
2301_80750063/SmartUI_lwh050
App.vue
Vue
unknown
317
<template> <view class="cardstyle" :style="{'background-color': bgColor}"> <slot name="header"></slot> <!-- 标题区域 --> <view class="titlebox"> <!-- 模式2和3显示图片 --> <view class="imgbox" v-if="mode === 2 || mode === 3"> <image :src="showImage" @error="handleImageException" mode="aspectFill"></image> </view> <view class="content-area"> <!-- 模式3显示灰色标题 --> <text v-if="mode === 3" class="ad-title">{{ title }}</text> <!-- 其他模式正常显示 --> <text v-else class="normal-title">{{ title }}</text> <!-- 模式3显示多图广告区域 --> <view class="adbox" v-if="mode === 3"> <view class="ad-images"> <image v-for="(img, index) in images" :key="index" :src="img" @error="handleAdImageError(index)" mode="aspectFill" class="ad-image" ></image> </view> <text class="ad-source">{{ author }}</text> </view> </view> </view> <!-- 底部信息区域 --> <view class="tips-box" v-if="mode !== 3"> <text class="top-tag" v-if="isTop">置顶</text> <text class="author" :style="authorColor">{{ author }}</text> <text class="comments">{{ comments }}评</text> <view class="time-wrapper"> <text class="time">{{ timedata }}</text> </view> </view> <!-- 广告模式的底部信息 --> <view class="ad-tips-box" v-if="mode === 3"> <text class="ad-author">{{ author }}</text> <text class="ad-comments">{{ comments }}评</text> </view> <slot name="tips" v-if="showSearch"></slot> <slot name="footer"></slot> </view> </template> <script> export default { name: "CardViewText", data() { return { defaultPic: "/static/logo.png", failPic: "/static/logo.png", imageError: false, adImageErrors: {} }; }, computed: { showImage() { if (!this.images || this.images.length === 0) { console.log("showImage Default-->" + this.title); return this.defaultPic; } if (this.imageError) { console.log("showImage Error-->" + this.title); return this.failPic; } return this.images[0]; }, authorColor() { return this.isTop ? 'color: #f00;' : 'color: #666;'; }, bgColor() { // 根据模式设置不同背景色 switch(this.mode) { case 1: return '#ffffff'; // 置顶新闻 case 2: return '#f8f9fa'; // 普通新闻 case 3: return '#f0f2f5'; // 广告 default: return '#ffffff'; } } }, methods: { handleImageException() { console.log("handleImageException: " + this.title); this.imageError = true; }, handleAdImageError(index) { console.log("广告图片加载失败: " + index); this.$set(this.adImageErrors, index, true); // 替换为默认图片 if (this.images && this.images[index]) { this.$set(this.images, index, this.failPic); } } }, props: { title: { type: String, default: "新闻标题", required: true }, isTop: { type: Boolean, default: false }, author: { type: String, default: "来源" }, comments: { type: String, default: "0" }, timedata: { type: String, default: "2000.01.01" }, mode: { type: Number, default: 1, require: true }, images: { type: Array, default: () => [] }, showSearch: { type: Boolean, default: false } } }; </script> <style scoped> .cardstyle { background-color: #fff; padding: 24rpx; border-radius: 16rpx; box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08); margin-bottom: 20rpx; } .titlebox { display: flex; flex-direction: row; align-items: flex-start; } .imgbox { margin-right: 20rpx; flex-shrink: 0; } .imgbox image { width: 120rpx; height: 90rpx; border-radius: 8rpx; } .content-area { flex: 1; } .normal-title { font-size: 32rpx; font-weight: 500; color: #333; line-height: 1.4; } .ad-title { font-size: 28rpx; color: #aaa; line-height: 1.4; } .adbox { margin-top: 16rpx; } .ad-images { display: flex; gap: 10rpx; margin-bottom: 12rpx; } .ad-image { width: 80rpx; height: 60rpx; border-radius: 6rpx; } .ad-source { font-size: 24rpx; color: #999; } .tips-box { display: flex; align-items: center; margin-top: 20rpx; font-size: 24rpx; color: #666; } .ad-tips-box { display: flex; align-items: center; margin-top: 16rpx; font-size: 22rpx; color: #999; gap: 20rpx; } .top-tag { color: #f00; font-weight: bold; margin-right: 20rpx; padding: 4rpx 12rpx; background: #ffeaea; border-radius: 6rpx; font-size: 20rpx; } .author { margin-right: 20rpx; } .comments { margin-right: auto; } .time-wrapper { display: flex; justify-content: flex-end; } .time { color: #999; } </style>
2301_80750063/SmartUI_lwh050
components/CardViewText.vue
Vue
unknown
4,863
<template> <view class="content"> <text style="font-size: 50rpx ;">子组件A</text> <view> <text>父组件传进来的值:</text> <text style="font-weight: bold;color:red">{{intent}}</text> </view> <button type="primary" @click="sendData()">传值给B组件</button> </view> </template> <script> export default { name:"comA", props:['intent'], data() { return { }; }, mounted() { console.log("comA---mouted"); }, methods:{ sendData(){ console.log("comA---sendData"); uni.$emit('sendIntent',this.intent) } } } </script> <style> </style>
2301_80750063/SmartUI_lwh050
components/comA.vue
Vue
unknown
603
<template> <view class="content"> <view class="title"> 子组件B </view> <view> ComA组件传进来的值: <text class="intent-text-box">{{result}}</text> </view> <view style="margin: 10rpx"> <text>回传值:</text> <input type="text" :value="callBackValue" style="color: yellow;" /> <button @click="sendOutside()" size="mini">回传</button> </view> </view> </template> <script> export default { name:"comB", data() { return { }; }, methods: { sendOutside() { console.warn("----ComB----sendOutside------>"+this.callBackValue); this.$emit('callBackFunction',this.callBackValue); } } } </script> <style> </style>
2301_80750063/SmartUI_lwh050
components/comB.vue
Vue
unknown
688
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8" /> <script> var coverSupport = 'CSS' in window && typeof CSS.supports === 'function' && (CSS.supports('top: env(a)') || CSS.supports('top: constant(a)')) document.write( '<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' + (coverSupport ? ', viewport-fit=cover' : '') + '" />') </script> <title></title> <!--preload-links--> <!--app-context--> </head> <body> <div id="app"><!--app-html--></div> <script type="module" src="/main.js"></script> </body> </html>
2301_80750063/SmartUI_lwh050
index.html
HTML
unknown
675
.smart-container{ padding: 15rpx; background-color: #CEFFCE; } .smart-panel{ margin-bottom: 12px; } .smart-panel-title{ background-color: #f1f1f1; font-size: 18px; font-weight: normal; padding: 5px; flex-direction: row; } .smart-panel-h{ background-color: #ffffff; flex-direction: row; align-items: center; padding: 5px; margin-bottom: 2px; } .smart-panel-head{ padding: 35prx; text-align: center; } .smart-panel-head-title{ font-size: 50rpx; height: 88rpx; line-height: 80rpx; color: #aaff00; border-bottom: 2rpx solid #d8d8d8; padding: 0 40rpx; box-sizing: border-box; display: inline-block; } .smart-flex{ display: flex; } .smart-row{ flex-direction: row; } .smart-padding-wrap{ padding: 0 30rpx; } .flex-item{ width: 33.3%; height: 200rpx; line-height: 200rpx; text-align: center; } .smart-bg-red{ background-color: #f76260; color: #FFFFFF; } .smart-bg-green{ background-color: #09bb07; color: #FFFFFF; } .smart-bg-blue{ background-color: #007aff; color: #FFFFFF; } .smart-column{ flex-direction: column; } .flex-item-c{ width: 100%; height: 100rpx; line-height: 100rpx; text-align: center; } .text{ margin: 15rpx 10rpx; padding: 0 20rpx; background-color: #ebebeb; height: 70rpx; line-height: 70rpx; color: #777; font-size: 26rpx; } /* scroll-view */ .scroll-view-tiem{ width: 100%; height: 300rpx; /* 每个item的高度 */ line-height: 300rpx; color: #FFFFFF; } .scroll-y{ height: 300rpx; /* scrollview的显示高度 */ } .scroll-x{ white-space: nowrap; /* 强制在同一行显示所有文本 */ width: 100%; } .scroll-view-tiem-h{ display: inline-block; height: 300rpx; width: 100%; line-height: 300rpx; text-align: center; } /*swiper*/ .swiper-item { display: block; height: 300rpx; line-height: 300rpx; text-align: center; } .smart-bg-0{ background-color: #f76260; } .smart-bg-1{ background-color: #D8D8D8; } .smart-bg-2{ background-color: #AA99FF; } .smart-bg-3{ background-color: #007AFF; } /* textview */ .text-box{ margin-bottom: 40rpx; padding: 40rpx 0; display: flex; min-height: 300rpx; background-color: #d8d8d8; justify-content: center; /* 元素在主轴(横轴)方向上的对齐方式 */ text-align: center; font-size: 30rpx; color: #353535; line-height: 1.8; } .text-space{ background-color: #AA99FF; } /*input输入框*/ .smart-input { height: 28px; line-height: 28px; font-size: 15px; flex: 1; background-color: #D8D8D8; padding: 3px; } /* 页面头部样式 */ .smart-page-head { padding: 10px; background-color: #f5f5f5; border-bottom: 1px solid #eee; } .smart-page-head-title { font-size: 16px; font-weight: bold; }
2301_80750063/SmartUI_lwh050
lib/smart.css
CSS
unknown
2,659
import App from './App' // #ifndef VUE3 import Vue from 'vue' import './uni.promisify.adaptor' Vue.config.productionTip = false App.mpType = 'app' const app = new Vue({ ...App }) app.$mount() // #endif // #ifdef VUE3 import { createSSRApp } from 'vue' export function createApp() { const app = createSSRApp(App) return { app } } // #endif
2301_80750063/SmartUI_lwh050
main.js
JavaScript
unknown
352
<template> <view> <view> <image :src="iconFilePath" mode="aspectFit"></image> </view> <button @click="downloadImage" :disabled="downloading"> {{ downloading ? '下载中...' : '下载图片' }} </button> <button @click="previewImage" :disabled="!iconFilePath"> 预览图片 </button> </view> </template> <script> export default { data() { return { imageURL: "https://cdn.pixabay.com/photo/2025/11/05/20/57/monastery-9939590_1280.jpg", iconFilePath: "", downloading: false } }, methods: { downloadImage() { this.downloading = true; const imagetask = uni.downloadFile({ url: this.imageURL, success: (res) => { if (res.statusCode === 200) { console.log('下载成功'); this.iconFilePath = res.tempFilePath; } }, fail: (err) => { console.error('下载失败:', err); } }); imagetask.onProgressUpdate((res) => { console.log('下载进度:', res.progress + "%"); console.log('已下载:', res.totalBytesWritten); console.log('总大小:', res.totalBytesExpectedToWrite); }); }, previewImage() { if (this.iconFilePath) { uni.previewImage({ urls: [this.iconFilePath] }); } } } } </script>
2301_80750063/SmartUI_lwh050
pages/APIpages/DownloadImages/DownloadImages.vue
Vue
unknown
1,278
<template> <view style="padding-top:100rpx;"> <view class="text-area"> <text>输入值:</text> <input type="text" v-model="title" style="color: red;" /> </view> <view class="text-area"> <text>回传值:</text> <input type="text" :value="callBackValue" style="color: yellow;" /> </view> <comA :itent="title"></comA> <comB @callBackFunction="callBack"></comB> </view> </template> <script> //引用 import comA from '../../../components/comA.vue'; import comB from '../../../components/comB.vue'; export default { //声明 components:{ comA, comB }, data() { return { title:"", }; }, created(){ console.log("comB created"); uni.$on('sendIntent',(msg)=>{ console.log("sendIntent---comB get Intent " + msg); }) }, methods: { callBack(msg){ console.warn("----index----callBack-->" + msg); this.callBackValue = msg; } } } </script> <style> </style>
2301_80750063/SmartUI_lwh050
pages/APIpages/IntentPage/IntentPage.vue
Vue
unknown
940
<template> <view> <button @click="onLog()">concle.log</button> </view> </template> <script> export default { data() { return { title:'打印日志' } }, methods: { onLog(){ console.log('-----this.title: ',this.title); } } } </script> <style> </style>
2301_80750063/SmartUI_lwh050
pages/APIpages/LogPage/LogPage.vue
Vue
unknown
293
<template> <view> <!-- 天气信息显示区域 --> <view v-if="weatherData"> <!-- 城市信息 --> <view> <text>城市: {{ weatherData.cityInfo.city }}</text> </view> <!-- 明天天气预报 --> <view> <text>明天天气预报</text> <view> <text>日期: {{ tomorrowData.ymd }}</text> <text>星期: {{ tomorrowData.week }}</text> <text>最高温: {{ tomorrowData.high }}</text> <text>最低温: {{ tomorrowData.low }}</text> </view> </view> </view> <!-- 加载状态 --> <view v-if="loading"> <text>正在获取天气数据...</text> </view> <!-- 错误提示 --> <view v-if="error"> <text>{{ error }}</text> </view> <!-- 获取天气按钮 --> <button @click="getWeather">获取天气预报</button> </view> </template> <script> export default { data() { return { weatherData: null, tomorrowData: {}, loading: false, error: '' } }, methods: { getWeather() { this.loading = true; this.error = ''; uni.request({ url: 'http://t.weather.sojson.com/api/weather/city/101230501', success: (res) => { console.log("success-----" + JSON.stringify(res)); this.weatherData = res.data; // 获取明天的天气预报数据(数组第二个元素) if (this.weatherData.data.forecast && this.weatherData.data.forecast.length > 1) { this.tomorrowData = this.weatherData.data.forecast[1]; } }, fail: (eMsg) => { console.log("request fail-----" + eMsg); this.error = "获取天气数据失败"; }, complete: () => { this.loading = false; } }); } } } </script> <style> </style>
2301_80750063/SmartUI_lwh050
pages/APIpages/Tianqiyubao/Tianqiyubao.vue
Vue
unknown
1,718
<template> <view> <button @click="onSetTimeCall">单次定时器setTimeout</button> <button @click="onSetTimeCallxy(name,password)">带参数setTimeout</button> <button @click="onTimeoutClear(name,password)">取消</button> </view> </template> <script> export default { data() { return { name:"lwh", password:'666', } }, methods: { onSetTimeCall(){ console.log("onSetTimeCall-->"); // setTimeout setTimeout(()=>{ //延时之后要执行的代码 console.log("我延时3秒才会打印"); },3000) }, onSetTimeCallxy(name,pwd){ console.log("onSetTimeCallxy--> name:"+name+",pwd:"+pwd); setTimeout((x,y)=>{ console.log("我可以传参数了> x:"+x+",y:"+y); },2000, name, pwd) }, onTimeoutClear(){ console.log(); clearTimeout(this.timeoutID); } } } </script> <style> </style>
2301_80750063/SmartUI_lwh050
pages/APIpages/TimerPage/TimerPage.vue
Vue
unknown
883
<template> <view style="text-align: center;"> <view style="margin-top: 100px;"> <image :src="iconFilePath" @click="updateImage()" mode="aspectFill"></image> </view> </view> </template> <script> export default { data() { return { iconFilePath: "/static/logo.png" } }, methods: { updateImage() { uni.chooseImage({ count: 1, sourceType: ['album'], success: (res) => { console.log("updateImage -->" + res.tempFilePaths[0]); this.iconFilePath = res.tempFilePaths[0]; this.previewImage([res.tempFilePaths[0]]); } }); }, previewImage(images) { uni.previewImage({ urls: images }) } } } </script>
2301_80750063/SmartUI_lwh050
pages/APIpages/imageyulan/imageyulan.vue
Vue
unknown
689
<template> <view> <button>setStorage</button> </view> </template> <script> export default { data() { return { } }, methods: { onFunCall(){ name = uni.getStorageSync("userName"); pwd="ssss"; } } } </script> <style> </style>
2301_80750063/SmartUI_lwh050
pages/StoragePage/StoragePage.vue
Vue
unknown
265
<template> <view> <page-head title="button,按钮"></page-head> <view class="smart-padding-wrap"> <!-- 主操作按钮 --> <button type="primary">页面主操作 normal</button> <button type="primary" :loading="true">页面主操作 loading</button> <button type="primary" disabled="false">页面主操作 disabled</button> <!-- 次操作按钮 --> <button type="default">页面次操作 normal</button> <button type="default" disabled="false">页面次操作 disabled</button> <!-- 警告操作按钮 --> <button type="warn">页面警告操作 warn</button> <button type="warn" disabled="false">页面警告操作 warn disabled</button> <!-- 镂空按钮 --> <button type="primary" plain="true">镂空按钮 plain</button> <button type="primary" plain="true" disabled="false">镂空按钮 plain disabled</button> <!-- 迷你按钮 --> <button type="primary" size="mini" class="mini-btn">按钮</button> <button type="default" size="mini" class="mini-btn">按钮</button> <button type="warn" size="mini" class="mini-btn">按钮</button> </view> </view> </template> <script> export default { data() { return { // 可以在这里添加按钮相关的数据 }; }, methods: { // 可以在这里添加按钮点击等方法 } }; </script> <style> button { margin-top: 30rpx; margin-bottom: 30rpx; } .mini-btn { margin-right: 30rpx; } </style>
2301_80750063/SmartUI_lwh050
pages/components/button/button.vue
Vue
unknown
1,517
<template> <view> <view class="smart-page-head"> <view class="smart-page-head-title">checkbox,多选按钮</view> </view> <view class="smart-padding-wrap"> <view class="item"> <checkbox checked="true"></checkbox> 选中 <checkbox></checkbox> 未选中 </view> <view class="item"> <checkbox checked="true" color="#F0AD4E" style="transform: scale(0.7);"></checkbox> 选中 <checkbox color="#F0AD4E" style="transform: scale(0.7);"></checkbox> 未选中 </view> <view class="item"> 推荐展示样式: <checkbox-group> <label class="list"> <view> <checkbox></checkbox> 中国 </view> </label> <label class="list"> <view> <checkbox></checkbox> 美国 </view> </label> <label class="list"> <view> <checkbox></checkbox> 日本 </view> </label> </checkbox-group> </view> </view> </view> </template> <script> export default { data() { return {}; }, methods: {} }; </script> <style> .item { margin-bottom: 30rpx; } .list { justify-content: flex-start; padding: 22rpx 30rpx; } .list view { padding-bottom: 20rpx; border-bottom: 1px solid #d8d8d8; } </style>
2301_80750063/SmartUI_lwh050
pages/components/checkbox/checkbox.vue
Vue
unknown
1,436
<template> <view> <view class="smart-page-head"> <view class="smart-page-head-title">input,输入框</view> </view> <view class="smart-padding-wrap"> <view class="item">可自动获取焦点的</view> <view><input class="smart-input" focus="true" placeholder="自动获取焦点" /></view> <view>右下角显示搜索</view> <view><input class="smart-input" confirm-type="search" placeholder="右下角显示搜索" /></view> <view>控制最大输入长度</view> <view><input class="smart-input" maxlength="10" placeholder="控制最大输入长度为10" /></view> <view> 同步获取输入值 <text style="color: #007AFF;">{{ inputValue }}</text> </view> <view><input class="smart-input" @input="onKeyInput" placeholder="同步获取输入值" /></view> <view>数字输入</view> <view><input class="smart-input" type="number" placeholder="这是一个数字输入框" /></view> <view>密码输入</view> <view><input class="smart-input" type="text" password="true" placeholder="这是一个密码输入框" /></view> <view>带小数点输入输入</view> <view><input class="smart-input" type="digit" placeholder="这是一个带小数点输入框" /></view> <view>身份证输入</view> <view><input class="smart-input" type="idcard" placeholder="这是一个身份证输入框" /></view> <view>带清除按钮</view> <view class="wrapper"> <input class="smart-input" :value="clearinputValue" @input="clearInput" placeholder="这是一个带清除按钮输入框" /> <text v-if="showClearIcon" @click="clearIcon" class="uni-icon">&#xe434;</text> </view> <view>可查看密码的输入框</view> <view class="wrapper"> <input class="smart-input" placeholder="请输入密码" :password="showPassword" /> <text class="uni-icon" :class="!showPassword ? 'eye-active' : ''" @click="changePassword">&#xe568;</text> </view> </view> </view> </template> <script> export default { data() { return { inputValue: '', showPassword: true, clearinputValue: '', showClearIcon: false }; }, methods: { onKeyInput: function (event) { this.inputValue = event.detail.value; }, clearInput: function (event) { this.clearinputValue = event.detail.value; if (event.detail.value.length > 0) this.showClearIcon = true; else this.showClearIcon = false; }, clearIcon: function (event) { this.clearinputValue = ''; this.showClearIcon = false; }, changePassword: function () { this.showPassword = !this.showPassword; } } }; </script> <style> .item { margin-bottom: 40rpx; } .uni-icon { font-family: unicons; font-size: 24px; font-weight: normal; font-style: normal; width: 24px; height: 24px; line-height: 24px; color: #999999; margin-top: 5px; } .wrapper { display: flex; flex-direction: row; flex-wrap: nowrap; background-color: #d8d8d8; } .eye-active { color: #007aff; } </style>
2301_80750063/SmartUI_lwh050
pages/components/input/input.vue
Vue
unknown
3,115
<template> <view> <page-head :title='title'></page-head> </view> </template> <script> export default { data() { return { } }, methods: { } } </script> <style> </style>
2301_80750063/SmartUI_lwh050
pages/components/navigator/navigate/navigate.vue
Vue
unknown
200
<template> <view> <view class="smart-panel-head"> <view class="smart-panel-head-title">navigator,链接</view> </view> <view class="smart-padding-wrap"> <navigator url="/pages/newpage/newpage" hover-class="navigator-hover"> <button type="default">跳转到新页面</button> </navigator> <navigator url="newpage/newpage?title=redirect" open-type="redirect" hover-class="other-navigator-hover"> <button type="default">在当前页打开</button> </navigator> <navigator url="newpage/newpage?title=redirect" open-type="redirect" hover-class="other-navigator-hover"> <button type="default">新建跳转栈</button> </navigator> <navigator url="/pages/tabBar/tabcompage/tabcompage" open-type="switchTab"> <button type="default">跳转tab页面</button> </navigator> </view> </view> </template> <script> export default { data() { return { title: 'navigator' } }, methods: { } } </script> <style> </style>
2301_80750063/SmartUI_lwh050
pages/components/navigator/navigator.vue
Vue
unknown
1,020
<template> <view> </view> </template> <script> export default { data() { return { } }, methods: { } } </script> <style> </style>
2301_80750063/SmartUI_lwh050
pages/components/navigator/redirect/redirect.vue
Vue
unknown
162
<template> <view> <!--顶部区域--> <view class="smart-page-head"> <view class="smart-panel-head-title">scroll-view视图</view> </view> <view class="smart-padding-wrap"> <view class="smart-text">可视滚动视图区域.</view> <view> vertical scroll 纵向滚动</view> <view> <scroll-view class="scroll-y" scroll-y="true"> <view class="scroll-view-tiem smart-bg-red">A</view> <view class="scroll-view-tiem smart-bg-blue">B</view> <view class="scroll-view-tiem smart-bg-green">C</view> </scroll-view> </view> <view> horizontal scroll 横向滚动</view> <view> <scroll-view class="scroll-x" scroll-x="true" scroll-left="120"> <view class="scroll-view-tiem-h smart-bg-red">A</view> <view class="scroll-view-tiem-h smart-bg-blue">B</view> <view class="scroll-view-tiem-h smart-bg-green">C</view> </scroll-view> </view> </view> </view> </template> <script> export default { data() { return { } }, methods: { } } </script> <style> </style>
2301_80750063/SmartUI_lwh050
pages/components/scroll-view/scroll-view.vue
Vue
unknown
1,051
<template> <view> <!--顶部区域--> <view class="smart-page-head"> <view class="smart-panel-head-title">swiper 滑块视图</view> </view> <view class="smart-padding-wrap"> <swiper circular :indicator-dots="indicatorDots" :autoplay="autoplay" :interval="interval" :duration="duration"> <swiper-item><view class="swiper-item smart-bg-blue">A</view></swiper-item> <swiper-item><view class="swiper-item smart-bg-green">B</view></swiper-item> <swiper-item><view class="swiper-item smart-bg-red">C</view></swiper-item> </swiper> </view> </view> </template> <script> export default { data() { return { indicatorDots :true, autoplay: true, interval: 5000, duration: 500 } }, methods: { } } </script> <style> </style>
2301_80750063/SmartUI_lwh050
pages/components/swiper/swiper.vue
Vue
unknown
778
<template> <view> <view class="smart-panel-head"> <view class="smart-panel-head-title">text文本文件</view> </view> <view class="smart-padding-wrap"> <view class="text-box" scroll-y="true"> <text>{{ texts }}</text> </view> <button type="primary">add line</button> <button type="warn">remove line</button> </view> </view> </template> <script> export default { data() { return { texts: [ 'HBuilder,400万开发者选择的IDE', 'HBuilderX,轻巧、极速,极客编辑器', 'uni-app,终极跨平台方案', 'HBuilder,400万开发者选择的IDE', 'HBuilder,轻巧、极速,极客编辑器', 'uni-app,终极跨平台方案!', 'HBuilder,400万开发者选择的IDE', 'HBuilder,轻巧、极速,极客编辑器', 'uni-app,终极跨平台方案', ], text:'', canAdd:true, canRemove:false, extraLine:[] }; }, methods: { add: function(e){ this.extraLine.push(this.texts[this.extraline.length % 12]); this.text = this.extraLine.join('\n'); this.canAdd =this.extraLine.length < 12; this.canRemove =this.extraLine.length > 0; }, remove:function(e) { if (this.extraLine.length > 0) { this.extraLine.pop(); this.text = this.extraLine.join('\n'); this.canAdd =this.extraLine.length < 12; this.canRemove =this.extraLine.length > 0; } } } }; </script> <style> </style>
2301_80750063/SmartUI_lwh050
pages/components/text/text.vue
Vue
unknown
1,435
<template> <view> <!--顶部区域--> <view class="smart-panel-head"> <view class="smart-panel-head-title">View视图</view> </view> <!--主体部分--> <view class="smart-padding-wrap"> <view>flex-direction:row 横向布局</view> </view> <view class="smart-flex smart-row"> <view class="flex-item smart-bg-blue">A</view> <view class="flex-item smart-bg-green">B</view> <view class="flex-item smart-bg-red">C</view> </view> <view class="smart-padding-wrap"> <view>flex-direction:column 纵向布局</view> </view> <view class="smart-flex smart-column"> <view class="flex-item-c smart-bg-blue">A</view> <view class="flex-item-c smart-bg-green">B</view> <view class="flex-item-c smart-bg-red">C</view> </view> <view>其他布局</view> <view> <view class="text">纵向布局-自动宽度</view> <view class="text" style="width: 300rpx;">纵向布局-固定宽度</view> <view class="smart-flex smart-row"> <view class="text">横向布局-自动宽度</view> <view class="text">横向布局-自动宽度</view> </view> <view class="smart-flex smart-row" style="justify-content: center;"> <view class="text">横向布局-居中</view> <view class="text">横向布局-居中</view> </view> <view class="smart-flex smart-row" style="justify-content: flex-end;"> <view class="text">横向布局-居右</view> <view class="text">横向布局-居右</view> </view> <view class="smart-flex smart-row"> <view class="text" style="-webkit-flex:1;flex:1;">横向布局-平均分布</view> <view class="text" style="-webkit-flex:1;flex:1;">横向布局-平均分布</view> </view> <view class="smart-flex smart-row" style="justify-content: justify-content:space-between;-webkit-justify-content:space-between;"> <view class="text">横向布局-两端对齐</view> <view class="text">横向布局-两端对齐</view> </view> <view class="smart-flex smart-row"> <view class="text" style="width: 150rpx;">固定宽度</view> <view class="text" style="width: -webkit-flex:1;flex:1;">自动占满</view> </view> <view class="smart-flex smart-row"> <view class="text" style="width: 150rpx;">固定宽度</view> <view class="text" style="width: -webkit-flex:1;flex:1;">自动占满</view> <view class="text" style="width: 150rpx;">固定宽度</view> </view> <view class="smart-flex smart-row" style="flex-wrap: wrap;-webkit-flex:wrap;"> <view class="text" style="width: 280rpx;">一行显示不全wrap折行</view> <view class="text" style="width: 280rpx;">一行显示不全wrap折行</view> <view class="text" style="width: 280rpx;">一行显示不全wrap折行</view> </view> <view class="smart-flex smart-row"> <view class="text" style="flex:2">权重2</view> <view class="text" style="flex:1">权重1</view> </view> </view> </view> </template> <script> export default { data() { return { } }, methods: { } } </script> <style> </style>
2301_80750063/SmartUI_lwh050
pages/components/view/view.vue
Vue
unknown
3,050
<template> <view class="content"> <image class="logo" src="/static/logo.png"></image> <view class="text-area"> <text class="title">{{title}}</text> </view> </view> </template> <script> export default { data() { return { title: 'Hello' } }, onLoad() { }, methods: { } } </script> <style> .content { display: flex; flex-direction: column; align-items: center; justify-content: center; } .logo { height: 200rpx; width: 200rpx; margin-top: 200rpx; margin-left: auto; margin-right: auto; margin-bottom: 50rpx; } .text-area { display: flex; justify-content: center; } .title { font-size: 36rpx; color: #8f8f94; } </style>
2301_80750063/SmartUI_lwh050
pages/index/index.vue
Vue
unknown
696
<template> <view class="login-container"> <view class="login-box"> <text class="login-title">登录</text> <view class="input-item"> <input class="input-field" type="text" placeholder="请输入用户名" v-model="username" /> </view> <view class="input-item"> <input class="input-field" type="password" placeholder="请输入密码" v-model="password" /> </view> <navigator url="/pages/tabBar/CardViewPage/CardViewPage" open-type="switchTab"> <button class="login-button" @click="login">登录</button></navigator> <view class="register-link"> <text>没有账号?</text> <text class="register-text" @click="goDetailPage('regist')">去注册</text> </view> </view> </view> </template> <script> export default { data() { return { }; }, onload(){ console.log("tabcomPage--->onLoad"); }, methods: { login() { if (!this.username) { uni.showToast({ title: '请输入用户名', icon: 'none' }); return; } if (!this.password) { uni.showToast({ title: '请输入密码', icon: 'none' }); return; } uni.showToast({ title: '登录成功', icon: 'success', duration:1500, }); }, goDetailPage(e) { if (typeof e === 'string') { uni.navigateTo({ url: '/pages/' + e + '/' + e }); } else { uni.navigateTo({ url: e.url }); } }, } }; </script> <style> .login-container { display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #fff; } .login-box { width: 80%; padding: 20px; background-color: #f5f5f5; border-radius: 10px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); } .login-title { display: block; text-align: center; font-size: 20px; margin-bottom: 20px; } .input-item { margin-bottom: 15px; } .input-field { width: 100%; height: 40px; padding: 0 10px; border: 1px solid #ccc; border-radius: 5px; box-sizing: border-box; } .login-button { height: 40px; background-color: #007AFF; color: white; border: none; border-radius: 5px; margin-top: 10px; } .register-link { text-align: center; margin-top: 10px; } .register-text { color: #007AFF; } </style>
2301_80750063/SmartUI_lwh050
pages/login/login.vue
Vue
unknown
2,419
<template> <view class="register-container"> <view class="register-box"> <text class="register-title">注册</text> <view class="input-item"> <input type="text" placeholder="请输入用户名" v-model="username" /> </view> <view class="input-item"> <input type="password" placeholder="请输入密码" v-model="password" /> </view> <view class="input-item"> <input type="password" placeholder="请确认密码" v-model="confirmPassword" /> </view> <button class="register-button" @click="register">注册</button> <view class="login-link"> <text>已有账号?</text> <text class="login-text" @click="goDetailPage('login')">去登录</text> </view> </view> </view> </template> <script> export default { data() { return { username: '', password: '', confirmPassword: '' }; }, methods: { register() { if (!this.username) { uni.showToast({ title: '请输入用户名', icon: 'none' }); return; } if (!this.password) { uni.showToast({ title: '请输入密码', icon: 'none' }); return; } if (this.password !== this.confirmPassword) { uni.showToast({ title: '两次输入的密码不一致', icon: 'none' }); return; } console.log('用户名:', this.username); console.log('密码:', this.password); uni.showToast({ title: '注册功能待实现,已打印输入信息', icon: 'none' }); }, goDetailPage(e) { if (typeof e === 'string') { uni.navigateTo({ url: '/pages/' + e + '/' + e }); } else { uni.navigateTo({ url: e.url }); } } } }; </script> <style> .register-container { display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #fff; } .register-box { width: 80%; padding: 20px; background-color: #f5f5f5; border-radius: 10px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); } .register-title { display: block; text-align: center; font-size: 20px; margin-bottom: 20px; } .input-item { margin-bottom: 15px; } .input-item input { width: 100%; height: 40px; padding: 0 10px; border: 1px solid #ccc; border-radius: 5px; } .register-button { height: 40px; background-color: #007AFF; color: white; border: none; border-radius: 5px; margin-top: 10px; } .login-link { text-align: center; margin-top: 10px; } .login-text { color: #007AFF; } </style>
2301_80750063/SmartUI_lwh050
pages/regist/regist.vue
Vue
unknown
2,711
<template> <view class="news-container"> <!-- 新增功能1: 选择图片并预览 --> <view class="function-section"> <view class="section-title">作业功能一:选择本机图片并预览</view> <view class="function-card"> <text class="function-title">3.1 选择图片 uni.chooseImage(OBJECT)</text> <view class="function-description"> <text>使用uni.chooseImage()选择图片,uni.previewImage()预览图片</text> </view> <button @click="chooseImage" class="func-btn primary-btn">选择图片</button> <view v-if="selectedImages.length > 0" class="image-preview-area"> <text class="preview-title">已选择 {{selectedImages.length}} 张图片</text> <text class="preview-tip">点击任意图片可预览大图</text> <scroll-view class="image-list" scroll-x="true"> <view v-for="(img, index) in selectedImages" :key="index" class="image-item"> <image :src="img" mode="aspectFill" @click="previewImage(index)" class="preview-image"> </image> <text class="image-index">图{{index + 1}}</text> </view> </scroll-view> <view class="preview-actions"> <button @click="previewAllImages" class="func-btn secondary-btn">预览全部</button> <button @click="clearImages" class="func-btn warn-btn">清空图片</button> </view> </view> <view v-else class="empty-state"> <text class="empty-text">暂未选择图片</text> <text class="empty-tip">点击上方按钮选择本地图片</text> </view> </view> </view> <!-- 原有新闻列表保持不变 --> <view class="news-list-section"> <text class="section-title">新闻列表</text> <view v-for="(item, index) in news" :key="item.nID" class="news-item"> <CardViewText :title="item.title" :isTop="item.isTop" :author="item.author" :comments="item.comments" :timedata="item.timedata" :mode="item.mode" :images="item.images" :showSearch="item.showSearch" @click="onCardClick(item.nID)"> <template v-slot:tips v-if="item.showSearch"> <view class="slotcontent"> <text>搜索</text> <view class="borderbox"><text>今日金价</text></view> <view class="borderbox"><text>精选好物</text></view> </view> </template> </CardViewText> </view> </view> </view> </template> <script> import CardViewText from "../../../components/CardViewText.vue" import xinwen from "../../../Data/news.json" export default { components: { CardViewText }, data() { return { news: null, // 新增功能1数据 selectedImages: [] // 选择的图片列表 } }, onShow() { this.news = xinwen.datalist; }, onLoad() { console.log("page onLoad " + this.news); }, methods: { onCardClick(nid) { console.log('点击了新闻:', nid); }, // 功能1: 选择本机图片 - 根据讲义3.1实现 chooseImage() { uni.chooseImage({ count: 6, // 默认9,根据讲义设置为6 sizeType: ['original', 'compressed'], // 原图和压缩图 sourceType: ['album'], // 从相册选择 success: (result) => { // 通过反馈结果中的tempFilePaths获取图片的本地文件路径列表 console.log("选择的图片路径:" + JSON.stringify(result.tempFilePaths)); this.selectedImages = result.tempFilePaths; uni.showToast({ title: `成功选择${result.tempFilePaths.length}张图片`, icon: 'success', duration: 2000 }); }, fail: (error) => { console.error('选择图片失败:', error); uni.showToast({ title: '选择图片失败,请检查权限设置', icon: 'none', duration: 3000 }); } }); }, // 预览单张图片 - 根据讲义3.2实现 previewImage(index) { console.log('预览图片索引:', index); uni.previewImage({ urls: this.selectedImages, current: index, indicator: 'default', loop: true }); }, // 预览全部图片 previewAllImages() { if (this.selectedImages.length === 0) { uni.showToast({ title: '请先选择图片', icon: 'none' }); return; } // 直接预览所有图片,从第一张开始 uni.previewImage({ urls: this.selectedImages, current: 0 }); }, // 清空已选图片 clearImages() { this.selectedImages = []; uni.showToast({ title: '已清空图片', icon: 'success' }); } } } </script> <style scoped> .news-container { padding: 20rpx; background-color: #f5f5f5; min-height: 100vh; } .section-title { font-size: 36rpx; font-weight: bold; color: #333; margin: 30rpx 0 20rpx 0; display: block; padding-left: 20rpx; border-left: 8rpx solid #007AFF; } /* 功能区域样式 */ .function-section { margin-bottom: 40rpx; } .function-card { background-color: #fff; padding: 30rpx; border-radius: 16rpx; margin-bottom: 24rpx; box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08); border: 2rpx solid #e8f4ff; } .function-title { font-size: 32rpx; font-weight: 600; color: #007AFF; display: block; margin-bottom: 15rpx; } .function-description { background-color: #f0f8ff; padding: 20rpx; border-radius: 8rpx; margin-bottom: 25rpx; border-left: 4rpx solid #007AFF; } .function-description text { font-size: 24rpx; color: #666; line-height: 1.6; } /* 按钮样式 */ .func-btn { border-radius: 12rpx; padding: 20rpx 30rpx; font-size: 26rpx; font-weight: 500; margin: 10rpx; border: none; } .primary-btn { background-color: #007AFF; color: white; } .secondary-btn { background-color: #66b3ff; color: white; } .warn-btn { background-color: #ff4d4f; color: white; } /* 图片预览区域 */ .image-preview-area { margin-top: 30rpx; padding: 20rpx; background-color: #f8f9fa; border-radius: 12rpx; border: 1rpx dashed #d9d9d9; } .preview-title { font-size: 28rpx; font-weight: 600; color: #333; display: block; margin-bottom: 8rpx; } .preview-tip { font-size: 22rpx; color: #999; display: block; margin-bottom: 20rpx; } .image-list { white-space: nowrap; margin: 20rpx 0; } .image-item { display: inline-flex; flex-direction: column; align-items: center; margin-right: 25rpx; } .preview-image { width: 140rpx; height: 140rpx; border-radius: 12rpx; border: 3rpx solid #e8f4ff; background-color: #fafafa; } .image-index { font-size: 20rpx; color: #999; margin-top: 8rpx; } .preview-actions { display: flex; justify-content: center; gap: 20rpx; margin-top: 25rpx; } /* 空状态样式 */ .empty-state { text-align: center; padding: 60rpx 20rpx; background-color: #fafafa; border-radius: 12rpx; margin-top: 20rpx; } .empty-text { font-size: 28rpx; color: #999; display: block; margin-bottom: 15rpx; } .empty-tip { font-size: 22rpx; color: #ccc; display: block; } /* 原有新闻列表样式 */ .news-list-section { margin-top: 40rpx; border-top: 2rpx solid #e8e8e8; padding-top: 30rpx; } .news-item { margin-bottom: 24rpx; } .slotcontent { display: flex; align-items: center; margin-top: 20rpx; gap: 16rpx; color: #1890ff; font-size: 26rpx; } .borderbox { padding: 8rpx 16rpx; border: 1rpx solid #e0e0e0; border-radius: 8rpx; background: #fafafa; } </style>
2301_80750063/SmartUI_lwh050
pages/tabBar/CardViewPage/CardViewPage.vue
Vue
unknown
7,424
<template> <view> <navigator url="/pages/APIpages/LogPage/LogPage"> <button>打印日志</button> </navigator> <navigator url="/pages/APIpages/TimerPage/TimerPage"> <button>计时器</button> </navigator> <navigator><button @click="goStotage">数据缓存</button></navigator> <navigator url="/pages/APIpages/imageyulan/imageyulan"> <button>页面刷新</button> </navigator> <navigator url="/pages/APIpages/Tianqiyubao/Tianqiyubao"> <button>天气预报</button> </navigator> <navigator url="/pages/APIpages/DownloadImages/DownloadImages"> <button>图片下载</button> </navigator> <navigator url="/pages/APIpages/IntentPage/IntentPage"> <button>组件传值</button> </navigator> </view> </template> <script> export default { data() { return { } }, onLoad() { uni.preloadPage({ url: "/pages/StoragePage/StoragePage" }) }, methods: { goStotage() { uni.navigateTo({ url: "/pages/StoragePage/StoragePage" }) } } } </script> <style> </style>
2301_80750063/SmartUI_lwh050
pages/tabBar/api/api.vue
Vue
unknown
1,039
<template> <scroll-view scroll-y style="height: 100vh;"> <!-- 轮播图 --> <view class="swiper-card"> <text class="title">泉州风光</text> <swiper circular indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000"> <swiper-item v-for="(item, index) in swiperImages" :key="index"> <image :src="item" style="width: 100%;" /> </swiper-item> </swiper> </view> <!-- 城市介绍 --> <view class="intro-card"> <view class="section"> <text class="title">城市介绍</text> <rich-text :nodes="CityIntro" class="city-intro-rich"></rich-text> </view> </view> <!-- 探索进度卡片 --> <view class="progress-card"> <text class="progress-title">探索进度</text> <view class="progress-bar"> <view class="progress-fill" :style="{ width: progress + '%' }"></view> </view> <text class="progress-percent">{{ progress }}%</text> </view> <!-- 城市选择 --> <view class="picker-card"> <text class="title">选择城市</text> <picker mode="selector" :range="cities" @change="handleCityChange"> <view class="picker-text">当前选择: {{ selectedCity }}</view> </picker> </view> <!-- 偏好设置 --> <view class="preference-card"> <text class="title">偏好设置</text> <view class="preference-item"> <text>出行方式:</text> <radio-group @change="handleTravelModeChange"> <label v-for="(mode, index) in travelModes" :key="index"> <radio :value="mode.value" :checked="mode.value === travelMode" /> <text>{{ mode.label }}</text> </label> </radio-group> </view> <view class="preference-item"> <text>显示推荐景点:</text> <switch :checked="showRecommendations" @change="handleShowRecommendationsChange" /> </view> <view class="preference-item"> <text>探索半径 (km):</text> <slider :value="exploreRadius" @change="handleExploreRadiusChange" min="1" max="50" /> <text>{{ exploreRadius }}km</text> </view> </view> <!-- 媒体展示 --> <view class="video-card"> <text class="title">城市宣传</text> <video :src="videoSrc" controls style="width: 100%;"></video> <text class="video-title">泉州背景音乐</text> <button @click="playMusic">播放</button> </view> </scroll-view> </template> <script> export default { data() { return { swiperImages: [ '/static/city1.png', '/static/city2.jpg', '/static/city3.jpg', '/static/city4.jpg', '/static/city5.jpg' ], CityIntro: ` <h4>海上丝绸之路起点 - 泉州</h4> <p> 历史文化: 泉州是国务院首批公布的24个历史文化名城之一, 是古代 "海上丝绸之路"起点, 宋元时期被誉为 "东方第一大港"。 </p> <p> 著名景点: 清源山、 开元寺、 泉州清净寺、 崇武古城、 洛阳桥等。 </p> <p> 特色文化:拥有<span class='highlight'>南音</span>、 <span class='highlight'>木偶戏</span>和<span class='highlight'>闽南建筑</span>等丰富的非物质文化遗产。 </p> `, progress: 55, cities: ['福建省 - 泉州市 - 丰泽区', '福建省 - 厦门市 - 思明区', '福建省 - 福州市 - 鼓楼区'], selectedCity: '福建省 - 泉州市 - 丰泽区', travelModes: [ { value: 'bus', label: '公交' }, { value: 'car', label: '自驾' }, { value: 'walk', label: '步行' } ], travelMode: 'bus', showRecommendations: true, exploreRadius: 10, videoSrc: '/static/city-video.mp4' // 假设视频文件在static目录下 }; }, methods: { handleCityChange(e) { this.selectedCity = this.cities[e.detail.value]; }, handleTravelModeChange(e) { this.travelMode = e.detail.value; }, handleShowRecommendationsChange(e) { this.showRecommendations = e.detail.value; }, handleExploreRadiusChange(e) { this.exploreRadius = e.detail.value; }, playMusic() { } } }; </script> <style> .title { font-size: 40rpx; font-weight: bold; margin-bottom: 10rpx; display: block; } .section { padding: 20rpx; margin-bottom: 20rpx; background-color: #fff; } .city-intro-rich { font-size: 28rpx; } .highlight { color: #aa55ff; font-weight: bold; } /* 卡片样式 */ .swiper-card{ padding: 30rpx; background-color: #fff; border-radius: 20rpx; box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1); margin: 20rpx; } .intro-card{ padding: 30rpx; background-color: #fff; border-radius: 20rpx; box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1); margin: 20rpx; } .progress-card{ padding: 30rpx; background-color: #fff; border-radius: 20rpx; box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1); margin: 20rpx; } .picker-card{ padding: 30rpx; background-color: #fff; border-radius: 20rpx; box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1); margin: 20rpx; } .preference-card{ padding: 30rpx; background-color: #fff; border-radius: 20rpx; box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1); margin: 20rpx; } .video-card { padding: 30rpx; background-color: #fff; border-radius: 20rpx; box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1); margin: 20rpx; } /* 轮播图图片样式 */ .swiper-image { width: 100%; height: 300rpx; border-radius: 10rpx; } /* 探索进度卡片样式 */ .progress-title { font-size: 32rpx; font-weight: bold; margin-bottom: 20rpx; display: block; } .progress-bar { width: 100%; height: 20rpx; background-color: #e0e0e0; border-radius: 10rpx; overflow: hidden; } .progress-fill { height: 100%; background-color: #007aff; border-radius: 10rpx; } .progress-percent { font-size: 28rpx; color: #666; margin-top: 10rpx; display: block; text-align: right; } /* 城市选择样式 */ .picker-text { font-size: 28rpx; color: #666; margin-top: 10rpx; } /* 偏好设置样式 */ .preference-item { margin-top: 20rpx; } /* 媒体展示样式 */ .video-title { font-size: 28rpx; color: #666; margin-top: 10rpx; display: block; } </style>
2301_80750063/SmartUI_lwh050
pages/tabBar/case/CityDiscovery/CityDiscovery.vue
Vue
unknown
6,266
<template> <view> <view class="smart-container">登录页与注册页</view> <view @click="goDetailPage(('login'))"> <text space="emsp">&nbsp;&emsp;登录页</text> </view> <view class="smart-container">城市探索</view> <view @click="goDetailPage2(('CityDiscovery'))"> <text space="emsp">&nbsp;&emsp;城市探索</text> </view> <view class="smart-container">自定义组件</view> <view @click="goDetailPage2(('CardViewPage'))"> <text space="emsp">&nbsp;&emsp;自定义组件</text> </view> </view> </template> <script> export default { data() { return { } }, methods: { goDetailPage(e) { if (typeof e === 'string') { uni.navigateTo({ url: '/pages/' + e + '/' + e }); } else { uni.navigateTo({ url: e.url }); } }, goDetailPage2(e) { if (typeof e === 'string') { uni.navigateTo({ url: '/pages/tabBar/case/' + e + '/' + e }); } else { uni.navigateTo({ url: e.url }); } } } } </script> <style> </style>
2301_80750063/SmartUI_lwh050
pages/tabBar/case/case.vue
Vue
unknown
1,148
<template> <view class="content"> <image :class="className" src="/static/logo.png"></image> <view class="text-area"> <text class="title" v-on:click="open">{{title}}</text> </view> <view> <view>{{ number + 1 }}</view> <view>{{ ok ? 'YES' : 'NO' }}</view> <view>{{ message.split('').reverse().join('') }}</view> </view> <view> <!-- 传递静态函数--> <button @click="handleClick('参数1')">按钮1</button> <!-- 传递动态函数 (来自data)--> <button @click="handleClick(dynamicParam)">按钮2</button> <!-- 传递多个函数 + 事件对象)--> <button @click="handleClick('参数A', '参数B', $event)">按钮3</button> <!-- 同时获取参数和事件对象--> <button @click="(e) => handleButton('点击事件',e)">带事件对象</button> </view> <view class = "modelclass"> <input v-model="message2" placeholder="edit me"/> <text>Message is : {{ message2 }}</text> </view> <view v-if="!raining">今天天气真好</view> <view v-if="raining">下雨天,只能在家呆着了</view> <view v-if="state === 'vue'">state的值是 Vue</view> <view>State is {{state?'vue':'APP'}}</view> <view> <view v-if="state === 'vue'">uni-app</view> <view v-else-if="state === 'html'"> HTML</view> <view v-else> APP</view> </view> <view v-for="item in arr" :key="item" style="color: #ff0000;"> {{item}} </view> <!-- 修正 v-for 语法和样式语法错误 --> <view v-for="(item, index) in 4" :key="index" style="color:#00ff00;"> <view :class="'list-' + (index % 2)">{{index % 2}}</view> </view> <!-- 修正 object 数据结构和 v-for 语法 --> <view v-for="(value, name, index) in object" :key="name"> {{index}}.{{name}}.{{value}} </view> <view v-for="item in arr" :key="item.id"> <view style="color: #0000ff;">{{item.id}}:{{item.name}}</view> </view> </view> </template> <script> export default { data() { return { title: 'Hello UniAPP', number: 1, ok:true, message: 'Hello Vue!', className:"smalllogo", dynamicParam : "我是动态参数", raining : true, state : 'vue', arr:[ {id:1,name:'uni-app'}, {id:2,name:'HTML'} ], // 修正 object 数据结构,应该是对象而不是数组 object:{ title:'How to lists in Vue', author:'Jame Doe', publishedAt:'2020-04-10' } } }, methods: { open(){ this.title = "opening a new Page"; this.className = 'logo' }, //接收参数 handleClick(param1,param2, event) { console.log("参数2:",param1) console.log("参数1:",param2) console.log("事件对象:",event) }, //同时获取参数和事件对象 handleButton(msg, event){ console.log("接收的消息:",msg) console.log("事件对象:",event) console.log("按钮文本:",event,target.textContent) } } } </script> <style> .content { display: flex; flex-direction: column; align-items: center; justify-content: center; } .logo { height: 200rpx; width: 200rpx; margin-top: 200rpx; margin-left: auto; margin-right: auto; margin-bottom: 50rpx; } .text-area { display: flex; justify-content: center; } .smalllogo { height: 50rpx; width: 50rpx; margin-top: 200rpx; margin-left: auto; margin-right: auto; margin-bottom: 50rpx; } .title { font-size: 36rpx; color: #8f8f94; } </style>
2301_80750063/SmartUI_lwh050
pages/tabBar/grammar/grammar.vue
Vue
unknown
3,410
<template> <view> </view> </template> <script> export default { data() { return { } }, methods: { } } </script> <style> </style>
2301_80750063/SmartUI_lwh050
pages/tabBar/mine/mine.vue
Vue
unknown
162
<template> <view> <view class="smart-container">1.容器</view> <view @click="goDetailPage('view')"> <text space="emsp">&nbsp;&emsp;view视图</text> </view> <view @click="goDetailPage('scroll-view')"> <text space="emsp">&nbsp;&emsp;scroll-view视图</text> </view> <view @click="goDetailPage('swiper')"> <text space="emsp">&nbsp;&emsp;swiper视图</text> </view> <view class="smart-container">2.基础内容</view> <view @click="goDetailPage(('text'))"> <text space="emsp">&nbsp;&emsp;text文本编辑</text> </view> <view @click="goDetailPage(('icon'))"> <text space="emsp">&nbsp;&emsp;icon图标</text> </view> <view class="smart-container">3.表单组件</view> <view @click="goDetailPage(('button'))"> <text space="emsp">&nbsp;&emsp;button按钮</text> </view> <view @click="goDetailPage(('checkbox'))"> <text space="emsp">&nbsp;&emsp;checkbox多选框</text> </view> <view> <text space="emsp">&nbsp;&emsp;label标签组件</text> </view> <view @click="goDetailPage(('input'))"> <text space="emsp">&nbsp;&emsp;input输入框</text> </view> <view> <text space="emsp">&nbsp;&emsp;textarea多行文本输入框</text> </view> <view> <text space="emsp">&nbsp;&emsp;form表单</text> </view> <view class="smart-container">4.导航组件</view> <view @click="goDetailPage(('navigator'))"> <text space="emsp">&nbsp;&emsp;navigator</text> </view> </view> </template> <script> export default { data() { return { } }, methods: { goDetailPage(e) { if (typeof e === 'string') { uni.navigateTo({ url: '/pages/components/' + e + '/' + e }); } else { uni.navigateTo({ url: e.url }); } } } } </script> <style> </style>
2301_80750063/SmartUI_lwh050
pages/tabBar/tabcompage/tabcompage.vue
Vue
unknown
1,828
<template> <view> </view> </template> <script> export default { data() { return { } }, methods: { } } </script> <style> </style>
2301_80750063/SmartUI_lwh050
pages/tabBar/topic/topic.vue
Vue
unknown
162
<template> <view> </view> </template> <script> export default { data() { return { } }, methods: { } } </script> <style> </style>
2301_80750063/SmartUI_lwh050
pages/tabBar/video/video.vue
Vue
unknown
162
uni.addInterceptor({ returnValue (res) { if (!(!!res && (typeof res === "object" || typeof res === "function") && typeof res.then === "function")) { return res; } return new Promise((resolve, reject) => { res.then((res) => { if (!res) return resolve(res) return res[0] ? reject(res[0]) : resolve(res[1]) }); }); }, });
2301_80750063/SmartUI_lwh050
uni.promisify.adaptor.js
JavaScript
unknown
373
/** * 这里是uni-app内置的常用样式变量 * * uni-app 官方扩展插件及插件市场(https://ext.dcloud.net.cn)上很多三方插件均使用了这些样式变量 * 如果你是插件开发者,建议你使用scss预处理,并在插件代码中直接使用这些变量(无需 import 这个文件),方便用户通过搭积木的方式开发整体风格一致的App * */ /** * 如果你是App开发者(插件使用者),你可以通过修改这些变量来定制自己的插件主题,实现自定义主题功能 * * 如果你的项目同样使用了scss预处理,你也可以直接在你的 scss 代码中使用如下变量,同时无需 import 这个文件 */ /* 颜色变量 */ /* 行为相关颜色 */ $uni-color-primary: #007aff; $uni-color-success: #4cd964; $uni-color-warning: #f0ad4e; $uni-color-error: #dd524d; /* 文字基本颜色 */ $uni-text-color:#333;//基本色 $uni-text-color-inverse:#fff;//反色 $uni-text-color-grey:#999;//辅助灰色,如加载更多的提示信息 $uni-text-color-placeholder: #808080; $uni-text-color-disable:#c0c0c0; /* 背景颜色 */ $uni-bg-color:#ffffff; $uni-bg-color-grey:#f8f8f8; $uni-bg-color-hover:#f1f1f1;//点击状态颜色 $uni-bg-color-mask:rgba(0, 0, 0, 0.4);//遮罩颜色 /* 边框颜色 */ $uni-border-color:#c8c7cc; /* 尺寸变量 */ /* 文字尺寸 */ $uni-font-size-sm:12px; $uni-font-size-base:14px; $uni-font-size-lg:16px; /* 图片尺寸 */ $uni-img-size-sm:20px; $uni-img-size-base:26px; $uni-img-size-lg:40px; /* Border Radius */ $uni-border-radius-sm: 2px; $uni-border-radius-base: 3px; $uni-border-radius-lg: 6px; $uni-border-radius-circle: 50%; /* 水平间距 */ $uni-spacing-row-sm: 5px; $uni-spacing-row-base: 10px; $uni-spacing-row-lg: 15px; /* 垂直间距 */ $uni-spacing-col-sm: 4px; $uni-spacing-col-base: 8px; $uni-spacing-col-lg: 12px; /* 透明度 */ $uni-opacity-disabled: 0.3; // 组件禁用态的透明度 /* 文章场景相关 */ $uni-color-title: #2C405A; // 文章标题颜色 $uni-font-size-title:20px; $uni-color-subtitle: #555555; // 二级标题颜色 $uni-font-size-subtitle:26px; $uni-color-paragraph: #3F536E; // 文章段落颜色 $uni-font-size-paragraph:15px;
2301_80750063/SmartUI_lwh050
uni.scss
SCSS
unknown
2,217
# -*- coding: utf-8 -*- """ FastMCP 快速入门示例。 首先,请切换到 `examples/snippets/clients` 目录,然后运行以下命令来启动服务器: uv run server fastmcp_quickstart stdio """ # 从 mcp.server.fastmcp 模块中导入 FastMCP 类,这是构建 MCP 服务器的核心。 from mcp.server.fastmcp import FastMCP # 创建一个 MCP 服务器实例,并将其命名为 "Demo"。 # 这个名字会向连接到此服务器的 AI 客户端展示。 mcp = FastMCP("Demo") # 使用 @mcp.tool() 装饰器来定义一个“工具”。 # 工具是 AI 可以调用的具体函数,用于执行特定的操作。 @mcp.tool() def add(a: int, b: int) -> int: """ 这个工具的功能是计算两个整数的和。 文档字符串(docstring)会作为工具的描述,帮助 AI 理解其功能。 """ result = a + b return result # 使用 @mcp.resource() 装饰器来定义一个“资源”。 # 资源代表 AI 可以访问的数据或信息。这里的路径 "greeting://{name}" 是动态的, # {name} 部分可以被实际的名称替换,例如 "greeting://World"。 @mcp.resource("greeting://{name}") def get_greeting(name: str) -> str: """ 根据提供的名称,获取一句个性化的问候语。 """ # 使用 f-string 格式化字符串,返回包含名字的问候语。 return f"Hello, {name}!" # 使用 @mcp.prompt() 装饰器来定义一个“提示词模板”。 # 这个功能可以根据输入动态生成更复杂的、用于指导大语言模型(LLM)的指令(Prompt)。 # @mcp.prompt() # def greet_user(name: str, style: str = "friendly") -> str: # """ # 根据给定的名字和风格,生成一句问候语的提示词。 # """ # # 定义一个字典,存储不同风格对应的提示词文本。 # styles = { # "friendly": "Please write a warm, friendly greeting", # "formal": "Please write a formal, professional greeting", # "casual": "Please write a casual, relaxed greeting", # } # # 根据传入的 style 参数,从字典中获取对应的提示词。 # # 如果 style 参数无效或未提供,则默认使用 "friendly" 风格。 # # 最后,将选择的风格提示词与用户名组合,形成一个完整的指令。 # return f"{styles.get(style, styles['friendly'])} for someone named {name}." if __name__ == "__main__": mcp.run(transport="sse")
2301_80863610/undoom-sketch-mcp
main copy.py
Python
mit
2,451
# -*- coding: utf-8 -*- """ 图片素描化 MCP 服务器。 提供图片素描化功能的 MCP 服务器,可以将输入的图片转换为素描效果。 支持多种素描风格和批量处理功能。 """ # 导入必要的库 import cv2 import numpy as np import os import base64 import glob from pathlib import Path from mcp.server.fastmcp import FastMCP # 创建一个 MCP 服务器实例,并将其命名为 "SketchConverter"。 # 这个名字会向连接到此服务器的 AI 客户端展示。 mcp = FastMCP("SketchConverter") # 支持的图片格式 SUPPORTED_FORMATS = {'.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff', '.webp'} def dodgeV2(image, mask, contrast=256.0): """图像混合函数,用于生成素描效果""" return cv2.divide(image, 255 - mask, scale=contrast) def validate_image_path(image_path: str) -> tuple[bool, str]: """验证图片路径和格式""" if not os.path.exists(image_path): return False, f"错误: 文件不存在 - {image_path}" file_ext = Path(image_path).suffix.lower() if file_ext not in SUPPORTED_FORMATS: return False, f"错误: 不支持的图片格式 - {file_ext}。支持的格式: {', '.join(SUPPORTED_FORMATS)}" return True, "验证通过" def load_image_safely(image_path: str): """安全加载图片,支持中文路径""" try: # 使用numpy读取图片,支持中文路径 img_array = np.fromfile(image_path, dtype=np.uint8) image = cv2.imdecode(img_array, cv2.IMREAD_COLOR) return image except Exception as e: return None def save_image_safely(image, output_path: str) -> bool: """安全保存图片,支持中文路径""" try: # 确保输出目录存在 os.makedirs(os.path.dirname(output_path), exist_ok=True) # 获取文件扩展名 ext = os.path.splitext(output_path)[1].lower() # 编码图片 success, encoded_img = cv2.imencode(ext, image) if success: # 写入文件 with open(output_path, 'wb') as f: f.write(encoded_img.tobytes()) return True return False except Exception as e: return False @mcp.tool() def convert_image_to_sketch(image_path: str, blur_size: int = 21, contrast: float = 256.0, style: str = "classic") -> str: """ 将输入的图片转换为素描效果。 参数: - image_path: 图片文件的路径 - blur_size: 高斯模糊的核大小,必须为奇数,默认为21 - contrast: 对比度参数,默认为256.0 - style: 素描风格 ("classic", "detailed", "soft") 返回: - 成功时返回保存的素描图片路径,失败时返回错误信息 """ try: # 验证图片路径 is_valid, message = validate_image_path(image_path) if not is_valid: return message # 确保blur_size是奇数且在合理范围内 blur_size = max(3, min(101, blur_size)) # 限制在3-101之间 if blur_size % 2 == 0: blur_size += 1 # 限制对比度参数 contrast = max(50.0, min(500.0, contrast)) # 限制在50-500之间 # 加载图片 src_image = load_image_safely(image_path) if src_image is None: return f"错误: 无法加载图片 - {image_path}" # 转换为灰度图 img_gray = cv2.cvtColor(src_image, cv2.COLOR_BGR2GRAY) # 根据风格调整处理参数 if style == "detailed": # 详细风格:更小的模糊核,更高的对比度 blur_size = max(3, blur_size // 2) if blur_size % 2 == 0: blur_size += 1 contrast *= 1.2 elif style == "soft": # 柔和风格:更大的模糊核,更低的对比度 blur_size = min(51, blur_size * 2) if blur_size % 2 == 0: blur_size += 1 contrast *= 0.8 # 反转灰度图 img_gray_inv = 255 - img_gray # 应用高斯模糊 img_blur = cv2.GaussianBlur(img_gray_inv, ksize=(blur_size, blur_size), sigmaX=0, sigmaY=0) # 使用dodgeV2函数进行混合 sketch_image = dodgeV2(img_gray, img_blur, contrast) # 后处理:增强对比度和锐化 if style == "detailed": # 对详细风格进行锐化处理 kernel = np.array([[-1,-1,-1], [-1,9,-1], [-1,-1,-1]]) sketch_image = cv2.filter2D(sketch_image, -1, kernel) sketch_image = np.clip(sketch_image, 0, 255).astype(np.uint8) # 生成输出文件名 original_filename = os.path.basename(image_path) filename_without_ext = os.path.splitext(original_filename)[0] output_dir = os.path.dirname(image_path) output_path = os.path.join(output_dir, f"Sketch_{style}_{filename_without_ext}.jpg") # 保存素描图片 if save_image_safely(sketch_image, output_path): return f"素描转换成功! 风格: {style}, 输出文件: {output_path}" else: return f"错误: 保存图片失败 - {output_path}" except Exception as e: return f"错误: 转换过程中出现异常 - {str(e)}" @mcp.tool() def batch_convert_images(folder_path: str, blur_size: int = 21, contrast: float = 256.0, style: str = "classic") -> str: """ 批量转换文件夹中的所有图片为素描效果。 参数: - folder_path: 包含图片的文件夹路径 - blur_size: 高斯模糊的核大小,默认为21 - contrast: 对比度参数,默认为256.0 - style: 素描风格 ("classic", "detailed", "soft") 返回: - 处理结果统计信息 """ try: if not os.path.exists(folder_path): return f"错误: 文件夹不存在 - {folder_path}" if not os.path.isdir(folder_path): return f"错误: 路径不是文件夹 - {folder_path}" # 查找所有支持的图片文件 image_files = [] for ext in SUPPORTED_FORMATS: pattern = os.path.join(folder_path, f"*{ext}") image_files.extend(glob.glob(pattern)) pattern = os.path.join(folder_path, f"*{ext.upper()}") image_files.extend(glob.glob(pattern)) if not image_files: return f"在文件夹中未找到支持的图片文件: {folder_path}" success_count = 0 error_count = 0 error_messages = [] for image_file in image_files: result = convert_image_to_sketch(image_file, blur_size, contrast, style) if result.startswith("素描转换成功"): success_count += 1 else: error_count += 1 error_messages.append(f"{os.path.basename(image_file)}: {result}") result_summary = f"批量处理完成!\n" result_summary += f"成功转换: {success_count} 张图片\n" result_summary += f"失败: {error_count} 张图片\n" if error_messages: result_summary += f"\n错误详情:\n" + "\n".join(error_messages[:5]) # 只显示前5个错误 if len(error_messages) > 5: result_summary += f"\n... 还有 {len(error_messages) - 5} 个错误" return result_summary except Exception as e: return f"错误: 批量处理过程中出现异常 - {str(e)}" @mcp.tool() def get_image_info(image_path: str) -> str: """ 获取图片的基本信息。 参数: - image_path: 图片文件的路径 返回: - 图片信息字符串 """ try: # 验证图片路径 is_valid, message = validate_image_path(image_path) if not is_valid: return message # 加载图片 image = load_image_safely(image_path) if image is None: return f"错误: 无法加载图片 - {image_path}" # 获取图片信息 height, width = image.shape[:2] channels = image.shape[2] if len(image.shape) == 3 else 1 file_size = os.path.getsize(image_path) file_size_mb = file_size / (1024 * 1024) info = f"图片信息:\n" info += f"文件名: {os.path.basename(image_path)}\n" info += f"尺寸: {width} x {height} 像素\n" info += f"通道数: {channels}\n" info += f"文件大小: {file_size_mb:.2f} MB\n" info += f"格式: {Path(image_path).suffix.upper()}\n" # 建议的处理参数 if width * height > 2000000: # 大于200万像素 info += f"\n建议参数 (大图片):\n" info += f"- blur_size: 31-51\n" info += f"- contrast: 200-300\n" elif width * height > 500000: # 大于50万像素 info += f"\n建议参数 (中等图片):\n" info += f"- blur_size: 21-31\n" info += f"- contrast: 256\n" else: info += f"\n建议参数 (小图片):\n" info += f"- blur_size: 11-21\n" info += f"- contrast: 300-400\n" return info except Exception as e: return f"错误: 获取图片信息时出现异常 - {str(e)}" # 使用 @mcp.resource() 装饰器来定义一个"资源"。 # 资源代表 AI 可以访问的数据或信息。这里提供素描转换的帮助信息。 @mcp.resource("sketch://help") def get_sketch_help() -> str: """ 获取图片素描转换功能的帮助信息。 """ help_text = """ 🎨 图片素描转换工具使用说明 📋 功能列表: 1. convert_image_to_sketch - 单张图片素描转换 2. batch_convert_images - 批量图片素描转换 3. get_image_info - 获取图片信息和建议参数 🖼️ 支持的图片格式: JPG, JPEG, PNG, BMP, GIF, TIFF, WEBP 🎭 素描风格: - classic: 经典素描风格 (默认) - detailed: 详细素描风格 (更清晰的线条) - soft: 柔和素描风格 (更柔和的效果) ⚙️ 参数说明: - image_path: 图片文件的完整路径 (必需) - blur_size: 高斯模糊核大小 (3-101,奇数,默认21) - contrast: 对比度参数 (50-500,默认256.0) - style: 素描风格 (classic/detailed/soft,默认classic) 📝 使用示例: 1. 单张转换: convert_image_to_sketch("/path/to/image.jpg", 21, 256.0, "classic") 2. 批量转换: batch_convert_images("/path/to/folder", 21, 256.0, "detailed") 3. 获取图片信息: get_image_info("/path/to/image.jpg") 💡 使用技巧: - 大图片建议使用较大的blur_size (31-51) - 小图片建议使用较小的blur_size (11-21) - detailed风格适合人像和细节丰富的图片 - soft风格适合风景和需要柔和效果的图片 - 可以先用get_image_info查看图片信息和建议参数 📁 输出文件: - 单张转换:原目录下,文件名格式为 "Sketch_{style}_{原文件名}.jpg" - 批量转换:每张图片都在原目录下生成对应的素描版本 ⚠️ 注意事项: - 确保图片文件存在且可读 - 支持中文路径和文件名 - 处理大图片时可能需要较长时间 - 建议在处理前备份原图片 """ return help_text if __name__ == "__main__": mcp.run(transport="sse")
2301_80863610/undoom-sketch-mcp
main.py
Python
mit
11,461
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 简单的图片素描转换示例 直接调用本地的素描转换功能,无需MCP协议。 """ import sys import os # 添加当前目录到Python路径 sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from undoom_sketch_mcp.server import convert_image_to_sketch, get_image_info def main(): """主函数 - 直接调用素描转换功能""" # 图片路径 image_path = r"D:\mcp_test\Cool Romantic Anime Character.png" print("🎨 图片素描转换示例") print("=" * 50) # 检查图片是否存在 if not os.path.exists(image_path): print(f"❌ 图片文件不存在: {image_path}") return print(f"📁 输入图片: {os.path.basename(image_path)}") # 获取图片信息 print("\n📊 获取图片信息...") info_result = get_image_info(image_path) print(info_result) # 转换为经典素描风格 print("\n🎨 转换为经典素描风格...") classic_result = convert_image_to_sketch( image_path=image_path, blur_size=21, contrast=256.0, style="classic" ) print(f"结果: {classic_result}") # 转换为详细素描风格 print("\n🎨 转换为详细素描风格...") detailed_result = convert_image_to_sketch( image_path=image_path, blur_size=21, contrast=256.0, style="detailed" ) print(f"结果: {detailed_result}") # 转换为柔和素描风格 print("\n🎨 转换为柔和素描风格...") soft_result = convert_image_to_sketch( image_path=image_path, blur_size=21, contrast=256.0, style="soft" ) print(f"结果: {soft_result}") print("\n✅ 所有转换完成!") print("\n💡 生成的素描图片保存在原图片相同目录下") print(" 文件名格式: Sketch_{style}_{原文件名}.jpg") if __name__ == "__main__": main()
2301_80863610/undoom-sketch-mcp
simple_sketch_example.py
Python
mit
1,996
""" Undoom Sketch MCP - 图片素描化转换服务器 一个基于 MCP (Model Context Protocol) 的图片素描化服务器, 可以将普通图片转换为素描效果,支持多种风格和批量处理。 """ __version__ = "0.1.4" __author__ = "Undoom" __email__ = "kaikaihuhu666@163.com" from .server import main __all__ = ["main"]
2301_80863610/undoom-sketch-mcp
undoom_sketch_mcp/__init__.py
Python
mit
341
#!/usr/bin/env python3 """ Undoom Sketch MCP Server - 主入口点 通过 python -m undoom_sketch_mcp 启动服务器 """ from .server import main if __name__ == "__main__": main()
2301_80863610/undoom-sketch-mcp
undoom_sketch_mcp/__main__.py
Python
mit
187
# -*- coding: utf-8 -*- """ 图片素描化 MCP 服务器。 提供图片素描化功能的 MCP 服务器,可以将输入的图片转换为素描效果。 支持多种素描风格和批量处理功能。 """ # 导入必要的库 import cv2 import numpy as np import os import base64 import glob from pathlib import Path from mcp.server.fastmcp import FastMCP # 创建一个 MCP 服务器实例,并将其命名为 "SketchConverter"。 # 这个名字会向连接到此服务器的 AI 客户端展示。 mcp = FastMCP("SketchConverter") # 支持的图片格式 SUPPORTED_FORMATS = {'.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff', '.webp'} def dodgeV2(image, mask, contrast=256.0): """图像混合函数,用于生成素描效果""" return cv2.divide(image, 255 - mask, scale=contrast) def validate_image_path(image_path: str) -> tuple[bool, str]: """验证图片路径和格式""" if not os.path.exists(image_path): return False, f"错误: 文件不存在 - {image_path}" file_ext = Path(image_path).suffix.lower() if file_ext not in SUPPORTED_FORMATS: return False, f"错误: 不支持的图片格式 - {file_ext}。支持的格式: {', '.join(SUPPORTED_FORMATS)}" return True, "验证通过" def load_image_safely(image_path: str): """安全加载图片,支持中文路径""" try: # 使用numpy读取图片,支持中文路径 img_array = np.fromfile(image_path, dtype=np.uint8) image = cv2.imdecode(img_array, cv2.IMREAD_COLOR) return image except Exception as e: return None def save_image_safely(image, output_path: str) -> bool: """安全保存图片,支持中文路径""" try: # 确保输出目录存在 os.makedirs(os.path.dirname(output_path), exist_ok=True) # 获取文件扩展名 ext = os.path.splitext(output_path)[1].lower() # 编码图片 success, encoded_img = cv2.imencode(ext, image) if success: # 写入文件 with open(output_path, 'wb') as f: f.write(encoded_img.tobytes()) return True return False except Exception as e: return False @mcp.tool() def convert_image_to_sketch(image_path: str, blur_size: int = 21, contrast: float = 256.0, style: str = "classic") -> str: """ 将输入的图片转换为素描效果。 参数: - image_path: 图片文件的路径 - blur_size: 高斯模糊的核大小,必须为奇数,默认为21 - contrast: 对比度参数,默认为256.0 - style: 素描风格 ("classic", "detailed", "soft") 返回: - 成功时返回保存的素描图片路径,失败时返回错误信息 """ try: # 验证图片路径 is_valid, message = validate_image_path(image_path) if not is_valid: return message # 确保blur_size是奇数且在合理范围内 blur_size = max(3, min(101, blur_size)) # 限制在3-101之间 if blur_size % 2 == 0: blur_size += 1 # 限制对比度参数 contrast = max(50.0, min(500.0, contrast)) # 限制在50-500之间 # 加载图片 src_image = load_image_safely(image_path) if src_image is None: return f"错误: 无法加载图片 - {image_path}" # 转换为灰度图 img_gray = cv2.cvtColor(src_image, cv2.COLOR_BGR2GRAY) # 根据风格调整处理参数 if style == "detailed": # 详细风格:更小的模糊核,更高的对比度 blur_size = max(3, blur_size // 2) if blur_size % 2 == 0: blur_size += 1 contrast *= 1.2 elif style == "soft": # 柔和风格:更大的模糊核,更低的对比度 blur_size = min(51, blur_size * 2) if blur_size % 2 == 0: blur_size += 1 contrast *= 0.8 # 反转灰度图 img_gray_inv = 255 - img_gray # 应用高斯模糊 img_blur = cv2.GaussianBlur(img_gray_inv, ksize=(blur_size, blur_size), sigmaX=0, sigmaY=0) # 使用dodgeV2函数进行混合 sketch_image = dodgeV2(img_gray, img_blur, contrast) # 后处理:增强对比度和锐化 if style == "detailed": # 对详细风格进行锐化处理 kernel = np.array([[-1,-1,-1], [-1,9,-1], [-1,-1,-1]]) sketch_image = cv2.filter2D(sketch_image, -1, kernel) sketch_image = np.clip(sketch_image, 0, 255).astype(np.uint8) # 生成输出文件名 original_filename = os.path.basename(image_path) filename_without_ext = os.path.splitext(original_filename)[0] output_dir = os.path.dirname(image_path) output_path = os.path.join(output_dir, f"Sketch_{style}_{filename_without_ext}.jpg") # 保存素描图片 if save_image_safely(sketch_image, output_path): return f"素描转换成功! 风格: {style}, 输出文件: {output_path}" else: return f"错误: 保存图片失败 - {output_path}" except Exception as e: return f"错误: 转换过程中出现异常 - {str(e)}" @mcp.tool() def batch_convert_images(folder_path: str, blur_size: int = 21, contrast: float = 256.0, style: str = "classic") -> str: """ 批量转换文件夹中的所有图片为素描效果。 参数: - folder_path: 包含图片的文件夹路径 - blur_size: 高斯模糊的核大小,默认为21 - contrast: 对比度参数,默认为256.0 - style: 素描风格 ("classic", "detailed", "soft") 返回: - 处理结果统计信息 """ try: if not os.path.exists(folder_path): return f"错误: 文件夹不存在 - {folder_path}" if not os.path.isdir(folder_path): return f"错误: 路径不是文件夹 - {folder_path}" # 查找所有支持的图片文件 image_files = [] for ext in SUPPORTED_FORMATS: pattern = os.path.join(folder_path, f"*{ext}") image_files.extend(glob.glob(pattern)) pattern = os.path.join(folder_path, f"*{ext.upper()}") image_files.extend(glob.glob(pattern)) if not image_files: return f"在文件夹中未找到支持的图片文件: {folder_path}" success_count = 0 error_count = 0 error_messages = [] for image_file in image_files: result = convert_image_to_sketch(image_file, blur_size, contrast, style) if result.startswith("素描转换成功"): success_count += 1 else: error_count += 1 error_messages.append(f"{os.path.basename(image_file)}: {result}") result_summary = f"批量处理完成!\n" result_summary += f"成功转换: {success_count} 张图片\n" result_summary += f"失败: {error_count} 张图片\n" if error_messages: result_summary += f"\n错误详情:\n" + "\n".join(error_messages[:5]) # 只显示前5个错误 if len(error_messages) > 5: result_summary += f"\n... 还有 {len(error_messages) - 5} 个错误" return result_summary except Exception as e: return f"错误: 批量处理过程中出现异常 - {str(e)}" @mcp.tool() def get_image_info(image_path: str) -> str: """ 获取图片的基本信息。 参数: - image_path: 图片文件的路径 返回: - 图片信息字符串 """ try: # 验证图片路径 is_valid, message = validate_image_path(image_path) if not is_valid: return message # 加载图片 image = load_image_safely(image_path) if image is None: return f"错误: 无法加载图片 - {image_path}" # 获取图片信息 height, width = image.shape[:2] channels = image.shape[2] if len(image.shape) == 3 else 1 file_size = os.path.getsize(image_path) file_size_mb = file_size / (1024 * 1024) info = f"图片信息:\n" info += f"文件名: {os.path.basename(image_path)}\n" info += f"尺寸: {width} x {height} 像素\n" info += f"通道数: {channels}\n" info += f"文件大小: {file_size_mb:.2f} MB\n" info += f"格式: {Path(image_path).suffix.upper()}\n" # 建议的处理参数 if width * height > 2000000: # 大于200万像素 info += f"\n建议参数 (大图片):\n" info += f"- blur_size: 31-51\n" info += f"- contrast: 200-300\n" elif width * height > 500000: # 大于50万像素 info += f"\n建议参数 (中等图片):\n" info += f"- blur_size: 21-31\n" info += f"- contrast: 256\n" else: info += f"\n建议参数 (小图片):\n" info += f"- blur_size: 11-21\n" info += f"- contrast: 300-400\n" return info except Exception as e: return f"错误: 获取图片信息时出现异常 - {str(e)}" # 使用 @mcp.resource() 装饰器来定义一个"资源"。 # 资源代表 AI 可以访问的数据或信息。这里提供素描转换的帮助信息。 @mcp.resource("sketch://help") def get_sketch_help() -> str: """ 获取图片素描转换功能的帮助信息。 """ help_text = """ 🎨 图片素描转换工具使用说明 📋 功能列表: 1. convert_image_to_sketch - 单张图片素描转换 2. batch_convert_images - 批量图片素描转换 3. get_image_info - 获取图片信息和建议参数 🖼️ 支持的图片格式: JPG, JPEG, PNG, BMP, GIF, TIFF, WEBP 🎭 素描风格: - classic: 经典素描风格 (默认) - detailed: 详细素描风格 (更清晰的线条) - soft: 柔和素描风格 (更柔和的效果) ⚙️ 参数说明: - image_path: 图片文件的完整路径 (必需) - blur_size: 高斯模糊核大小 (3-101,奇数,默认21) - contrast: 对比度参数 (50-500,默认256.0) - style: 素描风格 (classic/detailed/soft,默认classic) 📝 使用示例: 1. 单张转换: convert_image_to_sketch("/path/to/image.jpg", 21, 256.0, "classic") 2. 批量转换: batch_convert_images("/path/to/folder", 21, 256.0, "detailed") 3. 获取图片信息: get_image_info("/path/to/image.jpg") 💡 使用技巧: - 大图片建议使用较大的blur_size (31-51) - 小图片建议使用较小的blur_size (11-21) - detailed风格适合人像和细节丰富的图片 - soft风格适合风景和需要柔和效果的图片 - 可以先用get_image_info查看图片信息和建议参数 📁 输出文件: - 单张转换:原目录下,文件名格式为 "Sketch_{style}_{原文件名}.jpg" - 批量转换:每张图片都在原目录下生成对应的素描版本 ⚠️ 注意事项: - 确保图片文件存在且可读 - 支持中文路径和文件名 - 处理大图片时可能需要较长时间 - 建议在处理前备份原图片 """ return help_text def main(): """主函数,启动MCP服务器""" mcp.run(transport="stdio") if __name__ == "__main__": main()
2301_80863610/undoom-sketch-mcp
undoom_sketch_mcp/server.py
Python
mit
11,528
# Written in 2016-2017, 2021 by Henrik Steffen Gaßmann henrik@gassmann.onl # # To the extent possible under law, the author(s) have dedicated all # copyright and related and neighboring rights to this software to the # public domain worldwide. This software is distributed without any warranty. # # You should have received a copy of the CC0 Public Domain Dedication # along with this software. If not, see # # http://creativecommons.org/publicdomain/zero/1.0/ # ######################################################################## cmake_minimum_required(VERSION 3.10.2) # new dependent option syntax. We are already compliant if (POLICY CMP0127) cmake_policy(SET CMP0127 NEW) endif() project(base64 LANGUAGES C VERSION 0.5.2) include(GNUInstallDirs) include(CMakeDependentOption) include(CheckIncludeFile) include(FeatureSummary) list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules") ####################################################################### # platform detection include(TargetArch) detect_target_architecture(_TARGET_ARCH) check_include_file(getopt.h HAVE_GETOPT_H) cmake_dependent_option(BASE64_BUILD_CLI "Build the cli for encoding and decoding" ON "HAVE_GETOPT_H" OFF) add_feature_info(CLI BASE64_BUILD_CLI "enables the CLI executable for encoding and decoding") ################################################################### # optional/conditional dependencies find_package(OpenMP) set_package_properties(OpenMP PROPERTIES TYPE OPTIONAL PURPOSE "Allows to utilize OpenMP" ) ######################################################################## # Compilation options option(BASE64_WERROR "Treat warnings as error" ON) option(BASE64_BUILD_TESTS "add test projects" OFF) cmake_dependent_option(BASE64_WITH_OpenMP "use OpenMP" OFF "OpenMP_FOUND" OFF) add_feature_info("OpenMP codec" BASE64_WITH_OpenMP "spreads codec work accross multiple threads") cmake_dependent_option(BASE64_REGENERATE_TABLES "regenerate the codec tables" OFF "NOT CMAKE_CROSSCOMPILING" OFF) set(_IS_X86 "_TARGET_ARCH_x86 OR _TARGET_ARCH_x64") cmake_dependent_option(BASE64_WITH_SSSE3 "add SSSE 3 codepath" ON ${_IS_X86} OFF) add_feature_info(SSSE3 BASE64_WITH_SSSE3 "add SSSE 3 codepath") cmake_dependent_option(BASE64_WITH_SSE41 "add SSE 4.1 codepath" ON ${_IS_X86} OFF) add_feature_info(SSE4.1 BASE64_WITH_SSE41 "add SSE 4.1 codepath") cmake_dependent_option(BASE64_WITH_SSE42 "add SSE 4.2 codepath" ON ${_IS_X86} OFF) add_feature_info(SSE4.2 BASE64_WITH_SSE42 "add SSE 4.2 codepath") cmake_dependent_option(BASE64_WITH_AVX "add AVX codepath" ON ${_IS_X86} OFF) add_feature_info(AVX BASE64_WITH_AVX "add AVX codepath") cmake_dependent_option(BASE64_WITH_AVX2 "add AVX 2 codepath" ON ${_IS_X86} OFF) add_feature_info(AVX2 BASE64_WITH_AVX2 "add AVX2 codepath") cmake_dependent_option(BASE64_WITH_AVX512 "add AVX 512 codepath" ON ${_IS_X86} OFF) add_feature_info(AVX512 BASE64_WITH_AVX512 "add AVX512 codepath") cmake_dependent_option(BASE64_WITH_NEON32 "add NEON32 codepath" OFF _TARGET_ARCH_arm OFF) add_feature_info(NEON32 BASE64_WITH_NEON32 "add NEON32 codepath") cmake_dependent_option(BASE64_WITH_NEON64 "add NEON64 codepath" ON _TARGET_ARCH_arm64 OFF) add_feature_info(NEON64 BASE64_WITH_NEON64 "add NEON64 codepath") set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/bin") set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/bin") ######################################################################## # Regenerate headers if (BASE64_REGENERATE_TABLES) # Generate tables in build folder and copy to source tree. # Don't add the tables in the source tree to the outputs, to avoid `make clean` removing them. add_executable(table_generator lib/tables/table_generator.c ) add_custom_command(OUTPUT table_dec_32bit.h "${CMAKE_CURRENT_SOURCE_DIR}/lib/tables/table_dec_32bit.h" COMMAND table_generator > table_dec_32bit.h COMMAND "${CMAKE_COMMAND}" -E copy table_dec_32bit.h "${CMAKE_CURRENT_SOURCE_DIR}/lib/tables/table_dec_32bit.h" DEPENDS table_generator ) set(Python_ADDITIONAL_VERSIONS 3) find_package(PythonInterp REQUIRED) add_custom_command(OUTPUT table_enc_12bit.h "${CMAKE_CURRENT_SOURCE_DIR}/lib/tables/table_enc_12bit.h" COMMAND "${PYTHON_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/lib/tables/table_enc_12bit.py" > table_enc_12bit.h COMMAND "${CMAKE_COMMAND}" -E copy table_enc_12bit.h "${CMAKE_CURRENT_SOURCE_DIR}/lib/tables/table_enc_12bit.h" DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/lib/tables/table_enc_12bit.py" ) endif() ######################################################################## # library project add_library(base64 # library files lib/lib.c lib/codec_choose.c include/libbase64.h lib/tables/tables.c # Add generated headers explicitly to target, to insert them in the dependency tree lib/tables/table_dec_32bit.h lib/tables/table_enc_12bit.h # codec implementations lib/arch/generic/codec.c lib/arch/ssse3/codec.c lib/arch/sse41/codec.c lib/arch/sse42/codec.c lib/arch/avx/codec.c lib/arch/avx2/codec.c lib/arch/avx512/codec.c lib/arch/neon32/codec.c lib/arch/neon64/codec.c ) target_include_directories(base64 PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include> $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}> PRIVATE "${CMAKE_CURRENT_BINARY_DIR}" ) #################################################################### # platform/compiler specific configuration set_target_properties(base64 PROPERTIES C_STANDARD 99 C_STANDARD_REQUIRED YES C_EXTENSIONS OFF DEFINE_SYMBOL BASE64_EXPORTS VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION_MAJOR} ) #generate_export_header(base64) # the following definitions and those in libbase64.h have been # kept forward compatible in case we ever switch to generate_export_header if (BUILD_SHARED_LIBS) set_target_properties(base64 PROPERTIES C_VISIBILITY_PRESET hidden ) else() target_compile_definitions(base64 PUBLIC BASE64_STATIC_DEFINE ) endif() target_compile_options(base64 PRIVATE $<$<C_COMPILER_ID:MSVC>: /W4 /we4013 # Error warning C4013: 'function' undefined; assuming extern returning int /we4700 # Error warning C4700: uninitialized local variable /we4715 # not all control paths return a value /we4003 # not enough actual parameters for macro /wd4456 # disable warning C4456: declaration of 'xxx' hides previous local declaration > $<$<NOT:$<C_COMPILER_ID:MSVC>>: -Wall -Wextra -Wpedantic > $<$<BOOL:${BASE64_WERROR}>:$<IF:$<C_COMPILER_ID:MSVC>,/WX,-Werror>> ) target_compile_definitions(base64 PRIVATE $<$<C_COMPILER_ID:MSVC>: # remove unnecessary warnings about unchecked iterators _SCL_SECURE_NO_WARNINGS > ) ######################################################################## # SIMD settings include(TargetSIMDInstructionSet) define_SIMD_compile_flags() if (_TARGET_ARCH STREQUAL "x86" OR _TARGET_ARCH STREQUAL "x64") macro(configure_codec _TYPE) if (BASE64_WITH_${_TYPE}) string(TOLOWER "${_TYPE}" _DIR) set_source_files_properties("lib/arch/${_DIR}/codec.c" PROPERTIES COMPILE_FLAGS "${COMPILE_FLAGS_${_TYPE}}" ) if (${ARGC} GREATER 1 AND MSVC) set_source_files_properties("lib/arch/${_DIR}/codec.c" PROPERTIES COMPILE_DEFINITIONS ${ARGV1} ) endif() endif() endmacro() configure_codec(SSSE3 __SSSE3__) configure_codec(SSE41 __SSSE4_1__) configure_codec(SSE42 __SSSE4_2__) configure_codec(AVX) configure_codec(AVX2) configure_codec(AVX512) elseif (_TARGET_ARCH STREQUAL "arm") set(BASE64_NEON32_CFLAGS "${COMPILE_FLAGS_NEON32}" CACHE STRING "the NEON32 compile flags (for 'lib/arch/neon32/codec.c')") mark_as_advanced(BASE64_NEON32_CFLAGS) if (BASE64_WITH_NEON32) set_source_files_properties("lib/arch/neon32/codec.c" PROPERTIES COMPILE_FLAGS "${BASE64_NEON32_CFLAGS} " ) endif() #elseif (_TARGET_ARCH STREQUAL "arm64" AND BASE64_WITH_NEON64) endif() configure_file("${CMAKE_CURRENT_LIST_DIR}/cmake/config.h.in" "${CMAKE_CURRENT_BINARY_DIR}/config.h" @ONLY) ######################################################################## # OpenMP Settings if (BASE64_WITH_OpenMP) target_link_libraries(base64 PRIVATE OpenMP::OpenMP_C) endif() ######################################################################## if (BASE64_BUILD_TESTS) enable_testing() add_subdirectory(test) endif() ######################################################################## # base64 if (BASE64_BUILD_CLI) add_executable(base64-bin bin/base64.c ) target_link_libraries(base64-bin PRIVATE base64) set_target_properties(base64-bin PROPERTIES OUTPUT_NAME base64 ) if (WIN32) target_sources(base64-bin PRIVATE bin/base64.rc) endif () endif() ######################################################################## # cmake install install(DIRECTORY include/ TYPE INCLUDE) install(TARGETS base64 EXPORT base64-targets DESTINATION ${CMAKE_INSTALL_LIBDIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} ) if (BASE64_BUILD_CLI) install(TARGETS base64-bin EXPORT base64-targets DESTINATION ${CMAKE_INSTALL_BINDIR}) endif() include(CMakePackageConfigHelpers) configure_package_config_file(cmake/base64-config.cmake.in "${CMAKE_CURRENT_BINARY_DIR}/base64-config.cmake" INSTALL_DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}" ) write_basic_package_version_file( "${CMAKE_CURRENT_BINARY_DIR}/base64-config-version.cmake" VERSION ${BASE64_VERSION} COMPATIBILITY SameMajorVersion ) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/base64-config.cmake" "${CMAKE_CURRENT_BINARY_DIR}/base64-config-version.cmake" DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}" ) install(EXPORT base64-targets NAMESPACE aklomp:: DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}" ) ######################################################################## feature_summary(WHAT PACKAGES_FOUND PACKAGES_NOT_FOUND ENABLED_FEATURES DISABLED_FEATURES)
2301_81045437/base64
CMakeLists.txt
CMake
bsd
10,403
CFLAGS += -std=c99 -O3 -Wall -Wextra -pedantic -DBASE64_STATIC_DEFINE # Set OBJCOPY if not defined by environment: OBJCOPY ?= objcopy OBJS = \ lib/arch/avx512/codec.o \ lib/arch/avx2/codec.o \ lib/arch/generic/codec.o \ lib/arch/neon32/codec.o \ lib/arch/neon64/codec.o \ lib/arch/ssse3/codec.o \ lib/arch/sse41/codec.o \ lib/arch/sse42/codec.o \ lib/arch/avx/codec.o \ lib/lib.o \ lib/codec_choose.o \ lib/tables/tables.o HAVE_AVX512 = 0 HAVE_AVX2 = 0 HAVE_NEON32 = 0 HAVE_NEON64 = 0 HAVE_SSSE3 = 0 HAVE_SSE41 = 0 HAVE_SSE42 = 0 HAVE_AVX = 0 # The user should supply compiler flags for the codecs they want to build. # Check which codecs we're going to include: ifdef AVX512_CFLAGS HAVE_AVX512 = 1 endif ifdef AVX2_CFLAGS HAVE_AVX2 = 1 endif ifdef NEON32_CFLAGS HAVE_NEON32 = 1 endif ifdef NEON64_CFLAGS HAVE_NEON64 = 1 endif ifdef SSSE3_CFLAGS HAVE_SSSE3 = 1 endif ifdef SSE41_CFLAGS HAVE_SSE41 = 1 endif ifdef SSE42_CFLAGS HAVE_SSE42 = 1 endif ifdef AVX_CFLAGS HAVE_AVX = 1 endif ifdef OPENMP CFLAGS += -fopenmp endif TARGET := $(shell $(CC) -dumpmachine) .PHONY: all analyze clean all: bin/base64 lib/libbase64.o bin/base64: bin/base64.o lib/libbase64.o $(CC) $(CFLAGS) -o $@ $^ # Workaround: mangle exported function names on MinGW32. lib/exports.build.txt: lib/exports.txt ifeq (i686-w64-mingw32, $(TARGET)) sed -e 's/^/_/' $< > $@ else cp -f $< $@ endif lib/libbase64.o: lib/exports.build.txt $(OBJS) $(LD) -r -o $@ $(OBJS) $(OBJCOPY) --keep-global-symbols=$< $@ lib/config.h: @echo "#define HAVE_AVX512 $(HAVE_AVX512)" > $@ @echo "#define HAVE_AVX2 $(HAVE_AVX2)" >> $@ @echo "#define HAVE_NEON32 $(HAVE_NEON32)" >> $@ @echo "#define HAVE_NEON64 $(HAVE_NEON64)" >> $@ @echo "#define HAVE_SSSE3 $(HAVE_SSSE3)" >> $@ @echo "#define HAVE_SSE41 $(HAVE_SSE41)" >> $@ @echo "#define HAVE_SSE42 $(HAVE_SSE42)" >> $@ @echo "#define HAVE_AVX $(HAVE_AVX)" >> $@ $(OBJS): lib/config.h $(OBJS): CFLAGS += -Ilib lib/arch/avx512/codec.o: CFLAGS += $(AVX512_CFLAGS) lib/arch/avx2/codec.o: CFLAGS += $(AVX2_CFLAGS) lib/arch/neon32/codec.o: CFLAGS += $(NEON32_CFLAGS) lib/arch/neon64/codec.o: CFLAGS += $(NEON64_CFLAGS) lib/arch/ssse3/codec.o: CFLAGS += $(SSSE3_CFLAGS) lib/arch/sse41/codec.o: CFLAGS += $(SSE41_CFLAGS) lib/arch/sse42/codec.o: CFLAGS += $(SSE42_CFLAGS) lib/arch/avx/codec.o: CFLAGS += $(AVX_CFLAGS) %.o: %.c $(CC) $(CFLAGS) -o $@ -c $< analyze: clean scan-build --use-analyzer=`which clang` --status-bugs make clean: rm -f bin/base64 bin/base64.o lib/libbase64.o lib/config.h lib/exports.build.txt $(OBJS)
2301_81045437/base64
Makefile
Makefile
bsd
2,620
# Written in 2017 by Henrik Steffen Gaßmann henrik@gassmann.onl # # To the extent possible under law, the author(s) have dedicated all # copyright and related and neighboring rights to this software to the # public domain worldwide. This software is distributed without any warranty. # # You should have received a copy of the CC0 Public Domain Dedication # along with this software. If not, see # # http://creativecommons.org/publicdomain/zero/1.0/ # ######################################################################## set(TARGET_ARCHITECTURE_TEST_FILE "${CMAKE_CURRENT_LIST_DIR}/../test-arch.c") function(detect_target_architecture OUTPUT_VARIABLE) message(STATUS "${CMAKE_CURRENT_LIST_DIR}") try_compile(_IGNORED "${CMAKE_CURRENT_BINARY_DIR}" "${TARGET_ARCHITECTURE_TEST_FILE}" OUTPUT_VARIABLE _LOG ) string(REGEX MATCH "##arch=([^#]+)##" _IGNORED "${_LOG}") set(${OUTPUT_VARIABLE} "${CMAKE_MATCH_1}" PARENT_SCOPE) set("${OUTPUT_VARIABLE}_${CMAKE_MATCH_1}" 1 PARENT_SCOPE) if (CMAKE_MATCH_1 STREQUAL "unknown") message(WARNING "could not detect the target architecture.") endif() endfunction()
2301_81045437/base64
cmake/Modules/TargetArch.cmake
CMake
bsd
1,167
# Written in 2016-2017 by Henrik Steffen Gaßmann henrik@gassmann.onl # # To the extent possible under law, the author(s) have dedicated all # copyright and related and neighboring rights to this software to the # public domain worldwide. This software is distributed without any warranty. # # You should have received a copy of the CC0 Public Domain Dedication # along with this software. If not, see # # http://creativecommons.org/publicdomain/zero/1.0/ # ######################################################################## ######################################################################## # compiler flags definition macro(define_SIMD_compile_flags) if (CMAKE_C_COMPILER_ID STREQUAL "GNU" OR CMAKE_C_COMPILER_ID STREQUAL "Clang" OR CMAKE_C_COMPILER_ID STREQUAL "AppleClang") # x86 set(COMPILE_FLAGS_SSSE3 "-mssse3") set(COMPILE_FLAGS_SSE41 "-msse4.1") set(COMPILE_FLAGS_SSE42 "-msse4.2") set(COMPILE_FLAGS_AVX "-mavx") set(COMPILE_FLAGS_AVX2 "-mavx2") set(COMPILE_FLAGS_AVX512 "-mavx512vl -mavx512vbmi") #arm set(COMPILE_FLAGS_NEON32 "-mfpu=neon") elseif(MSVC) set(COMPILE_FLAGS_SSSE3 " ") set(COMPILE_FLAGS_SSE41 " ") set(COMPILE_FLAGS_SSE42 " ") set(COMPILE_FLAGS_AVX "/arch:AVX") set(COMPILE_FLAGS_AVX2 "/arch:AVX2") set(COMPILE_FLAGS_AVX512 "/arch:AVX512") endif() endmacro(define_SIMD_compile_flags)
2301_81045437/base64
cmake/Modules/TargetSIMDInstructionSet.cmake
CMake
bsd
1,458
@PACKAGE_INIT@ include("${CMAKE_CURRENT_LIST_DIR}/base64-targets.cmake") check_required_components(base64)
2301_81045437/base64
cmake/base64-config.cmake.in
CMake
bsd
109
// Written in 2017 by Henrik Steffen Gaßmann henrik@gassmann.onl // // To the extent possible under law, the author(s) have dedicated all // copyright and related and neighboring rights to this software to the // public domain worldwide. This software is distributed without any warranty. // // You should have received a copy of the CC0 Public Domain Dedication // along with this software. If not, see // // http://creativecommons.org/publicdomain/zero/1.0/ // //////////////////////////////////////////////////////////////////////////////// // ARM 64-Bit #if defined(__aarch64__) #error ##arch=arm64## // ARM 32-Bit #elif defined(__arm__) \ || defined(_M_ARM) #error ##arch=arm## // x86 64-Bit #elif defined(__x86_64__) \ || defined(_M_X64) #error ##arch=x64## // x86 32-Bit #elif defined(__i386__) \ || defined(_M_IX86) #error ##arch=x86## #else #error ##arch=unknown## #endif
2301_81045437/base64
cmake/test-arch.c
C
bsd
903
#ifndef LIBBASE64_H #define LIBBASE64_H #include <stddef.h> /* size_t */ #if defined(_WIN32) || defined(__CYGWIN__) #define BASE64_SYMBOL_IMPORT __declspec(dllimport) #define BASE64_SYMBOL_EXPORT __declspec(dllexport) #define BASE64_SYMBOL_PRIVATE #elif __GNUC__ >= 4 #define BASE64_SYMBOL_IMPORT __attribute__ ((visibility ("default"))) #define BASE64_SYMBOL_EXPORT __attribute__ ((visibility ("default"))) #define BASE64_SYMBOL_PRIVATE __attribute__ ((visibility ("hidden"))) #else #define BASE64_SYMBOL_IMPORT #define BASE64_SYMBOL_EXPORT #define BASE64_SYMBOL_PRIVATE #endif #if defined(BASE64_STATIC_DEFINE) #define BASE64_EXPORT #define BASE64_NO_EXPORT #else #if defined(BASE64_EXPORTS) // defined if we are building the shared library #define BASE64_EXPORT BASE64_SYMBOL_EXPORT #else #define BASE64_EXPORT BASE64_SYMBOL_IMPORT #endif #define BASE64_NO_EXPORT BASE64_SYMBOL_PRIVATE #endif #ifdef __cplusplus extern "C" { #endif /* These are the flags that can be passed in the `flags` argument. The values * below force the use of a given codec, even if that codec is a no-op in the * current build. Used in testing. Set to 0 for the default behavior, which is * runtime feature detection on x86, a compile-time fixed codec on ARM, and * the plain codec on other platforms: */ #define BASE64_FORCE_AVX2 (1 << 0) #define BASE64_FORCE_NEON32 (1 << 1) #define BASE64_FORCE_NEON64 (1 << 2) #define BASE64_FORCE_PLAIN (1 << 3) #define BASE64_FORCE_SSSE3 (1 << 4) #define BASE64_FORCE_SSE41 (1 << 5) #define BASE64_FORCE_SSE42 (1 << 6) #define BASE64_FORCE_AVX (1 << 7) #define BASE64_FORCE_AVX512 (1 << 8) struct base64_state { int eof; int bytes; int flags; unsigned char carry; }; /* Wrapper function to encode a plain string of given length. Output is written * to *out without trailing zero. Output length in bytes is written to *outlen. * The buffer in `out` has been allocated by the caller and is at least 4/3 the * size of the input. See above for `flags`; set to 0 for default operation: */ void BASE64_EXPORT base64_encode ( const char *src , size_t srclen , char *out , size_t *outlen , int flags ) ; /* Call this before calling base64_stream_encode() to init the state. See above * for `flags`; set to 0 for default operation: */ void BASE64_EXPORT base64_stream_encode_init ( struct base64_state *state , int flags ) ; /* Encodes the block of data of given length at `src`, into the buffer at * `out`. Caller is responsible for allocating a large enough out-buffer; it * must be at least 4/3 the size of the in-buffer, but take some margin. Places * the number of new bytes written into `outlen` (which is set to zero when the * function starts). Does not zero-terminate or finalize the output. */ void BASE64_EXPORT base64_stream_encode ( struct base64_state *state , const char *src , size_t srclen , char *out , size_t *outlen ) ; /* Finalizes the output begun by previous calls to `base64_stream_encode()`. * Adds the required end-of-stream markers if appropriate. `outlen` is modified * and will contain the number of new bytes written at `out` (which will quite * often be zero). */ void BASE64_EXPORT base64_stream_encode_final ( struct base64_state *state , char *out , size_t *outlen ) ; /* Wrapper function to decode a plain string of given length. Output is written * to *out without trailing zero. Output length in bytes is written to *outlen. * The buffer in `out` has been allocated by the caller and is at least 3/4 the * size of the input. See above for `flags`, set to 0 for default operation: */ int BASE64_EXPORT base64_decode ( const char *src , size_t srclen , char *out , size_t *outlen , int flags ) ; /* Call this before calling base64_stream_decode() to init the state. See above * for `flags`; set to 0 for default operation: */ void BASE64_EXPORT base64_stream_decode_init ( struct base64_state *state , int flags ) ; /* Decodes the block of data of given length at `src`, into the buffer at * `out`. Caller is responsible for allocating a large enough out-buffer; it * must be at least 3/4 the size of the in-buffer, but take some margin. Places * the number of new bytes written into `outlen` (which is set to zero when the * function starts). Does not zero-terminate the output. Returns 1 if all is * well, and 0 if a decoding error was found, such as an invalid character. * Returns -1 if the chosen codec is not included in the current build. Used by * the test harness to check whether a codec is available for testing. */ int BASE64_EXPORT base64_stream_decode ( struct base64_state *state , const char *src , size_t srclen , char *out , size_t *outlen ) ; #ifdef __cplusplus } #endif #endif /* LIBBASE64_H */
2301_81045437/base64
include/libbase64.h
C
bsd
4,789
#include <stdint.h> #include <stddef.h> #include <stdlib.h> #include "../../../include/libbase64.h" #include "../../tables/tables.h" #include "../../codecs.h" #include "config.h" #include "../../env.h" #if HAVE_AVX #include <immintrin.h> // Only enable inline assembly on supported compilers and on 64-bit CPUs. #ifndef BASE64_AVX_USE_ASM # if (defined(__GNUC__) || defined(__clang__)) && BASE64_WORDSIZE == 64 # define BASE64_AVX_USE_ASM 1 # else # define BASE64_AVX_USE_ASM 0 # endif #endif #include "../ssse3/dec_reshuffle.c" #include "../ssse3/dec_loop.c" #if BASE64_AVX_USE_ASM # include "enc_loop_asm.c" #else # include "../ssse3/enc_translate.c" # include "../ssse3/enc_reshuffle.c" # include "../ssse3/enc_loop.c" #endif #endif // HAVE_AVX void base64_stream_encode_avx BASE64_ENC_PARAMS { #if HAVE_AVX #include "../generic/enc_head.c" // For supported compilers, use a hand-optimized inline assembly // encoder. Otherwise fall back on the SSSE3 encoder, but compiled with // AVX flags to generate better optimized AVX code. #if BASE64_AVX_USE_ASM enc_loop_avx(&s, &slen, &o, &olen); #else enc_loop_ssse3(&s, &slen, &o, &olen); #endif #include "../generic/enc_tail.c" #else base64_enc_stub(state, src, srclen, out, outlen); #endif } int base64_stream_decode_avx BASE64_DEC_PARAMS { #if HAVE_AVX #include "../generic/dec_head.c" dec_loop_ssse3(&s, &slen, &o, &olen); #include "../generic/dec_tail.c" #else return base64_dec_stub(state, src, srclen, out, outlen); #endif }
2301_81045437/base64
lib/arch/avx/codec.c
C
bsd
1,504
// Apologies in advance for combining the preprocessor with inline assembly, // two notoriously gnarly parts of C, but it was necessary to avoid a lot of // code repetition. The preprocessor is used to template large sections of // inline assembly that differ only in the registers used. If the code was // written out by hand, it would become very large and hard to audit. // Generate a block of inline assembly that loads register R0 from memory. The // offset at which the register is loaded is set by the given round. #define LOAD(R0, ROUND) \ "vlddqu ("#ROUND" * 12)(%[src]), %["R0"] \n\t" // Generate a block of inline assembly that deinterleaves and shuffles register // R0 using preloaded constants. Outputs in R0 and R1. #define SHUF(R0, R1, R2) \ "vpshufb %[lut0], %["R0"], %["R1"] \n\t" \ "vpand %["R1"], %[msk0], %["R2"] \n\t" \ "vpand %["R1"], %[msk2], %["R1"] \n\t" \ "vpmulhuw %["R2"], %[msk1], %["R2"] \n\t" \ "vpmullw %["R1"], %[msk3], %["R1"] \n\t" \ "vpor %["R1"], %["R2"], %["R1"] \n\t" // Generate a block of inline assembly that takes R0 and R1 and translates // their contents to the base64 alphabet, using preloaded constants. #define TRAN(R0, R1, R2) \ "vpsubusb %[n51], %["R1"], %["R0"] \n\t" \ "vpcmpgtb %[n25], %["R1"], %["R2"] \n\t" \ "vpsubb %["R2"], %["R0"], %["R0"] \n\t" \ "vpshufb %["R0"], %[lut1], %["R2"] \n\t" \ "vpaddb %["R1"], %["R2"], %["R0"] \n\t" // Generate a block of inline assembly that stores the given register R0 at an // offset set by the given round. #define STOR(R0, ROUND) \ "vmovdqu %["R0"], ("#ROUND" * 16)(%[dst]) \n\t" // Generate a block of inline assembly that generates a single self-contained // encoder round: fetch the data, process it, and store the result. Then update // the source and destination pointers. #define ROUND() \ LOAD("a", 0) \ SHUF("a", "b", "c") \ TRAN("a", "b", "c") \ STOR("a", 0) \ "add $12, %[src] \n\t" \ "add $16, %[dst] \n\t" // Define a macro that initiates a three-way interleaved encoding round by // preloading registers a, b and c from memory. // The register graph shows which registers are in use during each step, and // is a visual aid for choosing registers for that step. Symbol index: // // + indicates that a register is loaded by that step. // | indicates that a register is in use and must not be touched. // - indicates that a register is decommissioned by that step. // x indicates that a register is used as a temporary by that step. // V indicates that a register is an input or output to the macro. // #define ROUND_3_INIT() /* a b c d e f */ \ LOAD("a", 0) /* + */ \ SHUF("a", "d", "e") /* | + x */ \ LOAD("b", 1) /* | + | */ \ TRAN("a", "d", "e") /* | | - x */ \ LOAD("c", 2) /* V V V */ // Define a macro that translates, shuffles and stores the input registers A, B // and C, and preloads registers D, E and F for the next round. // This macro can be arbitrarily daisy-chained by feeding output registers D, E // and F back into the next round as input registers A, B and C. The macro // carefully interleaves memory operations with data operations for optimal // pipelined performance. #define ROUND_3(ROUND, A,B,C,D,E,F) /* A B C D E F */ \ LOAD(D, (ROUND + 3)) /* V V V + */ \ SHUF(B, E, F) /* | | | | + x */ \ STOR(A, (ROUND + 0)) /* - | | | | */ \ TRAN(B, E, F) /* | | | - x */ \ LOAD(E, (ROUND + 4)) /* | | | + */ \ SHUF(C, A, F) /* + | | | | x */ \ STOR(B, (ROUND + 1)) /* | - | | | */ \ TRAN(C, A, F) /* - | | | x */ \ LOAD(F, (ROUND + 5)) /* | | | + */ \ SHUF(D, A, B) /* + x | | | | */ \ STOR(C, (ROUND + 2)) /* | - | | | */ \ TRAN(D, A, B) /* - x V V V */ // Define a macro that terminates a ROUND_3 macro by taking pre-loaded // registers D, E and F, and translating, shuffling and storing them. #define ROUND_3_END(ROUND, A,B,C,D,E,F) /* A B C D E F */ \ SHUF(E, A, B) /* + x V V V */ \ STOR(D, (ROUND + 3)) /* | - | | */ \ TRAN(E, A, B) /* - x | | */ \ SHUF(F, C, D) /* + x | | */ \ STOR(E, (ROUND + 4)) /* | - | */ \ TRAN(F, C, D) /* - x | */ \ STOR(F, (ROUND + 5)) /* - */ // Define a type A round. Inputs are a, b, and c, outputs are d, e, and f. #define ROUND_3_A(ROUND) \ ROUND_3(ROUND, "a", "b", "c", "d", "e", "f") // Define a type B round. Inputs and outputs are swapped with regard to type A. #define ROUND_3_B(ROUND) \ ROUND_3(ROUND, "d", "e", "f", "a", "b", "c") // Terminating macro for a type A round. #define ROUND_3_A_LAST(ROUND) \ ROUND_3_A(ROUND) \ ROUND_3_END(ROUND, "a", "b", "c", "d", "e", "f") // Terminating macro for a type B round. #define ROUND_3_B_LAST(ROUND) \ ROUND_3_B(ROUND) \ ROUND_3_END(ROUND, "d", "e", "f", "a", "b", "c") // Suppress clang's warning that the literal string in the asm statement is // overlong (longer than the ISO-mandated minimum size of 4095 bytes for C99 // compilers). It may be true, but the goal here is not C99 portability. #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Woverlength-strings" static inline void enc_loop_avx (const uint8_t **s, size_t *slen, uint8_t **o, size_t *olen) { // For a clearer explanation of the algorithm used by this function, // please refer to the plain (not inline assembly) implementation. This // function follows the same basic logic. if (*slen < 16) { return; } // Process blocks of 12 bytes at a time. Input is read in blocks of 16 // bytes, so "reserve" four bytes from the input buffer to ensure that // we never read beyond the end of the input buffer. size_t rounds = (*slen - 4) / 12; *slen -= rounds * 12; // 12 bytes consumed per round *olen += rounds * 16; // 16 bytes produced per round // Number of times to go through the 36x loop. size_t loops = rounds / 36; // Number of rounds remaining after the 36x loop. rounds %= 36; // Lookup tables. const __m128i lut0 = _mm_set_epi8( 10, 11, 9, 10, 7, 8, 6, 7, 4, 5, 3, 4, 1, 2, 0, 1); const __m128i lut1 = _mm_setr_epi8( 65, 71, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -19, -16, 0, 0); // Temporary registers. __m128i a, b, c, d, e, f; __asm__ volatile ( // If there are 36 rounds or more, enter a 36x unrolled loop of // interleaved encoding rounds. The rounds interleave memory // operations (load/store) with data operations (table lookups, // etc) to maximize pipeline throughput. " test %[loops], %[loops] \n\t" " jz 18f \n\t" " jmp 36f \n\t" " \n\t" ".balign 64 \n\t" "36: " ROUND_3_INIT() " " ROUND_3_A( 0) " " ROUND_3_B( 3) " " ROUND_3_A( 6) " " ROUND_3_B( 9) " " ROUND_3_A(12) " " ROUND_3_B(15) " " ROUND_3_A(18) " " ROUND_3_B(21) " " ROUND_3_A(24) " " ROUND_3_B(27) " " ROUND_3_A_LAST(30) " add $(12 * 36), %[src] \n\t" " add $(16 * 36), %[dst] \n\t" " dec %[loops] \n\t" " jnz 36b \n\t" // Enter an 18x unrolled loop for rounds of 18 or more. "18: cmp $18, %[rounds] \n\t" " jl 9f \n\t" " " ROUND_3_INIT() " " ROUND_3_A(0) " " ROUND_3_B(3) " " ROUND_3_A(6) " " ROUND_3_B(9) " " ROUND_3_A_LAST(12) " sub $18, %[rounds] \n\t" " add $(12 * 18), %[src] \n\t" " add $(16 * 18), %[dst] \n\t" // Enter a 9x unrolled loop for rounds of 9 or more. "9: cmp $9, %[rounds] \n\t" " jl 6f \n\t" " " ROUND_3_INIT() " " ROUND_3_A(0) " " ROUND_3_B_LAST(3) " sub $9, %[rounds] \n\t" " add $(12 * 9), %[src] \n\t" " add $(16 * 9), %[dst] \n\t" // Enter a 6x unrolled loop for rounds of 6 or more. "6: cmp $6, %[rounds] \n\t" " jl 55f \n\t" " " ROUND_3_INIT() " " ROUND_3_A_LAST(0) " sub $6, %[rounds] \n\t" " add $(12 * 6), %[src] \n\t" " add $(16 * 6), %[dst] \n\t" // Dispatch the remaining rounds 0..5. "55: cmp $3, %[rounds] \n\t" " jg 45f \n\t" " je 3f \n\t" " cmp $1, %[rounds] \n\t" " jg 2f \n\t" " je 1f \n\t" " jmp 0f \n\t" "45: cmp $4, %[rounds] \n\t" " je 4f \n\t" // Block of non-interlaced encoding rounds, which can each // individually be jumped to. Rounds fall through to the next. "5: " ROUND() "4: " ROUND() "3: " ROUND() "2: " ROUND() "1: " ROUND() "0: \n\t" // Outputs (modified). : [rounds] "+r" (rounds), [loops] "+r" (loops), [src] "+r" (*s), [dst] "+r" (*o), [a] "=&x" (a), [b] "=&x" (b), [c] "=&x" (c), [d] "=&x" (d), [e] "=&x" (e), [f] "=&x" (f) // Inputs (not modified). : [lut0] "x" (lut0), [lut1] "x" (lut1), [msk0] "x" (_mm_set1_epi32(0x0FC0FC00)), [msk1] "x" (_mm_set1_epi32(0x04000040)), [msk2] "x" (_mm_set1_epi32(0x003F03F0)), [msk3] "x" (_mm_set1_epi32(0x01000010)), [n51] "x" (_mm_set1_epi8(51)), [n25] "x" (_mm_set1_epi8(25)) // Clobbers. : "cc", "memory" ); } #pragma GCC diagnostic pop
2301_81045437/base64
lib/arch/avx/enc_loop_asm.c
C
bsd
9,314
#include <stdint.h> #include <stddef.h> #include <stdlib.h> #include "../../../include/libbase64.h" #include "../../tables/tables.h" #include "../../codecs.h" #include "config.h" #include "../../env.h" #if HAVE_AVX2 #include <immintrin.h> // Only enable inline assembly on supported compilers and on 64-bit CPUs. #ifndef BASE64_AVX2_USE_ASM # if (defined(__GNUC__) || defined(__clang__)) && BASE64_WORDSIZE == 64 # define BASE64_AVX2_USE_ASM 1 # else # define BASE64_AVX2_USE_ASM 0 # endif #endif #include "dec_reshuffle.c" #include "dec_loop.c" #if BASE64_AVX2_USE_ASM # include "enc_loop_asm.c" #else # include "enc_translate.c" # include "enc_reshuffle.c" # include "enc_loop.c" #endif #endif // HAVE_AVX2 void base64_stream_encode_avx2 BASE64_ENC_PARAMS { #if HAVE_AVX2 #include "../generic/enc_head.c" enc_loop_avx2(&s, &slen, &o, &olen); #include "../generic/enc_tail.c" #else base64_enc_stub(state, src, srclen, out, outlen); #endif } int base64_stream_decode_avx2 BASE64_DEC_PARAMS { #if HAVE_AVX2 #include "../generic/dec_head.c" dec_loop_avx2(&s, &slen, &o, &olen); #include "../generic/dec_tail.c" #else return base64_dec_stub(state, src, srclen, out, outlen); #endif }
2301_81045437/base64
lib/arch/avx2/codec.c
C
bsd
1,199
static BASE64_FORCE_INLINE int dec_loop_avx2_inner (const uint8_t **s, uint8_t **o, size_t *rounds) { const __m256i lut_lo = _mm256_setr_epi8( 0x15, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x13, 0x1A, 0x1B, 0x1B, 0x1B, 0x1A, 0x15, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x13, 0x1A, 0x1B, 0x1B, 0x1B, 0x1A); const __m256i lut_hi = _mm256_setr_epi8( 0x10, 0x10, 0x01, 0x02, 0x04, 0x08, 0x04, 0x08, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x01, 0x02, 0x04, 0x08, 0x04, 0x08, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10); const __m256i lut_roll = _mm256_setr_epi8( 0, 16, 19, 4, -65, -65, -71, -71, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 19, 4, -65, -65, -71, -71, 0, 0, 0, 0, 0, 0, 0, 0); const __m256i mask_2F = _mm256_set1_epi8(0x2F); // Load input: __m256i str = _mm256_loadu_si256((__m256i *) *s); // See the SSSE3 decoder for an explanation of the algorithm. const __m256i hi_nibbles = _mm256_and_si256(_mm256_srli_epi32(str, 4), mask_2F); const __m256i lo_nibbles = _mm256_and_si256(str, mask_2F); const __m256i hi = _mm256_shuffle_epi8(lut_hi, hi_nibbles); const __m256i lo = _mm256_shuffle_epi8(lut_lo, lo_nibbles); if (!_mm256_testz_si256(lo, hi)) { return 0; } const __m256i eq_2F = _mm256_cmpeq_epi8(str, mask_2F); const __m256i roll = _mm256_shuffle_epi8(lut_roll, _mm256_add_epi8(eq_2F, hi_nibbles)); // Now simply add the delta values to the input: str = _mm256_add_epi8(str, roll); // Reshuffle the input to packed 12-byte output format: str = dec_reshuffle(str); // Store the output: _mm256_storeu_si256((__m256i *) *o, str); *s += 32; *o += 24; *rounds -= 1; return 1; } static inline void dec_loop_avx2 (const uint8_t **s, size_t *slen, uint8_t **o, size_t *olen) { if (*slen < 45) { return; } // Process blocks of 32 bytes per round. Because 8 extra zero bytes are // written after the output, ensure that there will be at least 13 // bytes of input data left to cover the gap. (11 data bytes and up to // two end-of-string markers.) size_t rounds = (*slen - 13) / 32; *slen -= rounds * 32; // 32 bytes consumed per round *olen += rounds * 24; // 24 bytes produced per round do { if (rounds >= 8) { if (dec_loop_avx2_inner(s, o, &rounds) && dec_loop_avx2_inner(s, o, &rounds) && dec_loop_avx2_inner(s, o, &rounds) && dec_loop_avx2_inner(s, o, &rounds) && dec_loop_avx2_inner(s, o, &rounds) && dec_loop_avx2_inner(s, o, &rounds) && dec_loop_avx2_inner(s, o, &rounds) && dec_loop_avx2_inner(s, o, &rounds)) { continue; } break; } if (rounds >= 4) { if (dec_loop_avx2_inner(s, o, &rounds) && dec_loop_avx2_inner(s, o, &rounds) && dec_loop_avx2_inner(s, o, &rounds) && dec_loop_avx2_inner(s, o, &rounds)) { continue; } break; } if (rounds >= 2) { if (dec_loop_avx2_inner(s, o, &rounds) && dec_loop_avx2_inner(s, o, &rounds)) { continue; } break; } dec_loop_avx2_inner(s, o, &rounds); break; } while (rounds > 0); // Adjust for any rounds that were skipped: *slen += rounds * 32; *olen -= rounds * 24; }
2301_81045437/base64
lib/arch/avx2/dec_loop.c
C
bsd
3,229
static BASE64_FORCE_INLINE __m256i dec_reshuffle (const __m256i in) { // in, lower lane, bits, upper case are most significant bits, lower // case are least significant bits: // 00llllll 00kkkkLL 00jjKKKK 00JJJJJJ // 00iiiiii 00hhhhII 00ggHHHH 00GGGGGG // 00ffffff 00eeeeFF 00ddEEEE 00DDDDDD // 00cccccc 00bbbbCC 00aaBBBB 00AAAAAA const __m256i merge_ab_and_bc = _mm256_maddubs_epi16(in, _mm256_set1_epi32(0x01400140)); // 0000kkkk LLllllll 0000JJJJ JJjjKKKK // 0000hhhh IIiiiiii 0000GGGG GGggHHHH // 0000eeee FFffffff 0000DDDD DDddEEEE // 0000bbbb CCcccccc 0000AAAA AAaaBBBB __m256i out = _mm256_madd_epi16(merge_ab_and_bc, _mm256_set1_epi32(0x00011000)); // 00000000 JJJJJJjj KKKKkkkk LLllllll // 00000000 GGGGGGgg HHHHhhhh IIiiiiii // 00000000 DDDDDDdd EEEEeeee FFffffff // 00000000 AAAAAAaa BBBBbbbb CCcccccc // Pack bytes together in each lane: out = _mm256_shuffle_epi8(out, _mm256_setr_epi8( 2, 1, 0, 6, 5, 4, 10, 9, 8, 14, 13, 12, -1, -1, -1, -1, 2, 1, 0, 6, 5, 4, 10, 9, 8, 14, 13, 12, -1, -1, -1, -1)); // 00000000 00000000 00000000 00000000 // LLllllll KKKKkkkk JJJJJJjj IIiiiiii // HHHHhhhh GGGGGGgg FFffffff EEEEeeee // DDDDDDdd CCcccccc BBBBbbbb AAAAAAaa // Pack lanes: return _mm256_permutevar8x32_epi32(out, _mm256_setr_epi32(0, 1, 2, 4, 5, 6, -1, -1)); }
2301_81045437/base64
lib/arch/avx2/dec_reshuffle.c
C
bsd
1,304
static BASE64_FORCE_INLINE void enc_loop_avx2_inner_first (const uint8_t **s, uint8_t **o) { // First load is done at s - 0 to not get a segfault: __m256i src = _mm256_loadu_si256((__m256i *) *s); // Shift by 4 bytes, as required by enc_reshuffle: src = _mm256_permutevar8x32_epi32(src, _mm256_setr_epi32(0, 0, 1, 2, 3, 4, 5, 6)); // Reshuffle, translate, store: src = enc_reshuffle(src); src = enc_translate(src); _mm256_storeu_si256((__m256i *) *o, src); // Subsequent loads will be done at s - 4, set pointer for next round: *s += 20; *o += 32; } static BASE64_FORCE_INLINE void enc_loop_avx2_inner (const uint8_t **s, uint8_t **o) { // Load input: __m256i src = _mm256_loadu_si256((__m256i *) *s); // Reshuffle, translate, store: src = enc_reshuffle(src); src = enc_translate(src); _mm256_storeu_si256((__m256i *) *o, src); *s += 24; *o += 32; } static inline void enc_loop_avx2 (const uint8_t **s, size_t *slen, uint8_t **o, size_t *olen) { if (*slen < 32) { return; } // Process blocks of 24 bytes at a time. Because blocks are loaded 32 // bytes at a time an offset of -4, ensure that there will be at least // 4 remaining bytes after the last round, so that the final read will // not pass beyond the bounds of the input buffer: size_t rounds = (*slen - 4) / 24; *slen -= rounds * 24; // 24 bytes consumed per round *olen += rounds * 32; // 32 bytes produced per round // The first loop iteration requires special handling to ensure that // the read, which is done at an offset, does not underflow the buffer: enc_loop_avx2_inner_first(s, o); rounds--; while (rounds > 0) { if (rounds >= 8) { enc_loop_avx2_inner(s, o); enc_loop_avx2_inner(s, o); enc_loop_avx2_inner(s, o); enc_loop_avx2_inner(s, o); enc_loop_avx2_inner(s, o); enc_loop_avx2_inner(s, o); enc_loop_avx2_inner(s, o); enc_loop_avx2_inner(s, o); rounds -= 8; continue; } if (rounds >= 4) { enc_loop_avx2_inner(s, o); enc_loop_avx2_inner(s, o); enc_loop_avx2_inner(s, o); enc_loop_avx2_inner(s, o); rounds -= 4; continue; } if (rounds >= 2) { enc_loop_avx2_inner(s, o); enc_loop_avx2_inner(s, o); rounds -= 2; continue; } enc_loop_avx2_inner(s, o); break; } // Add the offset back: *s += 4; }
2301_81045437/base64
lib/arch/avx2/enc_loop.c
C
bsd
2,293
// Apologies in advance for combining the preprocessor with inline assembly, // two notoriously gnarly parts of C, but it was necessary to avoid a lot of // code repetition. The preprocessor is used to template large sections of // inline assembly that differ only in the registers used. If the code was // written out by hand, it would become very large and hard to audit. // Generate a block of inline assembly that loads register R0 from memory. The // offset at which the register is loaded is set by the given round and a // constant offset. #define LOAD(R0, ROUND, OFFSET) \ "vlddqu ("#ROUND" * 24 + "#OFFSET")(%[src]), %["R0"] \n\t" // Generate a block of inline assembly that deinterleaves and shuffles register // R0 using preloaded constants. Outputs in R0 and R1. #define SHUF(R0, R1, R2) \ "vpshufb %[lut0], %["R0"], %["R1"] \n\t" \ "vpand %["R1"], %[msk0], %["R2"] \n\t" \ "vpand %["R1"], %[msk2], %["R1"] \n\t" \ "vpmulhuw %["R2"], %[msk1], %["R2"] \n\t" \ "vpmullw %["R1"], %[msk3], %["R1"] \n\t" \ "vpor %["R1"], %["R2"], %["R1"] \n\t" // Generate a block of inline assembly that takes R0 and R1 and translates // their contents to the base64 alphabet, using preloaded constants. #define TRAN(R0, R1, R2) \ "vpsubusb %[n51], %["R1"], %["R0"] \n\t" \ "vpcmpgtb %[n25], %["R1"], %["R2"] \n\t" \ "vpsubb %["R2"], %["R0"], %["R0"] \n\t" \ "vpshufb %["R0"], %[lut1], %["R2"] \n\t" \ "vpaddb %["R1"], %["R2"], %["R0"] \n\t" // Generate a block of inline assembly that stores the given register R0 at an // offset set by the given round. #define STOR(R0, ROUND) \ "vmovdqu %["R0"], ("#ROUND" * 32)(%[dst]) \n\t" // Generate a block of inline assembly that generates a single self-contained // encoder round: fetch the data, process it, and store the result. Then update // the source and destination pointers. #define ROUND() \ LOAD("a", 0, -4) \ SHUF("a", "b", "c") \ TRAN("a", "b", "c") \ STOR("a", 0) \ "add $24, %[src] \n\t" \ "add $32, %[dst] \n\t" // Define a macro that initiates a three-way interleaved encoding round by // preloading registers a, b and c from memory. // The register graph shows which registers are in use during each step, and // is a visual aid for choosing registers for that step. Symbol index: // // + indicates that a register is loaded by that step. // | indicates that a register is in use and must not be touched. // - indicates that a register is decommissioned by that step. // x indicates that a register is used as a temporary by that step. // V indicates that a register is an input or output to the macro. // #define ROUND_3_INIT() /* a b c d e f */ \ LOAD("a", 0, -4) /* + */ \ SHUF("a", "d", "e") /* | + x */ \ LOAD("b", 1, -4) /* | + | */ \ TRAN("a", "d", "e") /* | | - x */ \ LOAD("c", 2, -4) /* V V V */ // Define a macro that translates, shuffles and stores the input registers A, B // and C, and preloads registers D, E and F for the next round. // This macro can be arbitrarily daisy-chained by feeding output registers D, E // and F back into the next round as input registers A, B and C. The macro // carefully interleaves memory operations with data operations for optimal // pipelined performance. #define ROUND_3(ROUND, A,B,C,D,E,F) /* A B C D E F */ \ LOAD(D, (ROUND + 3), -4) /* V V V + */ \ SHUF(B, E, F) /* | | | | + x */ \ STOR(A, (ROUND + 0)) /* - | | | | */ \ TRAN(B, E, F) /* | | | - x */ \ LOAD(E, (ROUND + 4), -4) /* | | | + */ \ SHUF(C, A, F) /* + | | | | x */ \ STOR(B, (ROUND + 1)) /* | - | | | */ \ TRAN(C, A, F) /* - | | | x */ \ LOAD(F, (ROUND + 5), -4) /* | | | + */ \ SHUF(D, A, B) /* + x | | | | */ \ STOR(C, (ROUND + 2)) /* | - | | | */ \ TRAN(D, A, B) /* - x V V V */ // Define a macro that terminates a ROUND_3 macro by taking pre-loaded // registers D, E and F, and translating, shuffling and storing them. #define ROUND_3_END(ROUND, A,B,C,D,E,F) /* A B C D E F */ \ SHUF(E, A, B) /* + x V V V */ \ STOR(D, (ROUND + 3)) /* | - | | */ \ TRAN(E, A, B) /* - x | | */ \ SHUF(F, C, D) /* + x | | */ \ STOR(E, (ROUND + 4)) /* | - | */ \ TRAN(F, C, D) /* - x | */ \ STOR(F, (ROUND + 5)) /* - */ // Define a type A round. Inputs are a, b, and c, outputs are d, e, and f. #define ROUND_3_A(ROUND) \ ROUND_3(ROUND, "a", "b", "c", "d", "e", "f") // Define a type B round. Inputs and outputs are swapped with regard to type A. #define ROUND_3_B(ROUND) \ ROUND_3(ROUND, "d", "e", "f", "a", "b", "c") // Terminating macro for a type A round. #define ROUND_3_A_LAST(ROUND) \ ROUND_3_A(ROUND) \ ROUND_3_END(ROUND, "a", "b", "c", "d", "e", "f") // Terminating macro for a type B round. #define ROUND_3_B_LAST(ROUND) \ ROUND_3_B(ROUND) \ ROUND_3_END(ROUND, "d", "e", "f", "a", "b", "c") // Suppress clang's warning that the literal string in the asm statement is // overlong (longer than the ISO-mandated minimum size of 4095 bytes for C99 // compilers). It may be true, but the goal here is not C99 portability. #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Woverlength-strings" static inline void enc_loop_avx2 (const uint8_t **s, size_t *slen, uint8_t **o, size_t *olen) { // For a clearer explanation of the algorithm used by this function, // please refer to the plain (not inline assembly) implementation. This // function follows the same basic logic. if (*slen < 32) { return; } // Process blocks of 24 bytes at a time. Because blocks are loaded 32 // bytes at a time an offset of -4, ensure that there will be at least // 4 remaining bytes after the last round, so that the final read will // not pass beyond the bounds of the input buffer. size_t rounds = (*slen - 4) / 24; *slen -= rounds * 24; // 24 bytes consumed per round *olen += rounds * 32; // 32 bytes produced per round // Pre-decrement the number of rounds to get the number of rounds // *after* the first round, which is handled as a special case. rounds--; // Number of times to go through the 36x loop. size_t loops = rounds / 36; // Number of rounds remaining after the 36x loop. rounds %= 36; // Lookup tables. const __m256i lut0 = _mm256_set_epi8( 10, 11, 9, 10, 7, 8, 6, 7, 4, 5, 3, 4, 1, 2, 0, 1, 14, 15, 13, 14, 11, 12, 10, 11, 8, 9, 7, 8, 5, 6, 4, 5); const __m256i lut1 = _mm256_setr_epi8( 65, 71, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -19, -16, 0, 0, 65, 71, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -19, -16, 0, 0); // Temporary registers. __m256i a, b, c, d, e; // Temporary register f doubles as the shift mask for the first round. __m256i f = _mm256_setr_epi32(0, 0, 1, 2, 3, 4, 5, 6); __asm__ volatile ( // The first loop iteration requires special handling to ensure // that the read, which is normally done at an offset of -4, // does not underflow the buffer. Load the buffer at an offset // of 0 and permute the input to achieve the same effect. LOAD("a", 0, 0) "vpermd %[a], %[f], %[a] \n\t" // Perform the standard shuffling and translation steps. SHUF("a", "b", "c") TRAN("a", "b", "c") // Store the result and increment the source and dest pointers. "vmovdqu %[a], (%[dst]) \n\t" "add $24, %[src] \n\t" "add $32, %[dst] \n\t" // If there are 36 rounds or more, enter a 36x unrolled loop of // interleaved encoding rounds. The rounds interleave memory // operations (load/store) with data operations (table lookups, // etc) to maximize pipeline throughput. " test %[loops], %[loops] \n\t" " jz 18f \n\t" " jmp 36f \n\t" " \n\t" ".balign 64 \n\t" "36: " ROUND_3_INIT() " " ROUND_3_A( 0) " " ROUND_3_B( 3) " " ROUND_3_A( 6) " " ROUND_3_B( 9) " " ROUND_3_A(12) " " ROUND_3_B(15) " " ROUND_3_A(18) " " ROUND_3_B(21) " " ROUND_3_A(24) " " ROUND_3_B(27) " " ROUND_3_A_LAST(30) " add $(24 * 36), %[src] \n\t" " add $(32 * 36), %[dst] \n\t" " dec %[loops] \n\t" " jnz 36b \n\t" // Enter an 18x unrolled loop for rounds of 18 or more. "18: cmp $18, %[rounds] \n\t" " jl 9f \n\t" " " ROUND_3_INIT() " " ROUND_3_A(0) " " ROUND_3_B(3) " " ROUND_3_A(6) " " ROUND_3_B(9) " " ROUND_3_A_LAST(12) " sub $18, %[rounds] \n\t" " add $(24 * 18), %[src] \n\t" " add $(32 * 18), %[dst] \n\t" // Enter a 9x unrolled loop for rounds of 9 or more. "9: cmp $9, %[rounds] \n\t" " jl 6f \n\t" " " ROUND_3_INIT() " " ROUND_3_A(0) " " ROUND_3_B_LAST(3) " sub $9, %[rounds] \n\t" " add $(24 * 9), %[src] \n\t" " add $(32 * 9), %[dst] \n\t" // Enter a 6x unrolled loop for rounds of 6 or more. "6: cmp $6, %[rounds] \n\t" " jl 55f \n\t" " " ROUND_3_INIT() " " ROUND_3_A_LAST(0) " sub $6, %[rounds] \n\t" " add $(24 * 6), %[src] \n\t" " add $(32 * 6), %[dst] \n\t" // Dispatch the remaining rounds 0..5. "55: cmp $3, %[rounds] \n\t" " jg 45f \n\t" " je 3f \n\t" " cmp $1, %[rounds] \n\t" " jg 2f \n\t" " je 1f \n\t" " jmp 0f \n\t" "45: cmp $4, %[rounds] \n\t" " je 4f \n\t" // Block of non-interlaced encoding rounds, which can each // individually be jumped to. Rounds fall through to the next. "5: " ROUND() "4: " ROUND() "3: " ROUND() "2: " ROUND() "1: " ROUND() "0: \n\t" // Outputs (modified). : [rounds] "+r" (rounds), [loops] "+r" (loops), [src] "+r" (*s), [dst] "+r" (*o), [a] "=&x" (a), [b] "=&x" (b), [c] "=&x" (c), [d] "=&x" (d), [e] "=&x" (e), [f] "+x" (f) // Inputs (not modified). : [lut0] "x" (lut0), [lut1] "x" (lut1), [msk0] "x" (_mm256_set1_epi32(0x0FC0FC00)), [msk1] "x" (_mm256_set1_epi32(0x04000040)), [msk2] "x" (_mm256_set1_epi32(0x003F03F0)), [msk3] "x" (_mm256_set1_epi32(0x01000010)), [n51] "x" (_mm256_set1_epi8(51)), [n25] "x" (_mm256_set1_epi8(25)) // Clobbers. : "cc", "memory" ); } #pragma GCC diagnostic pop
2301_81045437/base64
lib/arch/avx2/enc_loop_asm.c
C
bsd
10,453
static BASE64_FORCE_INLINE __m256i enc_reshuffle (const __m256i input) { // Translation of the SSSE3 reshuffling algorithm to AVX2. This one // works with shifted (4 bytes) input in order to be able to work // efficiently in the two 128-bit lanes. // Input, bytes MSB to LSB: // 0 0 0 0 x w v u t s r q p o n m // l k j i h g f e d c b a 0 0 0 0 const __m256i in = _mm256_shuffle_epi8(input, _mm256_set_epi8( 10, 11, 9, 10, 7, 8, 6, 7, 4, 5, 3, 4, 1, 2, 0, 1, 14, 15, 13, 14, 11, 12, 10, 11, 8, 9, 7, 8, 5, 6, 4, 5)); // in, bytes MSB to LSB: // w x v w // t u s t // q r p q // n o m n // k l j k // h i g h // e f d e // b c a b const __m256i t0 = _mm256_and_si256(in, _mm256_set1_epi32(0x0FC0FC00)); // bits, upper case are most significant bits, lower case are least // significant bits. // 0000wwww XX000000 VVVVVV00 00000000 // 0000tttt UU000000 SSSSSS00 00000000 // 0000qqqq RR000000 PPPPPP00 00000000 // 0000nnnn OO000000 MMMMMM00 00000000 // 0000kkkk LL000000 JJJJJJ00 00000000 // 0000hhhh II000000 GGGGGG00 00000000 // 0000eeee FF000000 DDDDDD00 00000000 // 0000bbbb CC000000 AAAAAA00 00000000 const __m256i t1 = _mm256_mulhi_epu16(t0, _mm256_set1_epi32(0x04000040)); // 00000000 00wwwwXX 00000000 00VVVVVV // 00000000 00ttttUU 00000000 00SSSSSS // 00000000 00qqqqRR 00000000 00PPPPPP // 00000000 00nnnnOO 00000000 00MMMMMM // 00000000 00kkkkLL 00000000 00JJJJJJ // 00000000 00hhhhII 00000000 00GGGGGG // 00000000 00eeeeFF 00000000 00DDDDDD // 00000000 00bbbbCC 00000000 00AAAAAA const __m256i t2 = _mm256_and_si256(in, _mm256_set1_epi32(0x003F03F0)); // 00000000 00xxxxxx 000000vv WWWW0000 // 00000000 00uuuuuu 000000ss TTTT0000 // 00000000 00rrrrrr 000000pp QQQQ0000 // 00000000 00oooooo 000000mm NNNN0000 // 00000000 00llllll 000000jj KKKK0000 // 00000000 00iiiiii 000000gg HHHH0000 // 00000000 00ffffff 000000dd EEEE0000 // 00000000 00cccccc 000000aa BBBB0000 const __m256i t3 = _mm256_mullo_epi16(t2, _mm256_set1_epi32(0x01000010)); // 00xxxxxx 00000000 00vvWWWW 00000000 // 00uuuuuu 00000000 00ssTTTT 00000000 // 00rrrrrr 00000000 00ppQQQQ 00000000 // 00oooooo 00000000 00mmNNNN 00000000 // 00llllll 00000000 00jjKKKK 00000000 // 00iiiiii 00000000 00ggHHHH 00000000 // 00ffffff 00000000 00ddEEEE 00000000 // 00cccccc 00000000 00aaBBBB 00000000 return _mm256_or_si256(t1, t3); // 00xxxxxx 00wwwwXX 00vvWWWW 00VVVVVV // 00uuuuuu 00ttttUU 00ssTTTT 00SSSSSS // 00rrrrrr 00qqqqRR 00ppQQQQ 00PPPPPP // 00oooooo 00nnnnOO 00mmNNNN 00MMMMMM // 00llllll 00kkkkLL 00jjKKKK 00JJJJJJ // 00iiiiii 00hhhhII 00ggHHHH 00GGGGGG // 00ffffff 00eeeeFF 00ddEEEE 00DDDDDD // 00cccccc 00bbbbCC 00aaBBBB 00AAAAAA }
2301_81045437/base64
lib/arch/avx2/enc_reshuffle.c
C
bsd
2,714
static BASE64_FORCE_INLINE __m256i enc_translate (const __m256i in) { // A lookup table containing the absolute offsets for all ranges: const __m256i lut = _mm256_setr_epi8( 65, 71, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -19, -16, 0, 0, 65, 71, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -19, -16, 0, 0); // Translate values 0..63 to the Base64 alphabet. There are five sets: // # From To Abs Index Characters // 0 [0..25] [65..90] +65 0 ABCDEFGHIJKLMNOPQRSTUVWXYZ // 1 [26..51] [97..122] +71 1 abcdefghijklmnopqrstuvwxyz // 2 [52..61] [48..57] -4 [2..11] 0123456789 // 3 [62] [43] -19 12 + // 4 [63] [47] -16 13 / // Create LUT indices from the input. The index for range #0 is right, // others are 1 less than expected: __m256i indices = _mm256_subs_epu8(in, _mm256_set1_epi8(51)); // mask is 0xFF (-1) for range #[1..4] and 0x00 for range #0: const __m256i mask = _mm256_cmpgt_epi8(in, _mm256_set1_epi8(25)); // Subtract -1, so add 1 to indices for range #[1..4]. All indices are // now correct: indices = _mm256_sub_epi8(indices, mask); // Add offsets to input values: return _mm256_add_epi8(in, _mm256_shuffle_epi8(lut, indices)); }
2301_81045437/base64
lib/arch/avx2/enc_translate.c
C
bsd
1,251
#include <stdint.h> #include <stddef.h> #include <stdlib.h> #include "../../../include/libbase64.h" #include "../../tables/tables.h" #include "../../codecs.h" #include "config.h" #include "../../env.h" #if HAVE_AVX512 #include <immintrin.h> #include "../avx2/dec_reshuffle.c" #include "../avx2/dec_loop.c" #include "enc_reshuffle_translate.c" #include "enc_loop.c" #endif // HAVE_AVX512 void base64_stream_encode_avx512 BASE64_ENC_PARAMS { #if HAVE_AVX512 #include "../generic/enc_head.c" enc_loop_avx512(&s, &slen, &o, &olen); #include "../generic/enc_tail.c" #else base64_enc_stub(state, src, srclen, out, outlen); #endif } // Reuse AVX2 decoding. Not supporting AVX512 at present int base64_stream_decode_avx512 BASE64_DEC_PARAMS { #if HAVE_AVX512 #include "../generic/dec_head.c" dec_loop_avx2(&s, &slen, &o, &olen); #include "../generic/dec_tail.c" #else return base64_dec_stub(state, src, srclen, out, outlen); #endif }
2301_81045437/base64
lib/arch/avx512/codec.c
C
bsd
940
static BASE64_FORCE_INLINE void enc_loop_avx512_inner (const uint8_t **s, uint8_t **o) { // Load input. __m512i src = _mm512_loadu_si512((__m512i *) *s); // Reshuffle, translate, store. src = enc_reshuffle_translate(src); _mm512_storeu_si512((__m512i *) *o, src); *s += 48; *o += 64; } static inline void enc_loop_avx512 (const uint8_t **s, size_t *slen, uint8_t **o, size_t *olen) { if (*slen < 64) { return; } // Process blocks of 48 bytes at a time. Because blocks are loaded 64 // bytes at a time, ensure that there will be at least 24 remaining // bytes after the last round, so that the final read will not pass // beyond the bounds of the input buffer. size_t rounds = (*slen - 24) / 48; *slen -= rounds * 48; // 48 bytes consumed per round *olen += rounds * 64; // 64 bytes produced per round while (rounds > 0) { if (rounds >= 8) { enc_loop_avx512_inner(s, o); enc_loop_avx512_inner(s, o); enc_loop_avx512_inner(s, o); enc_loop_avx512_inner(s, o); enc_loop_avx512_inner(s, o); enc_loop_avx512_inner(s, o); enc_loop_avx512_inner(s, o); enc_loop_avx512_inner(s, o); rounds -= 8; continue; } if (rounds >= 4) { enc_loop_avx512_inner(s, o); enc_loop_avx512_inner(s, o); enc_loop_avx512_inner(s, o); enc_loop_avx512_inner(s, o); rounds -= 4; continue; } if (rounds >= 2) { enc_loop_avx512_inner(s, o); enc_loop_avx512_inner(s, o); rounds -= 2; continue; } enc_loop_avx512_inner(s, o); break; } }
2301_81045437/base64
lib/arch/avx512/enc_loop.c
C
bsd
1,506
// AVX512 algorithm is based on permutevar and multishift. The code is based on // https://github.com/WojciechMula/base64simd which is under BSD-2 license. static BASE64_FORCE_INLINE __m512i enc_reshuffle_translate (const __m512i input) { // 32-bit input // [ 0 0 0 0 0 0 0 0|c1 c0 d5 d4 d3 d2 d1 d0| // b3 b2 b1 b0 c5 c4 c3 c2|a5 a4 a3 a2 a1 a0 b5 b4] // output order [1, 2, 0, 1] // [b3 b2 b1 b0 c5 c4 c3 c2|c1 c0 d5 d4 d3 d2 d1 d0| // a5 a4 a3 a2 a1 a0 b5 b4|b3 b2 b1 b0 c3 c2 c1 c0] const __m512i shuffle_input = _mm512_setr_epi32(0x01020001, 0x04050304, 0x07080607, 0x0a0b090a, 0x0d0e0c0d, 0x10110f10, 0x13141213, 0x16171516, 0x191a1819, 0x1c1d1b1c, 0x1f201e1f, 0x22232122, 0x25262425, 0x28292728, 0x2b2c2a2b, 0x2e2f2d2e); // Reorder bytes // [b3 b2 b1 b0 c5 c4 c3 c2|c1 c0 d5 d4 d3 d2 d1 d0| // a5 a4 a3 a2 a1 a0 b5 b4|b3 b2 b1 b0 c3 c2 c1 c0] const __m512i in = _mm512_permutexvar_epi8(shuffle_input, input); // After multishift a single 32-bit lane has following layout // [c1 c0 d5 d4 d3 d2 d1 d0|b1 b0 c5 c4 c3 c2 c1 c0| // a1 a0 b5 b4 b3 b2 b1 b0|d1 d0 a5 a4 a3 a2 a1 a0] // (a = [10:17], b = [4:11], c = [22:27], d = [16:21]) // 48, 54, 36, 42, 16, 22, 4, 10 const __m512i shifts = _mm512_set1_epi64(0x3036242a1016040alu); __m512i shuffled_in = _mm512_multishift_epi64_epi8(shifts, in); // Translate immediatedly after reshuffled. const __m512i lookup = _mm512_loadu_si512(base64_table_enc_6bit); // Translation 6-bit values to ASCII. return _mm512_permutexvar_epi8(shuffled_in, lookup); }
2301_81045437/base64
lib/arch/avx512/enc_reshuffle_translate.c
C
bsd
2,278
static BASE64_FORCE_INLINE int dec_loop_generic_32_inner (const uint8_t **s, uint8_t **o, size_t *rounds) { const uint32_t str = base64_table_dec_32bit_d0[(*s)[0]] | base64_table_dec_32bit_d1[(*s)[1]] | base64_table_dec_32bit_d2[(*s)[2]] | base64_table_dec_32bit_d3[(*s)[3]]; #if BASE64_LITTLE_ENDIAN // LUTs for little-endian set MSB in case of invalid character: if (str & UINT32_C(0x80000000)) { return 0; } #else // LUTs for big-endian set LSB in case of invalid character: if (str & UINT32_C(1)) { return 0; } #endif // Store the output: memcpy(*o, &str, sizeof (str)); *s += 4; *o += 3; *rounds -= 1; return 1; } static inline void dec_loop_generic_32 (const uint8_t **s, size_t *slen, uint8_t **o, size_t *olen) { if (*slen < 8) { return; } // Process blocks of 4 bytes per round. Because one extra zero byte is // written after the output, ensure that there will be at least 4 bytes // of input data left to cover the gap. (Two data bytes and up to two // end-of-string markers.) size_t rounds = (*slen - 4) / 4; *slen -= rounds * 4; // 4 bytes consumed per round *olen += rounds * 3; // 3 bytes produced per round do { if (rounds >= 8) { if (dec_loop_generic_32_inner(s, o, &rounds) && dec_loop_generic_32_inner(s, o, &rounds) && dec_loop_generic_32_inner(s, o, &rounds) && dec_loop_generic_32_inner(s, o, &rounds) && dec_loop_generic_32_inner(s, o, &rounds) && dec_loop_generic_32_inner(s, o, &rounds) && dec_loop_generic_32_inner(s, o, &rounds) && dec_loop_generic_32_inner(s, o, &rounds)) { continue; } break; } if (rounds >= 4) { if (dec_loop_generic_32_inner(s, o, &rounds) && dec_loop_generic_32_inner(s, o, &rounds) && dec_loop_generic_32_inner(s, o, &rounds) && dec_loop_generic_32_inner(s, o, &rounds)) { continue; } break; } if (rounds >= 2) { if (dec_loop_generic_32_inner(s, o, &rounds) && dec_loop_generic_32_inner(s, o, &rounds)) { continue; } break; } dec_loop_generic_32_inner(s, o, &rounds); break; } while (rounds > 0); // Adjust for any rounds that were skipped: *slen += rounds * 4; *olen -= rounds * 3; }
2301_81045437/base64
lib/arch/generic/32/dec_loop.c
C
bsd
2,218
static BASE64_FORCE_INLINE void enc_loop_generic_32_inner (const uint8_t **s, uint8_t **o) { uint32_t src; // Load input: memcpy(&src, *s, sizeof (src)); // Reorder to 32-bit big-endian, if not already in that format. The // workset must be in big-endian, otherwise the shifted bits do not // carry over properly among adjacent bytes: src = BASE64_HTOBE32(src); // Two indices for the 12-bit lookup table: const size_t index0 = (src >> 20) & 0xFFFU; const size_t index1 = (src >> 8) & 0xFFFU; // Table lookup and store: memcpy(*o + 0, base64_table_enc_12bit + index0, 2); memcpy(*o + 2, base64_table_enc_12bit + index1, 2); *s += 3; *o += 4; } static inline void enc_loop_generic_32 (const uint8_t **s, size_t *slen, uint8_t **o, size_t *olen) { if (*slen < 4) { return; } // Process blocks of 3 bytes at a time. Because blocks are loaded 4 // bytes at a time, ensure that there will be at least one remaining // byte after the last round, so that the final read will not pass // beyond the bounds of the input buffer: size_t rounds = (*slen - 1) / 3; *slen -= rounds * 3; // 3 bytes consumed per round *olen += rounds * 4; // 4 bytes produced per round do { if (rounds >= 8) { enc_loop_generic_32_inner(s, o); enc_loop_generic_32_inner(s, o); enc_loop_generic_32_inner(s, o); enc_loop_generic_32_inner(s, o); enc_loop_generic_32_inner(s, o); enc_loop_generic_32_inner(s, o); enc_loop_generic_32_inner(s, o); enc_loop_generic_32_inner(s, o); rounds -= 8; continue; } if (rounds >= 4) { enc_loop_generic_32_inner(s, o); enc_loop_generic_32_inner(s, o); enc_loop_generic_32_inner(s, o); enc_loop_generic_32_inner(s, o); rounds -= 4; continue; } if (rounds >= 2) { enc_loop_generic_32_inner(s, o); enc_loop_generic_32_inner(s, o); rounds -= 2; continue; } enc_loop_generic_32_inner(s, o); break; } while (rounds > 0); }
2301_81045437/base64
lib/arch/generic/32/enc_loop.c
C
bsd
1,932
static BASE64_FORCE_INLINE void enc_loop_generic_64_inner (const uint8_t **s, uint8_t **o) { uint64_t src; // Load input: memcpy(&src, *s, sizeof (src)); // Reorder to 64-bit big-endian, if not already in that format. The // workset must be in big-endian, otherwise the shifted bits do not // carry over properly among adjacent bytes: src = BASE64_HTOBE64(src); // Four indices for the 12-bit lookup table: const size_t index0 = (src >> 52) & 0xFFFU; const size_t index1 = (src >> 40) & 0xFFFU; const size_t index2 = (src >> 28) & 0xFFFU; const size_t index3 = (src >> 16) & 0xFFFU; // Table lookup and store: memcpy(*o + 0, base64_table_enc_12bit + index0, 2); memcpy(*o + 2, base64_table_enc_12bit + index1, 2); memcpy(*o + 4, base64_table_enc_12bit + index2, 2); memcpy(*o + 6, base64_table_enc_12bit + index3, 2); *s += 6; *o += 8; } static inline void enc_loop_generic_64 (const uint8_t **s, size_t *slen, uint8_t **o, size_t *olen) { if (*slen < 8) { return; } // Process blocks of 6 bytes at a time. Because blocks are loaded 8 // bytes at a time, ensure that there will be at least 2 remaining // bytes after the last round, so that the final read will not pass // beyond the bounds of the input buffer: size_t rounds = (*slen - 2) / 6; *slen -= rounds * 6; // 6 bytes consumed per round *olen += rounds * 8; // 8 bytes produced per round do { if (rounds >= 8) { enc_loop_generic_64_inner(s, o); enc_loop_generic_64_inner(s, o); enc_loop_generic_64_inner(s, o); enc_loop_generic_64_inner(s, o); enc_loop_generic_64_inner(s, o); enc_loop_generic_64_inner(s, o); enc_loop_generic_64_inner(s, o); enc_loop_generic_64_inner(s, o); rounds -= 8; continue; } if (rounds >= 4) { enc_loop_generic_64_inner(s, o); enc_loop_generic_64_inner(s, o); enc_loop_generic_64_inner(s, o); enc_loop_generic_64_inner(s, o); rounds -= 4; continue; } if (rounds >= 2) { enc_loop_generic_64_inner(s, o); enc_loop_generic_64_inner(s, o); rounds -= 2; continue; } enc_loop_generic_64_inner(s, o); break; } while (rounds > 0); }
2301_81045437/base64
lib/arch/generic/64/enc_loop.c
C
bsd
2,128
#include <stdint.h> #include <stddef.h> #include <string.h> #include "../../../include/libbase64.h" #include "../../tables/tables.h" #include "../../codecs.h" #include "config.h" #include "../../env.h" #if BASE64_WORDSIZE == 32 # include "32/enc_loop.c" #elif BASE64_WORDSIZE == 64 # include "64/enc_loop.c" #endif #if BASE64_WORDSIZE >= 32 # include "32/dec_loop.c" #endif void base64_stream_encode_plain BASE64_ENC_PARAMS { #include "enc_head.c" #if BASE64_WORDSIZE == 32 enc_loop_generic_32(&s, &slen, &o, &olen); #elif BASE64_WORDSIZE == 64 enc_loop_generic_64(&s, &slen, &o, &olen); #endif #include "enc_tail.c" } int base64_stream_decode_plain BASE64_DEC_PARAMS { #include "dec_head.c" #if BASE64_WORDSIZE >= 32 dec_loop_generic_32(&s, &slen, &o, &olen); #endif #include "dec_tail.c" }
2301_81045437/base64
lib/arch/generic/codec.c
C
bsd
807
int ret = 0; const uint8_t *s = (const uint8_t *) src; uint8_t *o = (uint8_t *) out; uint8_t q; // Use local temporaries to avoid cache thrashing: size_t olen = 0; size_t slen = srclen; struct base64_state st; st.eof = state->eof; st.bytes = state->bytes; st.carry = state->carry; // If we previously saw an EOF or an invalid character, bail out: if (st.eof) { *outlen = 0; ret = 0; // If there was a trailing '=' to check, check it: if (slen && (st.eof == BASE64_AEOF)) { state->bytes = 0; state->eof = BASE64_EOF; ret = ((base64_table_dec_8bit[*s++] == 254) && (slen == 1)) ? 1 : 0; } return ret; } // Turn four 6-bit numbers into three bytes: // out[0] = 11111122 // out[1] = 22223333 // out[2] = 33444444 // Duff's device again: switch (st.bytes) { for (;;) { case 0:
2301_81045437/base64
lib/arch/generic/dec_head.c
C
bsd
791
if (slen-- == 0) { ret = 1; break; } if ((q = base64_table_dec_8bit[*s++]) >= 254) { st.eof = BASE64_EOF; // Treat character '=' as invalid for byte 0: break; } st.carry = q << 2; st.bytes++; // Deliberate fallthrough: BASE64_FALLTHROUGH case 1: if (slen-- == 0) { ret = 1; break; } if ((q = base64_table_dec_8bit[*s++]) >= 254) { st.eof = BASE64_EOF; // Treat character '=' as invalid for byte 1: break; } *o++ = st.carry | (q >> 4); st.carry = q << 4; st.bytes++; olen++; // Deliberate fallthrough: BASE64_FALLTHROUGH case 2: if (slen-- == 0) { ret = 1; break; } if ((q = base64_table_dec_8bit[*s++]) >= 254) { st.bytes++; // When q == 254, the input char is '='. // Check if next byte is also '=': if (q == 254) { if (slen-- != 0) { st.bytes = 0; // EOF: st.eof = BASE64_EOF; q = base64_table_dec_8bit[*s++]; ret = ((q == 254) && (slen == 0)) ? 1 : 0; break; } else { // Almost EOF st.eof = BASE64_AEOF; ret = 1; break; } } // If we get here, there was an error: break; } *o++ = st.carry | (q >> 2); st.carry = q << 6; st.bytes++; olen++; // Deliberate fallthrough: BASE64_FALLTHROUGH case 3: if (slen-- == 0) { ret = 1; break; } if ((q = base64_table_dec_8bit[*s++]) >= 254) { st.bytes = 0; st.eof = BASE64_EOF; // When q == 254, the input char is '='. Return 1 and EOF. // When q == 255, the input char is invalid. Return 0 and EOF. ret = ((q == 254) && (slen == 0)) ? 1 : 0; break; } *o++ = st.carry | q; st.carry = 0; st.bytes = 0; olen++; } } state->eof = st.eof; state->bytes = st.bytes; state->carry = st.carry; *outlen = olen; return ret;
2301_81045437/base64
lib/arch/generic/dec_tail.c
C
bsd
1,774
// Assume that *out is large enough to contain the output. // Theoretically it should be 4/3 the length of src. const uint8_t *s = (const uint8_t *) src; uint8_t *o = (uint8_t *) out; // Use local temporaries to avoid cache thrashing: size_t olen = 0; size_t slen = srclen; struct base64_state st; st.bytes = state->bytes; st.carry = state->carry; // Turn three bytes into four 6-bit numbers: // in[0] = 00111111 // in[1] = 00112222 // in[2] = 00222233 // in[3] = 00333333 // Duff's device, a for() loop inside a switch() statement. Legal! switch (st.bytes) { for (;;) { case 0:
2301_81045437/base64
lib/arch/generic/enc_head.c
C
bsd
585
if (slen-- == 0) { break; } *o++ = base64_table_enc_6bit[*s >> 2]; st.carry = (*s++ << 4) & 0x30; st.bytes++; olen += 1; // Deliberate fallthrough: BASE64_FALLTHROUGH case 1: if (slen-- == 0) { break; } *o++ = base64_table_enc_6bit[st.carry | (*s >> 4)]; st.carry = (*s++ << 2) & 0x3C; st.bytes++; olen += 1; // Deliberate fallthrough: BASE64_FALLTHROUGH case 2: if (slen-- == 0) { break; } *o++ = base64_table_enc_6bit[st.carry | (*s >> 6)]; *o++ = base64_table_enc_6bit[*s++ & 0x3F]; st.bytes = 0; olen += 2; } } state->bytes = st.bytes; state->carry = st.carry; *outlen = olen;
2301_81045437/base64
lib/arch/generic/enc_tail.c
C
bsd
637
#include <stdint.h> #include <stddef.h> #include <string.h> #include "../../../include/libbase64.h" #include "../../tables/tables.h" #include "../../codecs.h" #include "config.h" #include "../../env.h" #ifdef __arm__ # if (defined(__ARM_NEON__) || defined(__ARM_NEON)) && HAVE_NEON32 # define BASE64_USE_NEON32 # endif #endif #ifdef BASE64_USE_NEON32 #include <arm_neon.h> // Only enable inline assembly on supported compilers. #if defined(__GNUC__) || defined(__clang__) #define BASE64_NEON32_USE_ASM #endif static BASE64_FORCE_INLINE uint8x16_t vqtbl1q_u8 (const uint8x16_t lut, const uint8x16_t indices) { // NEON32 only supports 64-bit wide lookups in 128-bit tables. Emulate // the NEON64 `vqtbl1q_u8` intrinsic to do 128-bit wide lookups. uint8x8x2_t lut2; uint8x8x2_t result; lut2.val[0] = vget_low_u8(lut); lut2.val[1] = vget_high_u8(lut); result.val[0] = vtbl2_u8(lut2, vget_low_u8(indices)); result.val[1] = vtbl2_u8(lut2, vget_high_u8(indices)); return vcombine_u8(result.val[0], result.val[1]); } #include "../generic/32/dec_loop.c" #include "../generic/32/enc_loop.c" #include "dec_loop.c" #include "enc_reshuffle.c" #include "enc_translate.c" #include "enc_loop.c" #endif // BASE64_USE_NEON32 // Stride size is so large on these NEON 32-bit functions // (48 bytes encode, 32 bytes decode) that we inline the // uint32 codec to stay performant on smaller inputs. void base64_stream_encode_neon32 BASE64_ENC_PARAMS { #ifdef BASE64_USE_NEON32 #include "../generic/enc_head.c" enc_loop_neon32(&s, &slen, &o, &olen); enc_loop_generic_32(&s, &slen, &o, &olen); #include "../generic/enc_tail.c" #else base64_enc_stub(state, src, srclen, out, outlen); #endif } int base64_stream_decode_neon32 BASE64_DEC_PARAMS { #ifdef BASE64_USE_NEON32 #include "../generic/dec_head.c" dec_loop_neon32(&s, &slen, &o, &olen); dec_loop_generic_32(&s, &slen, &o, &olen); #include "../generic/dec_tail.c" #else return base64_dec_stub(state, src, srclen, out, outlen); #endif }
2301_81045437/base64
lib/arch/neon32/codec.c
C
bsd
2,001
static BASE64_FORCE_INLINE int is_nonzero (const uint8x16_t v) { uint64_t u64; const uint64x2_t v64 = vreinterpretq_u64_u8(v); const uint32x2_t v32 = vqmovn_u64(v64); vst1_u64(&u64, vreinterpret_u64_u32(v32)); return u64 != 0; } static BASE64_FORCE_INLINE uint8x16_t delta_lookup (const uint8x16_t v) { const uint8x8_t lut = { 0, 16, 19, 4, (uint8_t) -65, (uint8_t) -65, (uint8_t) -71, (uint8_t) -71, }; return vcombine_u8( vtbl1_u8(lut, vget_low_u8(v)), vtbl1_u8(lut, vget_high_u8(v))); } static BASE64_FORCE_INLINE uint8x16_t dec_loop_neon32_lane (uint8x16_t *lane) { // See the SSSE3 decoder for an explanation of the algorithm. const uint8x16_t lut_lo = { 0x15, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x13, 0x1A, 0x1B, 0x1B, 0x1B, 0x1A }; const uint8x16_t lut_hi = { 0x10, 0x10, 0x01, 0x02, 0x04, 0x08, 0x04, 0x08, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10 }; const uint8x16_t mask_0F = vdupq_n_u8(0x0F); const uint8x16_t mask_2F = vdupq_n_u8(0x2F); const uint8x16_t hi_nibbles = vshrq_n_u8(*lane, 4); const uint8x16_t lo_nibbles = vandq_u8(*lane, mask_0F); const uint8x16_t eq_2F = vceqq_u8(*lane, mask_2F); const uint8x16_t hi = vqtbl1q_u8(lut_hi, hi_nibbles); const uint8x16_t lo = vqtbl1q_u8(lut_lo, lo_nibbles); // Now simply add the delta values to the input: *lane = vaddq_u8(*lane, delta_lookup(vaddq_u8(eq_2F, hi_nibbles))); // Return the validity mask: return vandq_u8(lo, hi); } static inline void dec_loop_neon32 (const uint8_t **s, size_t *slen, uint8_t **o, size_t *olen) { if (*slen < 64) { return; } // Process blocks of 64 bytes per round. Unlike the SSE codecs, no // extra trailing zero bytes are written, so it is not necessary to // reserve extra input bytes: size_t rounds = *slen / 64; *slen -= rounds * 64; // 64 bytes consumed per round *olen += rounds * 48; // 48 bytes produced per round do { uint8x16x3_t dec; // Load 64 bytes and deinterleave: uint8x16x4_t str = vld4q_u8(*s); // Decode each lane, collect a mask of invalid inputs: const uint8x16_t classified = dec_loop_neon32_lane(&str.val[0]) | dec_loop_neon32_lane(&str.val[1]) | dec_loop_neon32_lane(&str.val[2]) | dec_loop_neon32_lane(&str.val[3]); // Check for invalid input: if any of the delta values are // zero, fall back on bytewise code to do error checking and // reporting: if (is_nonzero(classified)) { break; } // Compress four bytes into three: dec.val[0] = vorrq_u8(vshlq_n_u8(str.val[0], 2), vshrq_n_u8(str.val[1], 4)); dec.val[1] = vorrq_u8(vshlq_n_u8(str.val[1], 4), vshrq_n_u8(str.val[2], 2)); dec.val[2] = vorrq_u8(vshlq_n_u8(str.val[2], 6), str.val[3]); // Interleave and store decoded result: vst3q_u8(*o, dec); *s += 64; *o += 48; } while (--rounds > 0); // Adjust for any rounds that were skipped: *slen += rounds * 64; *olen -= rounds * 48; }
2301_81045437/base64
lib/arch/neon32/dec_loop.c
C
bsd
2,906
#ifdef BASE64_NEON32_USE_ASM static BASE64_FORCE_INLINE void enc_loop_neon32_inner_asm (const uint8_t **s, uint8_t **o) { // This function duplicates the functionality of enc_loop_neon32_inner, // but entirely with inline assembly. This gives a significant speedup // over using NEON intrinsics, which do not always generate very good // code. The logic of the assembly is directly lifted from the // intrinsics version, so it can be used as a guide to this code. // Temporary registers, used as scratch space. uint8x16_t tmp0, tmp1, tmp2, tmp3; uint8x16_t mask0, mask1, mask2, mask3; // A lookup table containing the absolute offsets for all ranges. const uint8x16_t lut = { 65U, 71U, 252U, 252U, 252U, 252U, 252U, 252U, 252U, 252U, 252U, 252U, 237U, 240U, 0U, 0U }; // Numeric constants. const uint8x16_t n51 = vdupq_n_u8(51); const uint8x16_t n25 = vdupq_n_u8(25); const uint8x16_t n63 = vdupq_n_u8(63); __asm__ ( // Load 48 bytes and deinterleave. The bytes are loaded to // hard-coded registers q12, q13 and q14, to ensure that they // are contiguous. Increment the source pointer. "vld3.8 {d24, d26, d28}, [%[src]]! \n\t" "vld3.8 {d25, d27, d29}, [%[src]]! \n\t" // Reshuffle the bytes using temporaries. "vshr.u8 %q[t0], q12, #2 \n\t" "vshr.u8 %q[t1], q13, #4 \n\t" "vshr.u8 %q[t2], q14, #6 \n\t" "vsli.8 %q[t1], q12, #4 \n\t" "vsli.8 %q[t2], q13, #2 \n\t" "vand.u8 %q[t1], %q[t1], %q[n63] \n\t" "vand.u8 %q[t2], %q[t2], %q[n63] \n\t" "vand.u8 %q[t3], q14, %q[n63] \n\t" // t0..t3 are the reshuffled inputs. Create LUT indices. "vqsub.u8 q12, %q[t0], %q[n51] \n\t" "vqsub.u8 q13, %q[t1], %q[n51] \n\t" "vqsub.u8 q14, %q[t2], %q[n51] \n\t" "vqsub.u8 q15, %q[t3], %q[n51] \n\t" // Create the mask for range #0. "vcgt.u8 %q[m0], %q[t0], %q[n25] \n\t" "vcgt.u8 %q[m1], %q[t1], %q[n25] \n\t" "vcgt.u8 %q[m2], %q[t2], %q[n25] \n\t" "vcgt.u8 %q[m3], %q[t3], %q[n25] \n\t" // Subtract -1 to correct the LUT indices. "vsub.u8 q12, %q[m0] \n\t" "vsub.u8 q13, %q[m1] \n\t" "vsub.u8 q14, %q[m2] \n\t" "vsub.u8 q15, %q[m3] \n\t" // Lookup the delta values. "vtbl.u8 d24, {%q[lut]}, d24 \n\t" "vtbl.u8 d25, {%q[lut]}, d25 \n\t" "vtbl.u8 d26, {%q[lut]}, d26 \n\t" "vtbl.u8 d27, {%q[lut]}, d27 \n\t" "vtbl.u8 d28, {%q[lut]}, d28 \n\t" "vtbl.u8 d29, {%q[lut]}, d29 \n\t" "vtbl.u8 d30, {%q[lut]}, d30 \n\t" "vtbl.u8 d31, {%q[lut]}, d31 \n\t" // Add the delta values. "vadd.u8 q12, %q[t0] \n\t" "vadd.u8 q13, %q[t1] \n\t" "vadd.u8 q14, %q[t2] \n\t" "vadd.u8 q15, %q[t3] \n\t" // Store 64 bytes and interleave. Increment the dest pointer. "vst4.8 {d24, d26, d28, d30}, [%[dst]]! \n\t" "vst4.8 {d25, d27, d29, d31}, [%[dst]]! \n\t" // Outputs (modified). : [src] "+r" (*s), [dst] "+r" (*o), [t0] "=&w" (tmp0), [t1] "=&w" (tmp1), [t2] "=&w" (tmp2), [t3] "=&w" (tmp3), [m0] "=&w" (mask0), [m1] "=&w" (mask1), [m2] "=&w" (mask2), [m3] "=&w" (mask3) // Inputs (not modified). : [lut] "w" (lut), [n25] "w" (n25), [n51] "w" (n51), [n63] "w" (n63) // Clobbers. : "d24", "d25", "d26", "d27", "d28", "d29", "d30", "d31", "cc", "memory" ); } #endif static BASE64_FORCE_INLINE void enc_loop_neon32_inner (const uint8_t **s, uint8_t **o) { #ifdef BASE64_NEON32_USE_ASM enc_loop_neon32_inner_asm(s, o); #else // Load 48 bytes and deinterleave: uint8x16x3_t src = vld3q_u8(*s); // Reshuffle: uint8x16x4_t out = enc_reshuffle(src); // Translate reshuffled bytes to the Base64 alphabet: out = enc_translate(out); // Interleave and store output: vst4q_u8(*o, out); *s += 48; *o += 64; #endif } static inline void enc_loop_neon32 (const uint8_t **s, size_t *slen, uint8_t **o, size_t *olen) { size_t rounds = *slen / 48; *slen -= rounds * 48; // 48 bytes consumed per round *olen += rounds * 64; // 64 bytes produced per round while (rounds > 0) { if (rounds >= 8) { enc_loop_neon32_inner(s, o); enc_loop_neon32_inner(s, o); enc_loop_neon32_inner(s, o); enc_loop_neon32_inner(s, o); enc_loop_neon32_inner(s, o); enc_loop_neon32_inner(s, o); enc_loop_neon32_inner(s, o); enc_loop_neon32_inner(s, o); rounds -= 8; continue; } if (rounds >= 4) { enc_loop_neon32_inner(s, o); enc_loop_neon32_inner(s, o); enc_loop_neon32_inner(s, o); enc_loop_neon32_inner(s, o); rounds -= 4; continue; } if (rounds >= 2) { enc_loop_neon32_inner(s, o); enc_loop_neon32_inner(s, o); rounds -= 2; continue; } enc_loop_neon32_inner(s, o); break; } }
2301_81045437/base64
lib/arch/neon32/enc_loop.c
C
bsd
4,655
static BASE64_FORCE_INLINE uint8x16x4_t enc_reshuffle (uint8x16x3_t in) { uint8x16x4_t out; // Input: // in[0] = a7 a6 a5 a4 a3 a2 a1 a0 // in[1] = b7 b6 b5 b4 b3 b2 b1 b0 // in[2] = c7 c6 c5 c4 c3 c2 c1 c0 // Output: // out[0] = 00 00 a7 a6 a5 a4 a3 a2 // out[1] = 00 00 a1 a0 b7 b6 b5 b4 // out[2] = 00 00 b3 b2 b1 b0 c7 c6 // out[3] = 00 00 c5 c4 c3 c2 c1 c0 // Move the input bits to where they need to be in the outputs. Except // for the first output, the high two bits are not cleared. out.val[0] = vshrq_n_u8(in.val[0], 2); out.val[1] = vshrq_n_u8(in.val[1], 4); out.val[2] = vshrq_n_u8(in.val[2], 6); out.val[1] = vsliq_n_u8(out.val[1], in.val[0], 4); out.val[2] = vsliq_n_u8(out.val[2], in.val[1], 2); // Clear the high two bits in the second, third and fourth output. out.val[1] = vandq_u8(out.val[1], vdupq_n_u8(0x3F)); out.val[2] = vandq_u8(out.val[2], vdupq_n_u8(0x3F)); out.val[3] = vandq_u8(in.val[2], vdupq_n_u8(0x3F)); return out; }
2301_81045437/base64
lib/arch/neon32/enc_reshuffle.c
C
bsd
982
static BASE64_FORCE_INLINE uint8x16x4_t enc_translate (const uint8x16x4_t in) { // A lookup table containing the absolute offsets for all ranges: const uint8x16_t lut = { 65U, 71U, 252U, 252U, 252U, 252U, 252U, 252U, 252U, 252U, 252U, 252U, 237U, 240U, 0U, 0U }; const uint8x16_t offset = vdupq_n_u8(51); uint8x16x4_t indices, mask, delta, out; // Translate values 0..63 to the Base64 alphabet. There are five sets: // # From To Abs Index Characters // 0 [0..25] [65..90] +65 0 ABCDEFGHIJKLMNOPQRSTUVWXYZ // 1 [26..51] [97..122] +71 1 abcdefghijklmnopqrstuvwxyz // 2 [52..61] [48..57] -4 [2..11] 0123456789 // 3 [62] [43] -19 12 + // 4 [63] [47] -16 13 / // Create LUT indices from input: // the index for range #0 is right, others are 1 less than expected: indices.val[0] = vqsubq_u8(in.val[0], offset); indices.val[1] = vqsubq_u8(in.val[1], offset); indices.val[2] = vqsubq_u8(in.val[2], offset); indices.val[3] = vqsubq_u8(in.val[3], offset); // mask is 0xFF (-1) for range #[1..4] and 0x00 for range #0: mask.val[0] = vcgtq_u8(in.val[0], vdupq_n_u8(25)); mask.val[1] = vcgtq_u8(in.val[1], vdupq_n_u8(25)); mask.val[2] = vcgtq_u8(in.val[2], vdupq_n_u8(25)); mask.val[3] = vcgtq_u8(in.val[3], vdupq_n_u8(25)); // Subtract -1, so add 1 to indices for range #[1..4], All indices are // now correct: indices.val[0] = vsubq_u8(indices.val[0], mask.val[0]); indices.val[1] = vsubq_u8(indices.val[1], mask.val[1]); indices.val[2] = vsubq_u8(indices.val[2], mask.val[2]); indices.val[3] = vsubq_u8(indices.val[3], mask.val[3]); // Lookup delta values: delta.val[0] = vqtbl1q_u8(lut, indices.val[0]); delta.val[1] = vqtbl1q_u8(lut, indices.val[1]); delta.val[2] = vqtbl1q_u8(lut, indices.val[2]); delta.val[3] = vqtbl1q_u8(lut, indices.val[3]); // Add delta values: out.val[0] = vaddq_u8(in.val[0], delta.val[0]); out.val[1] = vaddq_u8(in.val[1], delta.val[1]); out.val[2] = vaddq_u8(in.val[2], delta.val[2]); out.val[3] = vaddq_u8(in.val[3], delta.val[3]); return out; }
2301_81045437/base64
lib/arch/neon32/enc_translate.c
C
bsd
2,116
#include <stdint.h> #include <stddef.h> #include <string.h> #include "../../../include/libbase64.h" #include "../../tables/tables.h" #include "../../codecs.h" #include "config.h" #include "../../env.h" #ifdef __aarch64__ # if (defined(__ARM_NEON__) || defined(__ARM_NEON)) && HAVE_NEON64 # define BASE64_USE_NEON64 # endif #endif #ifdef BASE64_USE_NEON64 #include <arm_neon.h> // Only enable inline assembly on supported compilers. #if defined(__GNUC__) || defined(__clang__) #define BASE64_NEON64_USE_ASM #endif static BASE64_FORCE_INLINE uint8x16x4_t load_64byte_table (const uint8_t *p) { #ifdef BASE64_NEON64_USE_ASM // Force the table to be loaded into contiguous registers. GCC will not // normally allocate contiguous registers for a `uint8x16x4_t'. These // registers are chosen to not conflict with the ones in the enc loop. register uint8x16_t t0 __asm__ ("v8"); register uint8x16_t t1 __asm__ ("v9"); register uint8x16_t t2 __asm__ ("v10"); register uint8x16_t t3 __asm__ ("v11"); __asm__ ( "ld1 {%[t0].16b, %[t1].16b, %[t2].16b, %[t3].16b}, [%[src]], #64 \n\t" : [src] "+r" (p), [t0] "=w" (t0), [t1] "=w" (t1), [t2] "=w" (t2), [t3] "=w" (t3) ); return (uint8x16x4_t) { .val[0] = t0, .val[1] = t1, .val[2] = t2, .val[3] = t3, }; #else return vld1q_u8_x4(p); #endif } #include "../generic/32/dec_loop.c" #include "../generic/64/enc_loop.c" #include "dec_loop.c" #ifdef BASE64_NEON64_USE_ASM # include "enc_loop_asm.c" #else # include "enc_reshuffle.c" # include "enc_loop.c" #endif #endif // BASE64_USE_NEON64 // Stride size is so large on these NEON 64-bit functions // (48 bytes encode, 64 bytes decode) that we inline the // uint64 codec to stay performant on smaller inputs. void base64_stream_encode_neon64 BASE64_ENC_PARAMS { #ifdef BASE64_USE_NEON64 #include "../generic/enc_head.c" enc_loop_neon64(&s, &slen, &o, &olen); enc_loop_generic_64(&s, &slen, &o, &olen); #include "../generic/enc_tail.c" #else base64_enc_stub(state, src, srclen, out, outlen); #endif } int base64_stream_decode_neon64 BASE64_DEC_PARAMS { #ifdef BASE64_USE_NEON64 #include "../generic/dec_head.c" dec_loop_neon64(&s, &slen, &o, &olen); dec_loop_generic_32(&s, &slen, &o, &olen); #include "../generic/dec_tail.c" #else return base64_dec_stub(state, src, srclen, out, outlen); #endif }
2301_81045437/base64
lib/arch/neon64/codec.c
C
bsd
2,350
// The input consists of five valid character sets in the Base64 alphabet, // which we need to map back to the 6-bit values they represent. // There are three ranges, two singles, and then there's the rest. // // # From To LUT Characters // 1 [0..42] [255] #1 invalid input // 2 [43] [62] #1 + // 3 [44..46] [255] #1 invalid input // 4 [47] [63] #1 / // 5 [48..57] [52..61] #1 0..9 // 6 [58..63] [255] #1 invalid input // 7 [64] [255] #2 invalid input // 8 [65..90] [0..25] #2 A..Z // 9 [91..96] [255] #2 invalid input // 10 [97..122] [26..51] #2 a..z // 11 [123..126] [255] #2 invalid input // (12) Everything else => invalid input // The first LUT will use the VTBL instruction (out of range indices are set to // 0 in destination). static const uint8_t dec_lut1[] = { 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 62U, 255U, 255U, 255U, 63U, 52U, 53U, 54U, 55U, 56U, 57U, 58U, 59U, 60U, 61U, 255U, 255U, 255U, 255U, 255U, 255U, }; // The second LUT will use the VTBX instruction (out of range indices will be // unchanged in destination). Input [64..126] will be mapped to index [1..63] // in this LUT. Index 0 means that value comes from LUT #1. static const uint8_t dec_lut2[] = { 0U, 255U, 0U, 1U, 2U, 3U, 4U, 5U, 6U, 7U, 8U, 9U, 10U, 11U, 12U, 13U, 14U, 15U, 16U, 17U, 18U, 19U, 20U, 21U, 22U, 23U, 24U, 25U, 255U, 255U, 255U, 255U, 255U, 255U, 26U, 27U, 28U, 29U, 30U, 31U, 32U, 33U, 34U, 35U, 36U, 37U, 38U, 39U, 40U, 41U, 42U, 43U, 44U, 45U, 46U, 47U, 48U, 49U, 50U, 51U, 255U, 255U, 255U, 255U, }; // All input values in range for the first look-up will be 0U in the second // look-up result. All input values out of range for the first look-up will be // 0U in the first look-up result. Thus, the two results can be ORed without // conflicts. // // Invalid characters that are in the valid range for either look-up will be // set to 255U in the combined result. Other invalid characters will just be // passed through with the second look-up result (using the VTBX instruction). // Since the second LUT is 64 bytes, those passed-through values are guaranteed // to have a value greater than 63U. Therefore, valid characters will be mapped // to the valid [0..63] range and all invalid characters will be mapped to // values greater than 63. static inline void dec_loop_neon64 (const uint8_t **s, size_t *slen, uint8_t **o, size_t *olen) { if (*slen < 64) { return; } // Process blocks of 64 bytes per round. Unlike the SSE codecs, no // extra trailing zero bytes are written, so it is not necessary to // reserve extra input bytes: size_t rounds = *slen / 64; *slen -= rounds * 64; // 64 bytes consumed per round *olen += rounds * 48; // 48 bytes produced per round const uint8x16x4_t tbl_dec1 = load_64byte_table(dec_lut1); const uint8x16x4_t tbl_dec2 = load_64byte_table(dec_lut2); do { const uint8x16_t offset = vdupq_n_u8(63U); uint8x16x4_t dec1, dec2; uint8x16x3_t dec; // Load 64 bytes and deinterleave: uint8x16x4_t str = vld4q_u8((uint8_t *) *s); // Get indices for second LUT: dec2.val[0] = vqsubq_u8(str.val[0], offset); dec2.val[1] = vqsubq_u8(str.val[1], offset); dec2.val[2] = vqsubq_u8(str.val[2], offset); dec2.val[3] = vqsubq_u8(str.val[3], offset); // Get values from first LUT: dec1.val[0] = vqtbl4q_u8(tbl_dec1, str.val[0]); dec1.val[1] = vqtbl4q_u8(tbl_dec1, str.val[1]); dec1.val[2] = vqtbl4q_u8(tbl_dec1, str.val[2]); dec1.val[3] = vqtbl4q_u8(tbl_dec1, str.val[3]); // Get values from second LUT: dec2.val[0] = vqtbx4q_u8(dec2.val[0], tbl_dec2, dec2.val[0]); dec2.val[1] = vqtbx4q_u8(dec2.val[1], tbl_dec2, dec2.val[1]); dec2.val[2] = vqtbx4q_u8(dec2.val[2], tbl_dec2, dec2.val[2]); dec2.val[3] = vqtbx4q_u8(dec2.val[3], tbl_dec2, dec2.val[3]); // Get final values: str.val[0] = vorrq_u8(dec1.val[0], dec2.val[0]); str.val[1] = vorrq_u8(dec1.val[1], dec2.val[1]); str.val[2] = vorrq_u8(dec1.val[2], dec2.val[2]); str.val[3] = vorrq_u8(dec1.val[3], dec2.val[3]); // Check for invalid input, any value larger than 63: const uint8x16_t classified = vcgtq_u8(str.val[0], vdupq_n_u8(63)) | vcgtq_u8(str.val[1], vdupq_n_u8(63)) | vcgtq_u8(str.val[2], vdupq_n_u8(63)) | vcgtq_u8(str.val[3], vdupq_n_u8(63)); // Check that all bits are zero: if (vmaxvq_u8(classified) != 0U) { break; } // Compress four bytes into three: dec.val[0] = vshlq_n_u8(str.val[0], 2) | vshrq_n_u8(str.val[1], 4); dec.val[1] = vshlq_n_u8(str.val[1], 4) | vshrq_n_u8(str.val[2], 2); dec.val[2] = vshlq_n_u8(str.val[2], 6) | str.val[3]; // Interleave and store decoded result: vst3q_u8((uint8_t *) *o, dec); *s += 64; *o += 48; } while (--rounds > 0); // Adjust for any rounds that were skipped: *slen += rounds * 64; *olen -= rounds * 48; }
2301_81045437/base64
lib/arch/neon64/dec_loop.c
C
bsd
5,205
static BASE64_FORCE_INLINE void enc_loop_neon64_inner (const uint8_t **s, uint8_t **o, const uint8x16x4_t tbl_enc) { // Load 48 bytes and deinterleave: uint8x16x3_t src = vld3q_u8(*s); // Divide bits of three input bytes over four output bytes: uint8x16x4_t out = enc_reshuffle(src); // The bits have now been shifted to the right locations; // translate their values 0..63 to the Base64 alphabet. // Use a 64-byte table lookup: out.val[0] = vqtbl4q_u8(tbl_enc, out.val[0]); out.val[1] = vqtbl4q_u8(tbl_enc, out.val[1]); out.val[2] = vqtbl4q_u8(tbl_enc, out.val[2]); out.val[3] = vqtbl4q_u8(tbl_enc, out.val[3]); // Interleave and store output: vst4q_u8(*o, out); *s += 48; *o += 64; } static inline void enc_loop_neon64 (const uint8_t **s, size_t *slen, uint8_t **o, size_t *olen) { size_t rounds = *slen / 48; *slen -= rounds * 48; // 48 bytes consumed per round *olen += rounds * 64; // 64 bytes produced per round // Load the encoding table: const uint8x16x4_t tbl_enc = load_64byte_table(base64_table_enc_6bit); while (rounds > 0) { if (rounds >= 8) { enc_loop_neon64_inner(s, o, tbl_enc); enc_loop_neon64_inner(s, o, tbl_enc); enc_loop_neon64_inner(s, o, tbl_enc); enc_loop_neon64_inner(s, o, tbl_enc); enc_loop_neon64_inner(s, o, tbl_enc); enc_loop_neon64_inner(s, o, tbl_enc); enc_loop_neon64_inner(s, o, tbl_enc); enc_loop_neon64_inner(s, o, tbl_enc); rounds -= 8; continue; } if (rounds >= 4) { enc_loop_neon64_inner(s, o, tbl_enc); enc_loop_neon64_inner(s, o, tbl_enc); enc_loop_neon64_inner(s, o, tbl_enc); enc_loop_neon64_inner(s, o, tbl_enc); rounds -= 4; continue; } if (rounds >= 2) { enc_loop_neon64_inner(s, o, tbl_enc); enc_loop_neon64_inner(s, o, tbl_enc); rounds -= 2; continue; } enc_loop_neon64_inner(s, o, tbl_enc); break; } }
2301_81045437/base64
lib/arch/neon64/enc_loop.c
C
bsd
1,857
// Apologies in advance for combining the preprocessor with inline assembly, // two notoriously gnarly parts of C, but it was necessary to avoid a lot of // code repetition. The preprocessor is used to template large sections of // inline assembly that differ only in the registers used. If the code was // written out by hand, it would become very large and hard to audit. // Generate a block of inline assembly that loads three user-defined registers // A, B, C from memory and deinterleaves them, post-incrementing the src // pointer. The register set should be sequential. #define LOAD(A, B, C) \ "ld3 {"A".16b, "B".16b, "C".16b}, [%[src]], #48 \n\t" // Generate a block of inline assembly that takes three deinterleaved registers // and shuffles the bytes. The output is in temporary registers t0..t3. #define SHUF(A, B, C) \ "ushr %[t0].16b, "A".16b, #2 \n\t" \ "ushr %[t1].16b, "B".16b, #4 \n\t" \ "ushr %[t2].16b, "C".16b, #6 \n\t" \ "sli %[t1].16b, "A".16b, #4 \n\t" \ "sli %[t2].16b, "B".16b, #2 \n\t" \ "and %[t1].16b, %[t1].16b, %[n63].16b \n\t" \ "and %[t2].16b, %[t2].16b, %[n63].16b \n\t" \ "and %[t3].16b, "C".16b, %[n63].16b \n\t" // Generate a block of inline assembly that takes temporary registers t0..t3 // and translates them to the base64 alphabet, using a table loaded into // v8..v11. The output is in user-defined registers A..D. #define TRAN(A, B, C, D) \ "tbl "A".16b, {v8.16b-v11.16b}, %[t0].16b \n\t" \ "tbl "B".16b, {v8.16b-v11.16b}, %[t1].16b \n\t" \ "tbl "C".16b, {v8.16b-v11.16b}, %[t2].16b \n\t" \ "tbl "D".16b, {v8.16b-v11.16b}, %[t3].16b \n\t" // Generate a block of inline assembly that interleaves four registers and // stores them, post-incrementing the destination pointer. #define STOR(A, B, C, D) \ "st4 {"A".16b, "B".16b, "C".16b, "D".16b}, [%[dst]], #64 \n\t" // Generate a block of inline assembly that generates a single self-contained // encoder round: fetch the data, process it, and store the result. #define ROUND() \ LOAD("v12", "v13", "v14") \ SHUF("v12", "v13", "v14") \ TRAN("v12", "v13", "v14", "v15") \ STOR("v12", "v13", "v14", "v15") // Generate a block of assembly that generates a type A interleaved encoder // round. It uses registers that were loaded by the previous type B round, and // in turn loads registers for the next type B round. #define ROUND_A() \ SHUF("v2", "v3", "v4") \ LOAD("v12", "v13", "v14") \ TRAN("v2", "v3", "v4", "v5") \ STOR("v2", "v3", "v4", "v5") // Type B interleaved encoder round. Same as type A, but register sets swapped. #define ROUND_B() \ SHUF("v12", "v13", "v14") \ LOAD("v2", "v3", "v4") \ TRAN("v12", "v13", "v14", "v15") \ STOR("v12", "v13", "v14", "v15") // The first type A round needs to load its own registers. #define ROUND_A_FIRST() \ LOAD("v2", "v3", "v4") \ ROUND_A() // The last type B round omits the load for the next step. #define ROUND_B_LAST() \ SHUF("v12", "v13", "v14") \ TRAN("v12", "v13", "v14", "v15") \ STOR("v12", "v13", "v14", "v15") // Suppress clang's warning that the literal string in the asm statement is // overlong (longer than the ISO-mandated minimum size of 4095 bytes for C99 // compilers). It may be true, but the goal here is not C99 portability. #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Woverlength-strings" static inline void enc_loop_neon64 (const uint8_t **s, size_t *slen, uint8_t **o, size_t *olen) { size_t rounds = *slen / 48; if (rounds == 0) { return; } *slen -= rounds * 48; // 48 bytes consumed per round. *olen += rounds * 64; // 64 bytes produced per round. // Number of times to go through the 8x loop. size_t loops = rounds / 8; // Number of rounds remaining after the 8x loop. rounds %= 8; // Temporary registers, used as scratch space. uint8x16_t tmp0, tmp1, tmp2, tmp3; __asm__ volatile ( // Load the encoding table into v8..v11. " ld1 {v8.16b-v11.16b}, [%[tbl]] \n\t" // If there are eight rounds or more, enter an 8x unrolled loop // of interleaved encoding rounds. The rounds interleave memory // operations (load/store) with data operations to maximize // pipeline throughput. " cbz %[loops], 4f \n\t" // The SIMD instructions do not touch the flags. "88: subs %[loops], %[loops], #1 \n\t" " " ROUND_A_FIRST() " " ROUND_B() " " ROUND_A() " " ROUND_B() " " ROUND_A() " " ROUND_B() " " ROUND_A() " " ROUND_B_LAST() " b.ne 88b \n\t" // Enter a 4x unrolled loop for rounds of 4 or more. "4: cmp %[rounds], #4 \n\t" " b.lt 30f \n\t" " " ROUND_A_FIRST() " " ROUND_B() " " ROUND_A() " " ROUND_B_LAST() " sub %[rounds], %[rounds], #4 \n\t" // Dispatch the remaining rounds 0..3. "30: cbz %[rounds], 0f \n\t" " cmp %[rounds], #2 \n\t" " b.eq 2f \n\t" " b.lt 1f \n\t" // Block of non-interlaced encoding rounds, which can each // individually be jumped to. Rounds fall through to the next. "3: " ROUND() "2: " ROUND() "1: " ROUND() "0: \n\t" // Outputs (modified). : [loops] "+r" (loops), [src] "+r" (*s), [dst] "+r" (*o), [t0] "=&w" (tmp0), [t1] "=&w" (tmp1), [t2] "=&w" (tmp2), [t3] "=&w" (tmp3) // Inputs (not modified). : [rounds] "r" (rounds), [tbl] "r" (base64_table_enc_6bit), [n63] "w" (vdupq_n_u8(63)) // Clobbers. : "v2", "v3", "v4", "v5", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "cc", "memory" ); } #pragma GCC diagnostic pop
2301_81045437/base64
lib/arch/neon64/enc_loop_asm.c
C
bsd
5,617
static BASE64_FORCE_INLINE uint8x16x4_t enc_reshuffle (const uint8x16x3_t in) { uint8x16x4_t out; // Input: // in[0] = a7 a6 a5 a4 a3 a2 a1 a0 // in[1] = b7 b6 b5 b4 b3 b2 b1 b0 // in[2] = c7 c6 c5 c4 c3 c2 c1 c0 // Output: // out[0] = 00 00 a7 a6 a5 a4 a3 a2 // out[1] = 00 00 a1 a0 b7 b6 b5 b4 // out[2] = 00 00 b3 b2 b1 b0 c7 c6 // out[3] = 00 00 c5 c4 c3 c2 c1 c0 // Move the input bits to where they need to be in the outputs. Except // for the first output, the high two bits are not cleared. out.val[0] = vshrq_n_u8(in.val[0], 2); out.val[1] = vshrq_n_u8(in.val[1], 4); out.val[2] = vshrq_n_u8(in.val[2], 6); out.val[1] = vsliq_n_u8(out.val[1], in.val[0], 4); out.val[2] = vsliq_n_u8(out.val[2], in.val[1], 2); // Clear the high two bits in the second, third and fourth output. out.val[1] = vandq_u8(out.val[1], vdupq_n_u8(0x3F)); out.val[2] = vandq_u8(out.val[2], vdupq_n_u8(0x3F)); out.val[3] = vandq_u8(in.val[2], vdupq_n_u8(0x3F)); return out; }
2301_81045437/base64
lib/arch/neon64/enc_reshuffle.c
C
bsd
988