디시인사이드 갤러리

갤러리 이슈박스, 최근방문 갤러리

갤러리 본문 영역

Ada 코드 다시..

나르시갤로그로 이동합니다. 2025.07.22 23:58:25
조회 51 추천 1 댓글 0

Ada 코드입니다.


Cada는 C - Ada 바딩인 라이브러리입니다.


재업 완료

ㅋㅋㅋ


여신






with System;

with Interfaces.C;

with Cada.Types;

with Cada.Error;

with sys_stat_h;

with sys_types_h;

with System.Storage_Elements;

with errno_h;

with unistd_h;


package body Cada.File is

  use type Interfaces.C.Int;

  use type Interfaces.C.long;


  function c_open2 (path  : Interfaces.C.Char_Array;

                    flags : Interfaces.C.Int) return File_Descriptor;

  function c_open3 (path  : Interfaces.C.Char_Array;

                    flags : Interfaces.C.Int;

                    mode  : sys_types_h.mode_t) return File_Descriptor;

  pragma import (c, c_open2, "open");

  pragma import (c, c_open3, "open");


  function open (path  : String;

                 flags : File_Flags) return Object is

    new_fd : constant File_Descriptor :=

      c_open2 (Interfaces.C.to_c (path), Interfaces.C.Int (flags));

  begin

    if new_fd = -1 then

      declare

        error_code : constant Interfaces.C.int := Cada.Error.get_errno;

        error_msg  : constant String           :=

          "open(2) failed for path """ & path & """ (errno: " & error_code'image & ")";

      begin

        case error_code is

          when errno_h.EACCES =>

            raise Cada.Error.Permission_Denied with error_msg;

          when errno_h.ENOENT =>

            raise Cada.Error.No_Such_File_Or_Directory with error_msg;

          when errno_h.EEXIST =>

            raise Cada.Error.File_Exists with error_msg;

          when errno_h.EISDIR =>

            raise Cada.Error.Is_A_Directory with error_msg;

          when errno_h.ENOTDIR =>

            raise Cada.Error.Not_A_Directory with error_msg;

          when others =>

            declare

              errno_text : constant String := Cada.Error.get_error_message(error_code);

            begin

              raise Cada.Error.Unknown_Error with errno_text & ": " & error_msg;

            end;

        end case;

      end;

    end if;

    return (Ada.Finalization.Controlled with fd => new_fd);

  end open;


  -- open implementation (3 arguments)

  function open (path  : String;

                 flags : File_Flags;

                 mode  : Cada.Types.File_Mode) return Object is

    new_fd : constant File_Descriptor := c_open3 (Interfaces.C.to_c (path),

                                                  Interfaces.C.Int (flags),

                                                  sys_types_h.mode_t (mode));

  begin

    if new_fd = -1 then

      declare

        error_code : constant Interfaces.C.int := Cada.Error.get_errno;

        error_msg  : constant String           :=

          "open(2) failed for path """ & path & """ (errno: " & error_code'image & ")";

      begin

        case error_code is

          when errno_h.EACCES =>

            raise Cada.Error.Permission_Denied with error_msg;

          when errno_h.ENOENT =>

            raise Cada.Error.No_Such_File_Or_Directory with error_msg;

          when errno_h.EEXIST =>

            raise Cada.Error.File_Exists with error_msg;

          when errno_h.EISDIR =>

            raise Cada.Error.Is_A_Directory with error_msg;

          when errno_h.ENOTDIR =>

            raise Cada.Error.Not_A_Directory with error_msg;

          when others =>

            declare

              errno_text : constant String := Cada.Error.get_error_message(error_code);

            begin

              raise Cada.Error.Unknown_Error with errno_text & ": " & error_msg;

            end;

        end case;

      end;

    end if;

    return (Ada.Finalization.Controlled with fd => new_fd);

  end open;


  procedure close (self : in out Object) is

    result : constant Interfaces.C.int := unistd_h.close (Interfaces.C.Int (self.fd));

  begin

    if result = -1 then

      -- Embed the error handling logic directly.

      declare

        error_code : constant Interfaces.C.int := Cada.Error.get_errno;

        error_msg  : constant String           :=

          "close(2) failed for fd " & self.fd'image &

          " (errno: " & error_code'image & ")";

      begin

        case error_code is

          when errno_h.EBADF => -- Bad file descriptor

            raise Cada.Error.Bad_File_Descriptor with error_msg;

          when errno_h.EINTR => -- Interrupted system call

            raise Cada.Error.Interrupted_System_Call with error_msg;

          when errno_h.EIO =>   -- I/O error

            raise Cada.Error.Input_Output_Error with error_msg;

          when others =>

            declare

              errno_text : constant String := Cada.Error.get_error_message(error_code);

            begin

              raise Cada.Error.Unknown_Error with errno_text & ": " & error_msg;

            end;

        end case;

      end;

    end if;

    self.fd := -1;

  end close;


  function write (self   : in Object;

                  buffer : in System.Storage_Elements.Storage_Array)

    return Natural is

    bytes_written : constant sys_types_h.ssize_t :=

      unistd_h.write (Interfaces.C.Int (self.fd),

                      buffer'address, buffer'length);

  begin

    if bytes_written = -1 then

      -- [!] 오류 처리 로직을 내부에 직접 작성

      declare

        error_code : constant Interfaces.C.int := Cada.Error.get_errno;

        error_msg  : constant String           :=

          "write(2) failed for fd " & self.fd'image &

          " (errno: " & error_code'image & ")";

      begin

        case error_code is

          when errno_h.EBADF => -- Bad file descriptor

            raise Cada.Error.Bad_File_Descriptor with error_msg;

          when errno_h.EPIPE => -- Broken pipe

            raise Cada.Error.Broken_Pipe with error_msg;

          when errno_h.EINTR => -- Interrupted system call

            raise Cada.Error.Interrupted_System_Call with error_msg;

          when errno_h.EAGAIN => -- (or EWOULDBLOCK) Resource temporarily unavailable

            raise Cada.Error.Resource_Temporarily_Unavailable with error_msg;

          when errno_h.EFBIG => -- File too large

            raise Cada.Error.File_Too_Large with error_msg;

          when others =>

            declare

              errno_text : constant String := Cada.Error.get_error_message(error_code);

            begin

              raise Cada.Error.Unknown_Error with errno_text & ": " & error_msg;

            end;

        end case;

      end;

    end if;

    return Natural (bytes_written);

  end write;


  function duplicate (self : in Object) return Object is

    new_fd : constant File_Descriptor :=

      File_Descriptor (unistd_h.dup (Interfaces.C.Int (self.fd)));

  begin

    if new_fd = -1 then

      declare

        error_code : constant Interfaces.C.int := Cada.Error.get_errno;

        error_msg  : constant String           :=

          "dup(2) failed for fd " & self.fd'image &

          " (errno: " & error_code'image & ")";

      begin

        case error_code is

          when errno_h.EBADF =>   -- Bad file descriptor

            raise Cada.Error.Bad_File_Descriptor with error_msg;

          when errno_h.EINTR =>   -- Interrupted system call

            raise Cada.Error.Interrupted_System_Call with error_msg;

          when errno_h.EMFILE =>  -- Per-process limit on open file descriptors reached

            raise Cada.Error.Too_Many_Open_Files with error_msg;

          when others =>

            declare

              errno_text : constant String := Cada.Error.get_error_message(error_code);

            begin

              raise Cada.Error.Unknown_Error with errno_text & ": " & error_msg;

            end;

        end case;

      end;

    end if;


    return (Ada.Finalization.Controlled with fd => new_fd);

  end duplicate;


  function duplicate_to (self   : in Object;

                         new_fd : File_Descriptor)

    return Object is

    result_fd : constant File_Descriptor :=

      File_Descriptor (unistd_h.dup2 (Interfaces.C.Int (self.fd),

                                      Interfaces.C.Int (new_fd)));

  begin

    if result_fd = -1 then

      declare

        error_code : constant Interfaces.C.int := Cada.Error.get_errno;

        error_msg  : constant String           :=

          "dup2(2) failed for old_fd " & self.fd'image & " to new_fd " &

          new_fd'image & " (errno: " & error_code'image & ")";

      begin

        case error_code is

          when errno_h.EBADF => -- Bad file descriptor

            raise Cada.Error.Bad_File_Descriptor with error_msg;

          when errno_h.EINTR => -- Interrupted system call

            raise Cada.Error.Interrupted_System_Call with error_msg;

          when errno_h.EBUSY => -- (Linux-specific) Race condition detected

            raise Cada.Error.Device_Busy with error_msg;

          when others =>

            declare

              errno_text : constant String := Cada.Error.get_error_message(error_code);

            begin

              raise Cada.Error.Unknown_Error with errno_text & ": " & error_msg;

            end;

        end case;

      end;

    end if;


    return (Ada.Finalization.Controlled with fd => result_fd);

  end duplicate_to;


  function umask (new_mask : Cada.Types.File_Mode)

    return Cada.Types.File_Mode is

    mode : constant sys_types_h.mode_t :=

      sys_stat_h.umask (sys_types_h.mode_t (new_mask));

  begin

    return Cada.Types.File_Mode (mode);

  end umask;


  overriding

  procedure finalize (self : in out Object) is

  begin

    if self.fd /= -1 then

      -- finalize에서는 예외를 전파하지 않는 것이 좋으므로,

      -- 오류 발생 가능성이 있는 호출은 블록으로 감쌉니다.

      declare

        result : Interfaces.C.Int :=

          unistd_h.close (Interfaces.C.Int (self.fd));

      begin

        if result /= 0 then

           null; -- 오류를 무시하거나 내부 로그로 기록

        end if;

      end;

      self.fd := -1;

    end if;

  end finalize;


end Cada.File;

추천 비추천

1

고정닉 0

0

댓글 영역

전체 댓글 0
본문 보기

하단 갤러리 리스트 영역

왼쪽 컨텐츠 영역

갤러리 리스트 영역

갤러리 리스트
번호 제목 글쓴이 작성일 조회 추천
설문 반응이 재밌어서 자꾸만 놀리고 싶은 리액션 좋은 스타는? 운영자 25/07/28 - -
AD 휴대폰 액세서리 세일 중임! 운영자 25/07/28 - -
2876107 달리는 열차에는 관성이 붙는당 By 나님 [1] ♥불사신냥덩♥갤로그로 이동합니다. 07.29 27 0
2876106 클로드 이 씹발새기들이 프갤러(49.165) 07.29 50 0
2876105 ❤✨☀⭐⚡☘⛩나님 시작합니당⛩☘⚡⭐☀✨❤ ♥불사신냥덩♥갤로그로 이동합니다. 07.29 22 0
2876104 왜안돼 [1] 아스카영원히사랑해갤로그로 이동합니다. 07.29 45 0
2876103 옛날처럼 위계질서잡힌 집안에서 살아보고싶지않냐? 헬마스터갤로그로 이동합니다. 07.29 40 0
2876102 고속버스터미널 사이트 개좆같네시발 프갤러(211.235) 07.29 31 0
2876101 십새기들 클코 멀티돌리는 새기들때문에 제한 생겼네 ㅇㅇ(211.234) 07.29 27 0
2876100 이더리움 기반 NFT 가치 상승중 ㅇㅅㅇ 어린이노무현갤로그로 이동합니다. 07.29 31 0
2876099 요즘 칼부림이 다시 유행한다도 하는구나 헬마스터갤로그로 이동합니다. 07.29 33 1
2876098 진짜 생산성은 항상 뇌에 여유공간을 남겨놔야 ♥불사신냥덩♥갤로그로 이동합니다. 07.29 28 0
2876097 ❤✨☀⭐⚡☘⛩나님 시작합니당⛩☘⚡⭐☀✨❤ ♥불사신냥덩♥갤로그로 이동합니다. 07.29 21 0
2876096 나님 홧실히 잠 푹자니 하루종일 퍼포넌스 장난 아님 ㄷㅅㄷ ♥불사신냥덩♥갤로그로 이동합니다. 07.29 28 0
2876094 현재 회사가 안좋은곳인지는 테스트 환경으로 판단가능 프갤러(211.58) 07.29 37 0
2876093 한국 대기업 외국으로 이전 현실화 ♥불사신냥덩♥갤로그로 이동합니다. 07.29 30 0
2876092 외국계 기업들 한국 떠난다 초읽기 한국경제 절망적 상황 ♥불사신냥덩♥갤로그로 이동합니다. 07.29 30 0
2876091 좆소 개발자 연봉 [2] 프갤러(119.244) 07.29 89 0
2876090 뉴프로에 ai도입하고 비용 폭증했다 [4] 헬마스터갤로그로 이동합니다. 07.29 56 0
2876089 회사 복포 150만원 모인 걸로 [1] 아스카영원히사랑해갤로그로 이동합니다. 07.29 36 0
2876088 경찰에 신고합니다 ♥불사신냥덩♥갤로그로 이동합니다. 07.29 34 0
2876087 raspberrypi baremetal x86 emul faux86 발명도둑잡기(118.216) 07.29 23 0
2876086 raspberry pi bare metal library 발명도둑잡기(118.216) 07.29 25 0
2876085 else좀 쓰지마 제에발 [9] 프갤러(119.244) 07.29 97 0
2876084 더워서 컨디견 조절이 힘들다 [3] 개멍청한유라갤로그로 이동합니다. 07.29 46 0
2876083 2찢명 관세협상 폭망한 이유:협상이고 뭐고 감옥 안 갈려고 발악중 ♥불사신냥덩♥갤로그로 이동합니다. 07.29 33 0
2876082 뉴프로 요즘 많이발전했더러 [5] 헬마스터갤로그로 이동합니다. 07.29 64 0
2876081 광고들어가고 찐) [1] 넥도리아(106.101) 07.29 35 0
2876080 친중극좌새끼들 윤석열대통령 탄압하다 좃되게 생김 ㄷㅅㄷ ♥불사신냥덩♥갤로그로 이동합니다. 07.29 43 0
2876079 장기간 유지되던 경쟁관계의 순위가 바뀌는 시기나 분위기, 계기 특징 발명도둑잡기(118.216) 07.29 102 0
2876078 인간을 생체 대이터센터로 만드는 기술 개발즁⭐ ♥불사신냥덩♥갤로그로 이동합니다. 07.29 32 0
2876077 418번길 [1] 넥도리아(223.38) 07.29 36 0
2876076 대공황 ♥불사신냥덩♥갤로그로 이동합니다. 07.29 32 0
2876075 김건모-내가 그댈 느끼는 만큼 발명도둑잡기(118.216) 07.29 19 0
2876074 소비쿠폰을 돈으로 만드는 법 발명도둑잡기(118.216) 07.29 72 0
2876073 ai때문에 현타와서 코딩 놓은지 좀 됐는데 [1] ㅇㅇ(118.235) 07.29 122 0
2876072 늑대와 개 유전자 갯수 차이 교배 방법 발명도둑잡기(118.216) 07.29 24 0
2876071 데이터복구 IMMOU 넥도리아(223.38) 07.29 31 0
2876070 소비쿠폰=로또 4등 세번 당첨 발명도둑잡기(118.216) 07.29 24 0
2876069 연봉 1억 넘으면 배급권은 나눔해야지 ㅇㅇ(49.165) 07.29 33 0
2876068 련봉1억따리가 이런거 살수 있슴? ㅇㅇ(223.38) 07.29 47 0
2876067 생물학에서 변종이 원래의 종을 역전하는 경우 연구 발명도둑잡기(118.216) 07.29 40 0
2876066 병렬프로그래밍도 좀 공부하고 그래라 프갤러(122.43) 07.29 58 0
2876065 다리 찢기 발명도둑잡기(118.216) 07.29 29 1
2876064 오늘의 발명 실마리: 에어콘 쏘이는 영역 줄이는 실내용 텐트 발명도둑잡기(118.216) 07.29 28 0
2876063 소비쿠폰 149400원을 어디에 쓸 것인가 [1] 발명도둑잡기(118.216) 07.29 41 0
2876062 AI시대에 숫자 3개 정렬한다고 꼬박 5시간 고민하는게 맞는거냐?? [1] ㅇㅇ(223.38) 07.29 59 0
2876061 본인 AI구독 ㅁㅌㅊ? 일이삼123갤로그로 이동합니다. 07.29 63 0
2876060 개쩌는 서비스 아이디어 떠올랐다. 뭐냐면 [5] ㅇㅇ(211.235) 07.29 77 0
2876058 이.. 이대로 가면.. ♥불사신냥덩♥갤로그로 이동합니다. 07.29 49 0
2876056 4mat - paper dolls 배구공(119.202) 07.29 37 0
2876054 외국인 보험비 유출 < 주한미군 방위비 일본, 괌, 하와이 유출 발명도둑잡기(118.216) 07.29 25 0
뉴스 유병재, 사진 한 장에 고소 당할 위기…네티즌 “선처없다” 디시트렌드 07.30
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

뉴스

디시미디어

디시이슈

1/2