SPB Git

Repository Public

Segments.swift 7.8 KB 167 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : MacLustr SMS Gateway9// File             : ios/MacLustrSMS/Core/Segments.swift10// Description      : Découpage d'un SMS en segments, identique au serveur11//                    (backend/src/security/segments.ts) : GSM 7 bits +12//                    extension, UCS-2.13// Module           : ios14// Repository       : https://git.spboucher.ai/maclustr-sms15// Project Website  : https://sms.spboucher.ai16// Created          : 2026-11-3017// Last Modified    : 2026-11-3018//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author           : Simon-Pierre Boucher24// Position         : Professor of Finance25// Institution      : Université du Québec en Outaouais (UQO)26// Department       : Département des sciences administratives27// Organization     : SP Boucher28//29// Website          : https://spboucher.ai30// Git              : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General          : info@spboucher.ai37// Professional     : contact@spboucher.ai38// Direct           : simon@spboucher.ai39// Research         : research@spboucher.ai40// Development      : dev@spboucher.ai41// Support          : support@spboucher.ai42// Security/Admin   : admin@spboucher.ai43// Notifications    : notifications@spboucher.ai44//45// Preferred Contact: admin@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification   : Public70// Distribution     : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License          : None specified (no license file in this repository)84// Maintainer       : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import Foundation9293enum SMSEncoding: String, Sendable { case gsm7, ucs2 }9495struct SegmentInfo: Equatable, Sendable {96    let encoding: SMSEncoding97    let characters: Int      // caractères visibles98    let units: Int           // septets (GSM) ou unités UTF-16 (UCS-2)99    let segments: Int100    let perSegment: Int101    var remainingInSegment: Int { segments * perSegment - units }102}103104/// Un caractère qui force le passage en Unicode, avec le remplacement GSM proposé quand il en existe un.105struct UnicodeOffender: Equatable, Identifiable, Sendable {106    let character: Character107    let count: Int108    let replacement: String?109    var id: String { String(character) }110}111112enum Segments {113    static let maxSegments = 10114    static let basic: Set<Character> = Set("@£$¥èéùìòÇ\nØø\rÅåΔ_ΦΓΛΩΠΨΣΘΞÆæßÉ !\"#¤%&'()*+,-./0123456789:;<=>?¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà")115    static let ext: Set<Character> = Set("^{}\\[~]|€\u{0C}")116117    /// Remplacements sans perte de sens vers l'alphabet GSM (typographie « intelligente » des claviers, espaces spéciales, lettres accentuées absentes).118    static let replacements: [Character: String] = [119        "’": "'", "‘": "'", "‚": ",", "“": "\"", "”": "\"", "„": "\"", "«": "\"", "»": "\"",120        "–": "-", "—": "-", "‑": "-", "…": "...", "\u{00A0}": " ", "\u{202F}": " ", "\u{2009}": " ", "•": "-", "·": ".",121        "ê": "e", "ë": "e", "â": "a", "á": "a", "ã": "a", "î": "i", "ï": "i", "í": "i", "ô": "o", "ó": "o", "õ": "o", "û": "u", "ú": "u", "ç": "c",122        "À": "A", "Â": "A", "È": "E", "Ê": "E", "Ë": "E", "Î": "I", "Ï": "I", "Ô": "O", "Ù": "U", "Û": "U", "œ": "oe", "Œ": "OE", "°": "o", "™": "TM", "©": "(c)", "®": "(R)",123    ]124125    static func info(_ text: String) -> SegmentInfo {126        var gsm = true, septets = 0127        // Le serveur itère par point de code : un caractère composé (émoji, lettre + accent combinant) n'est jamais dans l'alphabet GSM.128        for scalar in text.unicodeScalars {129            let ch = Character(scalar)130            if basic.contains(ch) { septets += 1 } else if ext.contains(ch) { septets += 2 } else { gsm = false; break }131        }132        let chars = text.unicodeScalars.count133        if gsm {134            let segments = septets <= 160 ? 1 : Int((Double(septets) / 153).rounded(.up))135            return SegmentInfo(encoding: .gsm7, characters: chars, units: septets, segments: max(segments, 1), perSegment: septets <= 160 ? 160 : 153)136        }137        let units = text.utf16.count138        let segments = units <= 70 ? 1 : Int((Double(units) / 67).rounded(.up))139        return SegmentInfo(encoding: .ucs2, characters: chars, units: units, segments: max(segments, 1), perSegment: units <= 70 ? 70 : 67)140    }141142    /// Les caractères hors alphabet GSM, dans l'ordre de première apparition.143    static func offenders(_ text: String) -> [UnicodeOffender] {144        var order: [Character] = [], counts: [Character: Int] = [:]145        for ch in text where !isGSM(ch) {146            if counts[ch] == nil { order.append(ch) }147            counts[ch, default: 0] += 1148        }149        return order.map { UnicodeOffender(character: $0, count: counts[$0]!, replacement: replacements[$0]) }150    }151    static func isGSM(_ ch: Character) -> Bool { ch.unicodeScalars.count == 1 && (basic.contains(ch) || ext.contains(ch)) }152153    /// Applique tous les remplacements connus ; les caractères sans équivalent (émoji…) sont laissés tels quels.154    static func simplified(_ text: String) -> String {155        var out = ""156        for ch in text { if !isGSM(ch), let r = replacements[ch] { out += r } else { out.append(ch) } }157        return out158    }159    /// Ce que coûte le passage en Unicode : segments actuels contre segments si le texte était ramené à l'alphabet GSM.160    static func savings(_ text: String) -> (now: Int, simplified: Int)? {161        let now = info(text)162        guard now.encoding == .ucs2 else { return nil }163        let s = info(simplified(text))164        return s.encoding == .gsm7 ? (now.segments, s.segments) : nil165    }166}167
Files main
Menu

Theme