| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- //
- // Copyright 2026 Aarav Ravindra Kharade
- //
- // Licensed under the Apache License, Version 2.0 (the "License");
- // you may not use this file except in compliance with the License.
- // You may obtain a copy of the License at
- //
- // http://www.apache.org/licenses/LICENSE-2.0
- //
- // Unless required by applicable law or agreed to in writing, software
- // distributed under the License is distributed on an "AS IS" BASIS,
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- // See the License for the specific language governing permissions and
- // limitations under the License.
- //
- // ── Pure-libc utilities replacing Foundation APIs ─────────────────
- /// Read an entire file into a String via fopen/fread (replaces String(contentsOfFile:)).
- public func readFileContents(_ path: String) -> String? {
- guard let fp = fopen(path, "r") else { return nil }
- defer { fclose(fp) }
- var buffer = [UInt8](repeating: 0, count: 8192)
- var result = ""
- while true {
- let n = fread(&buffer, 1, buffer.count, fp)
- if n == 0 { break }
- buffer.withUnsafeBufferPointer { ptr in
- let slice = UnsafeBufferPointer(start: ptr.baseAddress, count: n)
- for byte in slice {
- result.append(Character(UnicodeScalar(byte)))
- }
- }
- }
- return result.isEmpty ? nil : result
- }
- /// Trim whitespace and newlines from both ends of a string (replaces .trimmingCharacters(in:)).
- public func trimWhitespace(_ s: String) -> String {
- var chars = Array(s)
- while let first = chars.first, first == " " || first == "\n" || first == "\r" || first == "\t" {
- chars.removeFirst()
- }
- while let last = chars.last, last == " " || last == "\n" || last == "\r" || last == "\t" {
- chars.removeLast()
- }
- return String(chars)
- }
- /// Simple snprintf-style format for a single Double with one decimal place.
- public func formatDouble(_ value: Double, decimals: Int = 1) -> String {
- let intPart = Int(value)
- var factor = 1
- for _ in 0..<decimals { factor *= 10 }
- let fracPart = abs(Int((value - Double(intPart)) * Double(factor)))
- return "\(intPart).\(fracPart)"
- }
|